Sonoff Ifan04 - ESPHome working code

Hi Higel, Thank you. I also tried swapping TX and RX several times and I always used Tasmotizer, but unfortunately didn’t work. It was like the device didn’t accept coms on the exposed pins. I also tried with the pads underneath.
Starting with the button pressed obviously was doing something, as It didn’t beep or flash the led.

Do you remember if putting your into flash mode did anything like flashing the led even if it was once?

I can’t say that I remember, but I do remember keeping the button pressed through-out the entire flashing process.

Have a gander at this page that was recommended by people in the Tasmoto chat Getting Started - Tasmota

I was having many issues flashing mine. I would suggest testing the device first with esptool: Releases · espressif/esptool · GitHub

Check flash (Useful to get the flash size for the second command 1M etc):

Nix

esptool --port /dev/ttyUSB1 flash_id

or Windows

esptool --port COM4 flash_id

Should spit out something like this:

esptool.py v2.8
Serial port /dev/ttyUSB1
Connecting....
Detecting chip type... ESP8266
Chip is ESP8285
Features: WiFi, Embedded Flash
Crystal is 26MHz
MAC: xx:xx:xx:xx:xx:xx
Enabling default SPI flash mode...
Manufacturer: 5e
Device: 3214
Detected flash size: 1MB
Hard resetting via RTS pin...

A fail will look like this:

esptool.py v2.8
Serial port /dev/ttyUSB0
Connecting........_____....._____....._____....._____....._____....._____....._____

A fatal error occurred: Failed to connect to Espressif device: Timed out waiting for packet header

Once you get a success you can then dump the firmware with:

sudo chmod +x esptool
./esptool --port /dev/ttyUSB0--baud 921600 read_flash 0x00000 0x100000 ifan04lfwbackup001-1.bin

Which should then look something like this:

esptool.py v3.3.2
Serial port /dev/ttyUSB0
Connecting...
Detecting chip type... Unsupported detection protocol, switching and trying again...
Connecting...
Detecting chip type... ESP8266
Chip is ESP8285N08
Features: WiFi, Embedded Flash
Crystal is 26MHz
MAC: xx:xx:xx:xx:xx:xx
Stub is already running. No upload is necessary.
Changing baud rate to 921600
Changed.
1048576 (100 %)
1048576 (100 %)
Read 1048576 bytes at 0x0 in 16.7 seconds (501.9 kbit/s)...
Hard resetting via RTS pin...

If that is not working with your USB to TTL just remove the --baud line so it will default back to 115200.

You should dump the firmware twice and compare just for a sanity check. (If you ever care about returning the worst beeping firmware on earth)

md5sum ifan04lfwbackup001-1.bin
cb5b29008c9459e4014ffdaa12537c94  ifan04lfwbackup001-1.bin
md5sum ifan04lfwbackup001-2.bin
cb5b29008c9459e4014ffdaa12537c94  ifan04lfwbackup001-2.bin

I was having multiple issues. First issue was I was using an FT232RL (not fake) but had no voltage regulator on the board. I think this board consumes a lot of mW with the two radio IC etc.

I ended up wiring it to VAC (Not recommended for safety reasons in the documentation above) then just using TX to TX, RX to RX (Thanks above) and Ground only. Which started dumping the firmware but then would die at 40%.

You can also test if your getting any console data with Putty or Minicom as the device will dump a version line to the serial console when you hold the button down while powered and not synced to the eWeLink app yet (“DIY mode” gets activated with an ad-hoc AP. Check out sonoff.tech/diy-developer for more information about the process. The blurb about the other device seems to work with this one when you hold the sync button down on the 433 remote as well I think).

Serial Console:

FWFAN-XXXXXXXXMCU-IFAN04-XXXXXXXXX v1.1.0

I then bought the recommended USB adapter with the CH340G and an external LDO regulator from that Tasmoto article above from AliExpress for a few dollars (Don’t just grab any CH340G from Ali as some of the boards are garbage with no external LDO. I haven’t got it yet but I remembered I had a second device an ESP-Prog so I hooked that up and at first it had an error:

A fatal error occurred: ESP8266 ROM does not support function read_flash.

This was caused from Debian’s old apt esptool version 2.8. After grabbing the one from the github repo above 3+ it worked fine.

I remembered in the past I also had issues with the laptop dock (USB C) when it’s charging the laptop. I can’t get programmers to flash the ESP for some reason. (USB2TTL plugged into the side of the laptop not the dock) Maybe it’s noisy or something. Soon as I unplug the laptop from power it flashes fine.

So there’s some more food for thought. Try a different computer / programmer / get solid power to it / make sure everything shares the same ground plane.

I just bought my iFan04 a week ago. They are on firmware 3.5 from Sonoff (latest) and still read the flash fine. So your unit age should be ok as well (I had this same concern). People in the Tasmoto chat said there is pretty much nothing Sonoff could do with the firmware to prevent flashing an esp82xx.

Also your question about holding the button down. Your 5 seconds should be fine but maybe you are also activating the “DIY mode” if not power cycling properly. Check if there is a WiFi itead SSID near you. I hold the button down, then flick the power bar on, then count to 2 or 3, then let go, then test with esptool flash id command. (This is of course with no 3v3 connected from the TTL Adapter / ie VAC power)

Otherwise if I had a decent external LDO without VAC attached. I would go: Hold button down, plug in USB, do the count, let go, test the flash.

Note the quality control on Sonoff gear may not be the best… The transformer leads on the back of my board were not removed and touching each other (I’m glad I never plugged it in before taking it apart).

I also had to remove half a mm off both sides with the sanding dremel tool to fit it in the fan bracket mount housing.

Could you not use the SDA/SCL at the top of the board for your extra IO requirements?

Edit: SDA/SCL at the top of the board is connected to the RF module (PIN10(SCL) and PIN9(SDA) of OB38R08 chip) and not the ESP :frowning:

You could technically attach an I2C I/O expander IC there as well maybe. And just plug the standard default light switch direct into it for a super cheap control option.

I was thinking you could add dimming to the unit with something like this. (space willing) pass the iFan04 light relay wire into it then out to the fan light wire. Attach the I2C wires to the Sonoff I2C port at the top of the board.

1 Like

Thank you NonaSuomy for your very informative reply.

That’s the output I’m always getting from esptool. There’s no communication.
I’ve tried several adapters, the d-sun-v30, the yp-01 (that became trashed by the driver when plugged into a w10 laptop), a cp2102 and that one for esp01.
With their own power supply, with mains and only wiring ground, and also powering the board with a lab PSU.
Always same results. Linux and Windows. The firmware version is also 3.5. So I’m using it with their platform and the HA integration for Sonoff.

I wrote here in case there was a known issue or knowledge of the brand locking these boards.

They recommend this specific “Gold” Adapter with a CH340G and external 3v3 LDO on the board: https://www.aliexpress.com/item/32761423124.html
to do any of your device flashing with. Not the CP2102 I’ve had these cheap boards fry my esp’s just from unplugging the laptop from AC be careful. Do your USB to TTL boards have a 3v3 LDO Regulator on them? Can you show a link or picture to the one you are using? This is the part circled in red that should be on the TTL boards to supply power to this hungry fan controller board.

Did you try a completely different computer plugged into AC and not plugged into AC? (Not just dual booting from Windows to Linux)

If you order that one above and then want to try again in the future it’s super easy to do so. I wanted to test their platform out so I understood how it worked before the flashing of custom firmware. Just click the fan in the eWeLink app then click the top right settings button then delete the device from there. It will factory reset it and be back to beeping with no config. Though maybe it shouldn’t matter weather it’s paired or not as it should still just work even then.

As said above they haven’t “Locked” them and apparently it’s improbable. They would probably loose a ton of business if they could.

My main computer, the linux equipped, is a desktop one. A big-ugly naked gaming :poop: that I use for everything else but gaming.
I borrowed “the woman at charge’s” laptop with W10 for the try.

The only serial converter I have with it’s own regulator appears to be the one I use for esp01s. I tried with it, just matching the cables with no success.


The one in the right is the one that I used most. I soldered cables to be sure it wasn’t a problem with the proto-cables.

I have another fan to make smart, so I’ll be ordering another sonoff to try with. And I’ll buy the adapter you posted. Many thanks.

@cpyarger can you please add this simple pull request?

I was having the same issue with the nonstop beeeeeeeeep on boot and it fixed it.

Thank you.

Indeed the Yellow connector one seems to be the only one with an LDO Regulator. Maybe it’s not supplying enough mW for this board. Maybe remove your soldering and clean up any residue and just hold the connectors in the holes. Maybe the TX/RX lines are shorted in someway. On the next one you get just attach the programming leads to a 4 pin header and hold them in there with some pressure on a slight angle and see if you are first getting communication with that version number above that dumps to the console on boot in Putty/Minicom with the factory firmware for a sanity check.

I have 2 more units to do. I will attempt to do them with no VAC attached and just the ESP-Prog. It has an LDO as well. The firmware uploaded and is now functioning on this first unit. :partying_face:

Speeds 1 and 2 seem to be pretty slow hopefully there is an adjustment for that. Speed 2 seems like speed 1 when tested with the other same model fan.

I wish the relays properly interfaced with the switch harness plugs instead of just the single fan lead. As I noticed a bit more of a hum from the fan when it used to be completely silent before.

My light seems to randomly flick on and off for some reason also not sure what that’s about yet.

Can’t get the remote to work yet turned it to : true didn’t seem to help. Has anyone got the remote working with @cpyarger codebase?

I didn’t actually know what those where (I saw them after I purchased them and was trying to flash the firmware as I thought they where the serial pins). The original reason I planned on using the pins from the button (while keeping the existing button in place) is because I plan on butting a button on it so it would work great. Could those pins meant for I2C work as normal gpio?

I actually just figured out the remote… The manual’s instructions are technically correct just kinda confusing… They tell you to press any button on the remote within 5 seconds of power on. Which made sense to me but my understanding of power on was power into the module (mains power). Turns out they meant power to the remote… So pull the battery out and put it back in. Within 5 seconds of it being back in press a button. It should now be paired.

I only have one fan installed currently but when I get more installed I dont know how it is going to know which of the fans to pair too. Hopefully it will pair with only power from a serial interface and I can just go way outside the range of any of the fans and pair it there. But I guess that is another problem for another day…

Yup they are also known as GPIO04 (SDA) and GPIO05 (SCL).

Seems he has the same idea as he has the fan controller there in the video too :slight_smile:

You can also just use the button on the case to test with as it currently just turns the light on and off.

esp8266-chip-pinout

Hmm are you using @cpyarger code above or the previous stuff? (I’m wondering if it’s supported in his code as it is defaulted to disabled so maybe it wasn’t working yet?)

I tried your pulling the battery sequence but no go still. :sob:

Yes I am using @cpyarger’s code (technically a fork of it that I made so I can merge in the buzzer fix and make some changes I want) and the config I am using (for the remote) in esphome is as follows.

# Disable logging on serial as it is used by the remote
logger:
  baud_rate: 0

#ifan04:
#  on_fan:
#    - lambda: |-
#          auto call = speed ? id (the_fan).turn_on() :  id (the_fan).turn_off();
#          call.set_speed(speed);
#          call.perform();
#  on_light:
#    - light.toggle: fan_light
ifan04:
  on_fan:
    - lambda: ESP_LOGD("IFAN04", "speed is %d", speed);
  on_light:
    - lambda: ESP_LOGD("IFAN04", "light trigger");
  on_buzzer:
    - lambda: ESP_LOGD("IFAN04", "buzzer trigger");

uart:
  tx_pin: GPIO01
  rx_pin: GPIO03
  baud_rate: 9600

Currently it just logs stuff out as I just got it working. But the commented out stuff is from the config that @cpyarger posted to go with the code and should match the buttons on the remote.

It is worth noting that remote_enable option (next to the buzzer_enable) on the ifan fan needs to be false. There is a separate module for the ifan04’s remote (see above config)

Hmm still no go does everything look fine here?

I enabled debug: under uart: and it shows nothing in the wifi log while pressing buttons. Does the remote circuit work when there is only 3v3 from the usb2ttl plugged in (no AC)?

substitutions:
  name: ifan-bedroom-001
  friendly_name: Master Bedroom Fan

external_components:
  - source: github://hfuller/custom_components@master
    refresh: 0s

esphome:
  name: ${name}
  comment: Sonoff iFan04-L
  # This will allow for (future) project identification,
  # configuration and updates.
  project:
    name: cpyarger.sonoff-ifan04-l
    version: "1.0"

esp8266:
  board: esp01_1m

# Disable logging on serial as it is used by the remote
logger:
  baud_rate: 0

# Enable Home Assistant API
api:
  services:
    - service: fan_cycle
      then:
        - fan.cycle_speed: the_fan
  encryption:
    key: !secret encryption_key001

ota:
  password: !secret ota_pass001

uart:
  tx_pin: GPIO01
  rx_pin: GPIO03
  baud_rate: 9600
  debug:

dashboard_import:
  package_import_url: github://cpyarger/esphome-templates/sonoff-ifan04-l.yaml@main

captive_portal:

binary_sensor:
  - platform: gpio
    id: button_light
    pin: GPIO0
    on_press:
      then:
        - light.toggle: fan_light

output:
  - platform: esp8266_pwm
    id: led_pin
    pin: GPIO13
    inverted: true

light:
  - platform: ifan
    id: fan_light
    name: "${friendly_name} Light"
  - platform: monochromatic
    id: led1
    output: led_pin
    default_transition_length: 0s
    restore_mode: always off

button:
  - platform: template
    name: ${friendly_name} Cycle Fan
    on_press:
      then:
        - fan.cycle_speed: the_fan

fan:
  - platform: ifan
    id: the_fan
    name: "${friendly_name} Fan"
    remote_enable: false  
    buzzer_enable: false

ifan04:
  on_fan:
    - lambda: |-
          auto call = speed ? id (the_fan).turn_on() :  id (the_fan).turn_off();
          call.set_speed(speed);
          call.perform();
          ESP_LOGD("IFAN04", "speed is %d", speed);
  on_light:
    - light.toggle: fan_light
    - lambda: ESP_LOGD("IFAN04", "light trigger");
  on_buzzer:
    - lambda: ESP_LOGD("IFAN04", "buzzer trigger");

wifi:
  ssid: !secret wifi_ssid
  password: !secret wifi_password
  use_address: !secret use_address001
  # Enable fallback hotspot (captive portal) in case wifi connection fails
  ap:
    ssid: "Ifan04-001 Fallback Hotspot"
    password: !secret fallbackhotspot001

web_server:

Did you pair the remote before or after adding ESPHome to the device?

Maybe I will try to flash it back to the factory firmware and try to pair it from there…

./esptool --chip esp8266 -p /dev/ttyUSB1 write_flash 0x0 ifan04lfwbackup001-1.bin

Yay I got it!

[04:07:36][D][uart_debug:158]: <<< "\xAAU\x01\x04\x00\x01\x04\n"
[04:07:36][D][light:035]: 'Master Bedroom Fan Light' Setting:
[04:07:36][D][light:046]:   State: ON
[04:07:36][D][IFAN04:101]: light trigger
[04:07:37][D][uart_debug:158]: <<< "\xAAU\x01\x04\x00\x01\x04\n"
[04:07:37][D][light:035]: 'Master Bedroom Fan Light' Setting:
[04:07:37][D][light:046]:   State: OFF
[04:07:37][D][IFAN04:101]: light trigger

You have to have VAC connected or the 433MHz receiver won’t listen.
You have to hit the button on the remote while the fan controller first starts from being plugged into VAC. (Battery thing didn’t work)

I paired it with the stock firmware reflashed to the device (yay my backup worked).

After flashing ESPHome back it also kept the pair (So the pair is kept on the 433MHz receiver. Nothing to do with the ESP).

I will try to pair the 3rd controller from ESPHome now that I know what I’m doing.

Both bottom buttons on the remote are the same for some reason :frowning: would have been nice to have two different extra buttons to use for something fun.

Left bottom:

|04:28:28|[D]|[ifan04:077]|unknown command type 1 param 2|
|04:28:28|[D]|[uart_debug:158]|<<< "\xAAU\x01\x01\x00\x01\x02\x05"|

Right bottom:

|04:28:30|[D]|[ifan04:077]|unknown command type 1 param 2|
|04:28:30|[D]|[uart_debug:158]|<<< "\xAAU\x01\x01\x00\x01\x02\x05"|

Edit: Tried from ESPHome and it worked as well.

Not sure if it’s just my fan but I seem to have to enable multiple capacitors in the fan to make the medium/high speed work properly. My low speed was basically the same as my medium speed. If you have this same issue you may need to enable multiple relays in the controller code.

You can make the changes at your own risk by editing this file after forking the github then editing the file below then change hfuller/cpyarger/ssieb in your yaml include to your own github name.

ssieb made the RF433 code.
cpyarger modified that.
hfuller fixed the annoying beep on boot.
nonasuomy (mine was forked from the hfuller code) Note: Capacitor changes.

void IFan::set_med() {
  digitalWrite(relay_1, HIGH);
  digitalWrite(relay_2, HIGH);
  digitalWrite(relay_3, LOW);
  beep(2);
}
void IFan::set_high() {
  digitalWrite(relay_1, HIGH);
  digitalWrite(relay_2, LOW);
  digitalWrite(relay_3, HIGH);

  beep(3);
}

No changes really.

substitutions:
  name: ifan-bedroom-001
  friendly_name: Master Bedroom

external_components:
  - source: github://nonasuomy/custom_components@master
    refresh: 0s

esphome:
  name: ${name}
  comment: Sonoff iFan04-L
  # This will allow for (future) project identification,
  # configuration and updates.
  project:
    name: cpyarger.sonoff-ifan04-l
    version: "1.0"

esp8266:
  board: esp01_1m

# Disable logging on serial as it is used by the remote
logger:
  baud_rate: 0

# Enable Home Assistant API
api:
  services:
    - service: fan_cycle
      then:
        - fan.cycle_speed: the_fan
  encryption:
    key: !secret encryption_key001

ota:
  password: !secret ota_pass001

uart:
  tx_pin: GPIO01
  rx_pin: GPIO03
  baud_rate: 9600
  #debug:

dashboard_import:
  package_import_url: github://cpyarger/esphome-templates/sonoff-ifan04-l.yaml@main

captive_portal:

binary_sensor:
  - platform: gpio
    id: button_light
    pin: GPIO0
    on_press:
      then:
        - light.toggle: fan_light

output:
  - platform: esp8266_pwm
    id: led_pin
    pin: GPIO13
    inverted: true

light:
  - platform: ifan
    id: fan_light
    name: "${friendly_name} Light"
  - platform: monochromatic
    id: led1
    output: led_pin
    default_transition_length: 0s
    restore_mode: always off

button:
  - platform: template
    name: ${friendly_name} Cycle Fan
    on_press:
      then:
        - fan.cycle_speed: the_fan

fan:
  - platform: ifan
    id: the_fan
    name: "${friendly_name} Fan"
    remote_enable: false  
    buzzer_enable: false

ifan04:
  on_fan:
    - lambda: |-
          auto call = speed ? id (the_fan).turn_on() :  id (the_fan).turn_off();
          call.set_speed(speed);
          call.perform();
  on_light:
    - light.toggle: fan_light

wifi:
  ssid: !secret wifi_ssid
  password: !secret wifi_password
  use_address: !secret use_address001
  # Enable fallback hotspot (captive portal) in case wifi connection fails
  ap:
    ssid: "Ifan04-001 Fallback Hotspot"
    password: !secret fallbackhotspot001

web_server:

This is a nice button row for this fan controller instead of a bogus slider/toggle:

Documentation settings:

hacs → frontend → + Explore & Download Repositories → Fan Percent Button Row → Download

Add Card → Manual (at the bottom) → Card Configuration (Make sure to remove type: ‘’ default entry) then paste:

type: entities
title: Bedroom Fans
show_header_toggle: false
entities:
  - entity: light.master_bedroom_light
  - entity: fan.master_bedroom_fan
    type: custom:fan-percent-button-row
    name: Master Bedroom
    reverseButtons: true
    customTheme: true
    isOnLowColor: rgb(255, 0, 0)
    isOnMedColor: '#888888'
    isOnHiColor: '#222222'
    buttonInactiveColor: '#aaaaaa'
    isOffColor: purple

image

1 Like

Thanks to everyone here I now have my ifan04 working through esphome. An added step I have is to use an openhasp display/switch to control the fan. For anyone else that needs it,I mimic the buttons in the fan percent row card

IMG_5173 Small

Here is the code:

plate jsonl


{"page":1,"id":10,"obj":"btn","x":5,"y":30,"w":55,"h":55,"toggle":true,"text":"\uE210 Off","text_font":24,"mode":"break","align":1}
{"page":1,"id":11,"obj":"btn","x":65,"y":30,"w":55,"h":55,"toggle":true,"text":"\uE210 Low","text_font":24,"mode":"break","align":1}
{"page":1,"id":12,"obj":"btn","x":125,"y":30,"w":55,"h":55,"toggle":true,"text":"\uE210 Med","text_font":24,"mode":"break","align":1}
{"page":1,"id":13,"obj":"btn","x":185,"y":30,"w":55,"h":55,"toggle":true,"text":"\uE210 High","text_font":24,"mode":"break","align":1}

configuration yaml

    - obj: "p1b10"
      properties:
        "val": '{{ 1 if states("fan.bedroom_fan") == "on" else 0 }}'
        "text": '{{ "\uE210 On" if is_state("fan.bedroom_fan", "on") else "\uE210 Off" | e }}'
      event:
        "down":
          - service: homeassistant.toggle
            entity_id: "fan.bedroom_fan"
          - service: fan.set_percentage
            entity_id: "fan.bedroom_fan"
            data:
              percentage: 0
    - obj: "p1b11"
      properties:
        "val": '{{1 if states("fan.bedroom_fan") == "on" and is_state_attr("fan.bedroom_fan", "percentage", 33) else 0 }}'
        "text": '{{ "\uE210 Low" if is_state("fan.bedroom_fan", "on") else "\uE210 Low" | e }}'
      event:
        "down":
          - service: fan.set_percentage
            entity_id: "fan.bedroom_fan"
            data:
              percentage: 33
          - service: homeassistant.turn_on
            entity_id: "fan.bedroom_fan"
    - obj: "p1b12"
      properties:
        "val": '{{1 if states("fan.bedroom_fan") == "on" and is_state_attr("fan.bedroom_fan", "percentage", 66) else 0 }}'
        "text": '{{ "\uE210 Med" if is_state("fan.bedroom_fan", "on") else "\uE210 Med" | e }}'
      event:
        "down":
          - service: fan.set_percentage
            entity_id: "fan.bedroom_fan"
            data:
              percentage: 66

    - obj: "p1b13"
      properties:
        "val": '{{1 if states("fan.bedroom_fan") == "on" and is_state_attr("fan.bedroom_fan", "percentage", 100) else 0 }}'
        "text": '{{ "\uE210 High" if is_state("fan.bedroom_fan", "on") else "\uE210 High" | e }}'
      event:
        "down":
          - service: fan.set_percentage
            entity_id: "fan.bedroom_fan"
            data:
              percentage: 100
          - service: homeassistant.turn_on
            entity_id: "fan.bedroom_fan"

1 Like

I feel like the LOW MID HIGH logic is wrong.

EDIT: I should read more before posting, NonaSumony posted the same 2 months ago lol.

The code above puts Low as relay 1, Mid as Relay 2, and High as Relay 3. But if you do that Mid is almost the same speed as low is.

I looked up the Tasmota code for the same device, and it has Low as Relay 1, Mid as Relay 1 AND 2, and High as Relay 1 AND 3. Doing that change on my local repo has made a big difference.

Pull request for this change here:

On another note, anyone know a good way to put the fan in high only for a second when starting up give it a boost? Like if the fan goes from is off and its then set to Mid, the Fan actually goes from OFF->HIGH (2 seconds) → MID. So it spins up faster.

cpyarger is MIA, the pr will probably sit there for a while. Essentially the 04-L model was supposed to fix the slow speed issue. We shouldn’t need to do this alas these modules are not the greatest. They should nix the capacitor switching to remove the hum and just properly integrate with just the relays to replace the pull chain switching but most users probably wouldn’t want to take that on. As usually there are multiple coils in the motor that they switch to for speed changes. We’re basically just cutting all that out and only operating with the fast coil with voltage drops which were never meant to run at slower speeds.

I’m not sure how this will go down but you could try some simple Arduino modifications with a delay(ms); also note use at your own risk not sure how much it will like to ramp fast to slow like that. I can understand going slow to fast for longevity reasons.

Try this though:

void IFan::set_med() {
            // Ramp up to high speed.
            digitalWrite(relay_1, HIGH);
            digitalWrite(relay_2, LOW);
            digitalWrite(relay_3, HIGH);
            beep(3);
            delay(10000); //  Delay 10 seconds.
            // Ramp down to medium speed.
            digitalWrite(relay_1, HIGH);
            digitalWrite(relay_2, HIGH);
            digitalWrite(relay_3, LOW);
            beep(2);
          }