PWM fan control

Hello everyone!

I have problem with getting PC PWM fans to work with ESPHome. I have working application written in Arduino cpp and I’m trying to convert it into ESPHome. But with ESPHome code fans are not slowing or speeding up. When I set speed variable to 0-99 they spin at some “default” unknown speed. When I set 100 they are spinning at full speed. Can somebody help me please how to make it work just like Arduino code?

This is working Arduino code:

pinMode(D1, OUTPUT);
analogWriteRange(100);
analogWriteFreq(25000);
analogWrite(D1, speed); // speed is in range of 0 - 100

I tried to convert it into ESPHome like this:

output:
  - platform: esp8266_pwm
    pin: D1
    frequency: 25000 Hz
    id: pwm_fan

sensor:
  - platform: homeassistant
    name: "Manual speed"
    entity_id: input_number.pc_fan_speed
    id: manual_speed
    on_value:
      - script.execute: speed_check

script:
  - id: speed_check
    then:
      lambda: |-
        uint8_t speed = id(manual_speed).state;
        id(pwm_fan).set_level(speed / 100);

Do you need to actually tuen on the output?

script:
  - id: speed_check
    then:
      lambda: |-
        uint8_t speed = id(manual_speed).state;
        id(pwm_fan).set_level(speed / 100);
      output.turn_on: pwm_fan

Not sure if I got the indent right there - but I think that’s what is missing.

You don’t need the input number from home assistant. Use the speed fan component and it will create an entity with a 0-100 slider

@zoogara Thats good idea, thanks! I’ll try it when I’ll be at home.

@Mikefila Thanks, I’ll check this component. But my way should work too, right?

You can, the component, I find easier to use with on device automations.

Not the king of esphome, but I think this should have / 100.0, or the division will return an integer.

@koying I think you are right and this would be solution! Just tested in simulator: sketch.ino - Wokwi Arduino Simulator
I’m used to program in C# so I was blind for this kind of “simple mistake”. And in my original Arduino code I’m not dividing speed value because PWM output is in 0-100 range instead of ESPHomes 0.0-1.0

Thanks everyone for giving advices. I’ll try everything when I’ll be at home at evening and let you know! :slight_smile:

@koying Was right. It was dividing error:

35 / 100 = 0
35 / 100.0 = 0.35

Thank you @koying and everybody else for helping me out. :slight_smile: