PWM
Introduction
PWM or "Pulse Width Modulation" is the continuous fast-switching of a pin from '0' to '1' and back, creating a square wave signal.
By varying the ratio between "on-time" (the time during which the pin is "on" or 1) and "off-time" (the time during which the pin is "off" or 0), we can precisely control the amount of power delivered to a device, without ever changing the voltage.
Visualization of PWM duty cycle
More details about PWM can be found on Wikipedia.
Typical application
Typical applications for PWM include:
- motor speed control
- LED intensity control ("dimming")
- servo control
This tutorial presents the 'pwm' library, which allows us to control the PWM pins of the ioNode.
Note: not all pins are PWM-capable. Check out the ioNode documentation to see which pins can do PWM.
How to use
First, we need to add the 'pwm' library to our dependencies in dfe.conf:
name: example_app type: app mmcu: atmega1284p freq: 10000000 deps: - pwm
Then we can set the PWM ratio on any PWM-enabled pin with 'pwm_set' (and disable it completely with 'pwm_off').
The PWM value (ratio) is a single byte. Therefore:
- 0 -> 0%
- 127 -> 50%
- 255 -> 100%
etc...
1 #include <pwm/pwm.h> 2 3 void main() 4 { 5 // Set PWM @ 50% on pin 11 6 pwm_set(11, 127); 7 8 // ... 9 10 // Disable PWM on pin 11 11 pwm_off(11); 12 13 // ... 14 }