Simvik

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 255

A slow fan still starts

printf("%u %u\n", fan_duty(255), fan_duty(276));

Expected output:

64 66

Learn it first

  • Timers and PWM · Prescalers, auto-reload, input capture, output compare and dead time.

More Timers and PWM problems