Greenhouse: fan speed from temperature
Map a temperature to a PWM duty cycle, without stalling the fan at low speed. A medium embedded C problem (Timers and PWM), run and graded in the browser.
medium · Timers and PWM · pwm · scaling · product
Product: Smart greenhouse controller (Agriculture)
Requirement. The ventilation fan is off at 25.0 °C and below and at full speed at 35.0 °C and above. In between, its PWM duty (0 to 255) rises in proportion, rounded to the nearest step.
Real fans stall below about a quarter of full speed: they hum and draw current but do not turn. So any duty between 1 and 63 is raised to 64.
temp_c10 is the temperature in tenths of a degree (253 is 25.3 °C). Return the duty.
Starter code
uint8_t fan_duty(int16_t temp_c10) {
return (temp_c10 - 250) * 255 / 100;
}Example tests
Cool, warm and hot
printf("%u %u %u\n", fan_duty(200), fan_duty(300), fan_duty(400));Expected output:
0 128 255A slow fan still starts
printf("%u %u\n", fan_duty(255), fan_duty(276));Expected output:
64 66Learn it first
- Timers and PWM · Prescalers, auto-reload, input capture, output compare and dead time.
More Timers and PWM problems
- Servo pulse width · Turn an angle into the compare value for a hobby servo's pulse.
- Prescaler and auto-reload · Choose PSC and ARR for a 16-bit timer to hit an update frequency.
- Frequency from input capture · Compute a signal's frequency from two capture timestamps on a 16-bit timer.
- Duty cycle from captures · Measure a PWM signal's duty cycle in tenths of a percent.
- Decode a quadrature encoder · Turn A/B channel transitions into +1, -1 or 0 steps with a lookup table.
- Software PWM · Drive four PWM channels from a timer tick on pins without PWM hardware.
- Fan speed from tach pulses · Compute a fan's RPM from captured tach pulse times, and report 0 when it stalls.
- Fix: long delays end far too early · Delays over about four seconds come out wrong.
- Driver: a millisecond delay on a hardware timer · Program a timer's prescaler and auto-reload, and wait for exactly one period.
- Fix: 100 % brightness still flickers · A duty-cycle conversion uses the auto-reload value instead of the period length.
- Robot gripper: servo angle to timer value · Turn a servo angle into the timer's compare value, within the gripper's mechanical limits.