Sonoff Ifan04 - ESPHome working code

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);
          }

(Try at your own risk) I found two spots you may be able to solder a small lead to. Maybe add some hot glue to your wires as well to not rip the pads off the board. You can use them for I2C or extra pins for fun. I donā€™t believe they are connected to anything besides these test points on the back of the board. Sonoff told me they are not connected to anything but these test points.

iFan04 ESP8285 Pinout

GPIO00 - Button
GPIO01 - TX (labelled wrong as RX) Also connected to the RF Remote IC
GPIO02 - N/C
GPIO03 - RX (labelled wrong as TX) Also connected to the RF Remote IC

Note: I think these test points are also on the older models as well. Not sure if connected to the same pins though.

GPIO04 - TP11 D_RX (SDA)
GPIO05 - TP10 D_TX (SCL)

GPIO06 - N/C
GPIO07 - N/C
GPIO08 - N/C
GPIO09 - Relay Light
GPIO10 - Buzzer
GPIO11 - N/C
GPIO12 - Relay 2 Fan Medium
GPIO13 - LED
GPIO14 - Relay 1 Fan Low
GPIO15 - Relay 3 Fan High
GPIO16 - N/C

iFan04 OB38R08 Microcontroller Pinout

Note: Do not use these SDA/SCL header pins at the top of the board as they are not connected to the ESP and are connected to the OB38R08 IC. (3v3/GND should be ok to use up there for your sensor modules)

PIN9(SDA)
PIN10(SCL)

iFan04 backside of PCB

SDA/SCL circled in red.

Few Ideas

  • ENS160+AHT21 CARBON Dioxide CO2 eCO2 TVOC Air Quality And Temperature And Humidity Sensor Replaces CCS811 $10 āœ“
  • Or BME280 I2C Temp/Hum/Pressure $5 āœ“
  • PCF8575 IO Expander Module I2C To 16 I/O Integrated Circuits (Connect the existing dumb light switch to it to re-enable light switch control without wireless switches). $2-3 āœ“
  • Use the pin directly as a digital IO and attach the light switch (may need to add some static protection).
  • ADS1115 ADC ultra-compact 16-precision ADC module. $4 (Not sure why haha)
  • Ardutex Trailing Edge I2C AC LED Light Dimmer. $20 (Dim the lights in the fan)

Example ESPHome YAML for BME280

# Define the I2C device for iFan04 to the Test Points on the back of the board.
# GPIO04 - TP11 D_RX (SDA)
# GPIO05 - TP10 D_TX (SCL)
i2c:
  id: i2c_component
  sda: 4
  scl: 5
  scan: true

sensor:
  - platform: bme280
    temperature:
      name: "BME280 Temperature"
      oversampling: 16x
    pressure:
      name: "BME280 Pressure"
    humidity:
      name: "BME280 Humidity"
    address: 0x77
    update_interval: 60s

Note: Caution high voltage! Do not setup like this! For quick testing purposes only!

Log

[01:32:17][C][i2c.arduino:039]:   SDA Pin: GPIO4
[01:32:17][C][i2c.arduino:040]:   SCL Pin: GPIO5
[01:32:17][C][i2c.arduino:041]:   Frequency: 50000 Hz
[01:32:17][C][i2c.arduino:044]:   Recovery: bus successfully recovered
[01:32:17][I][i2c.arduino:054]: Results from i2c bus scan:
[01:32:17][I][i2c.arduino:060]: Found i2c device at address 0x77
[01:32:17][C][bme280.sensor:174]: BME280:
[01:32:17][C][bme280.sensor:175]:   Address: 0x77
[01:32:17][C][bme280.sensor:187]:   IIR Filter: OFF
[01:32:17][C][bme280.sensor:188]:   Update Interval: 60.0s
[01:32:17][C][bme280.sensor:190]:   Temperature 'BME280 Temperature'
[01:32:17][C][bme280.sensor:190]:     Device Class: 'temperature'
[01:32:17][C][bme280.sensor:190]:     State Class: 'measurement'
[01:32:17][C][bme280.sensor:190]:     Unit of Measurement: 'Ā°C'
[01:32:17][C][bme280.sensor:190]:     Accuracy Decimals: 1
[01:32:17][C][bme280.sensor:191]:     Oversampling: 16x
[01:32:17][C][bme280.sensor:192]:   Pressure 'BME280 Pressure'
[01:32:17][C][bme280.sensor:192]:     Device Class: 'pressure'
[01:32:17][C][bme280.sensor:192]:     State Class: 'measurement'
[01:32:17][C][bme280.sensor:192]:     Unit of Measurement: 'hPa'
[01:32:17][C][bme280.sensor:192]:     Accuracy Decimals: 1
[01:32:17][C][bme280.sensor:193]:     Oversampling: 16x
[01:32:17][C][bme280.sensor:194]:   Humidity 'BME280 Humidity'
[01:32:17][C][bme280.sensor:194]:     Device Class: 'humidity'
[01:32:17][C][bme280.sensor:194]:     State Class: 'measurement'
[01:32:17][C][bme280.sensor:194]:     Unit of Measurement: '%'
[01:32:17][C][bme280.sensor:194]:     Accuracy Decimals: 1
[01:32:17][C][bme280.sensor:195]:     Oversampling: 16x
[01:32:17][C][IFAN:032]: IFan 'Master Bedroom Fan'
[01:32:35][D][api.connection:917]: Home Assistant 2022.11.1 (IP): Connected successfully
[01:32:36][D][sensor:126]: 'BME280 Temperature': Sending state 23.73000 Ā°C with 1 decimals of accuracy
[01:32:36][D][sensor:126]: 'BME280 Pressure': Sending state 978.19110 hPa with 1 decimals of accuracy
[01:32:36][D][sensor:126]: 'BME280 Humidity': Sending state 52.13184 % with 1 decimals of accuracy

Nice it worked :smiley:

You canā€™t use delay like that. Everything will stop working and youā€™ll likely trigger the WDT to reboot the device.

Have you tested that?

https://arduino-esp8266.readthedocs.io/en/3.0.0/reference.html#:~:text=Timing%20and%20delaysĀ¶&text=delay(ms)%20pauses%20the%20sketch,TCP/IP%20tasks%20to%20run

You would know better than I with ESPHome. I believe Arduino core wise delay(); triggers esp8266 yield(); behind the scenes which keeps it from hanging and allow it to do tasks like keeping WiFi up.

Otherwise, maybe do something like this instead:

You are blocking the loop() function which means that no other components can do anything.

I assume youā€™re referring to this:

Remember that there is a lot of code that needs to run on the chip besides the sketch when WiFi is connected. WiFi and TCP/IP libraries get a chance to handle any pending events each time the loop() function completes, OR when delay is called. If you have a loop somewhere in your sketch that takes a lot of time (>50ms) without calling delay, you might consider adding a call to delay function to keep the WiFi stack running smoothly.

The part youā€™re missing is the ā€œbesides the sketchā€. All of esphome is in ā€œthe sketchā€. So you are blocking all of esphomeā€™s functions. No sensor updates, no binary sensor triggers, no communication with HA, etc.

Not missing any part as to why I said you would know better about the ESPHome parts.

I fully understand what you mean as to why I also offered the BlinkWithoutDelay URL above.

Here is a modified example of how that may work:

// Generally, you should use "unsigned long" for variables that hold time
// The value will quickly become too large for an int to store
unsigned long previousMillis = 0;  // Will store last time relay ramp was updated

// Constants won't change:
const long interval = 10000;  // 10 second interval at which to trigger the relay ramp (milliseconds)

bool rampmed = false;

void IFan::set_med() {
  // Ramp up to high speed.
  digitalWrite(relay_1, HIGH);
  digitalWrite(relay_2, LOW);
  digitalWrite(relay_3, HIGH);
  beep(3);
  rampmed = true;
}

void loop() {

//... other code ...

  if (rampmed) {
    // Check to see if it's time to ramp down the relays; that is, if the difference
    // between the current time and the last time you ramped the relays is bigger than
    // the interval at which you want to ramp the relays.
    unsigned long currentMillis = millis();
    if (currentMillis - previousMillis >= interval) {
      // Save the last time you ramped the relays.
      previousMillis = currentMillis;
      // Ramp down to medium speed.
      digitalWrite(relay_1, HIGH);
      digitalWrite(relay_2, HIGH);
      digitalWrite(relay_3, LOW);
      beep(2);
      rampmed = false;
    }
  }
}

:smiley:

ā€¦Guess that wouldnā€™t totally work as the loop wouldnā€™t call it again without hitting the button again haha. Iā€™ll leave that one for him to further invest time into. Would probably have to add a boolean tracker that will just run in the loop and then rest itself after it runs.

Edit: Fixed the code for fun (not tested) play at your own risk @DelusionalAI .

Edit: Confirmed with @ssieb in discord which they replied with: ā€œYes, thatā€™s a good way to do it.ā€