Press enter to see results or esc to cancel.

PWM โ€“ Pulse width modulation

This article is actually from and about a robot called small bit ๐Ÿ™‚

PWM is widely used in electrotechnics for lights, chargers, motors, generating different signals, etc. which are all present in robots as well. In short, PWM is a way of expressing analog values in the digital world.


You have probably wondered how, in the digital world, we can use some other value than supply voltage โ€“ which is output value from our microcontrollers like Arduino. The solution for this is PWM, which is essentially a microcontroller turning the output pin on and off very fast so that, for example, rather than seeing LED blinking, our eyes see an average brightness of LED being on and off.

For basic Arduino boards like Uno, the default PWM frequency is 490 Hz, while advanced Duo has 1000 Hz.

PWM is all about frequency (in Hz) and duty cycle (in %), which is the ratio between for how long the value is high, and for how long it is low. If the PWM duty cycle is 0%, then output voltage will be 0 V and vice versa. We can see some examples in Image below.

PWM duty cycle

PWM frequency and duty cycle can both be changed in the middle of the process. Which one we change depends on our application but in most beginner projects we change the duty cycle only. In the next image, we can see how sine waves can be generated using Arduino PWM by changing the duty cycle.

PWM sine wave

To get a clean sine wave signal you should use a filter.

The last thing that I would like to mention is how a PWM signal is generated in any microcontroller as well in Arduino. This is good to know for when you get your teeth into more complicated projects. The core behind PWM are timers, which are a topic for another article. But in short, timers are counters incrementing until a predefined value and then restarting. This value defines the period of a duty cycle, so by changing timer, we change the frequency and duty cycle of our PWM. Now that we know how PWM works we can see that in the same way we can read the PWM signal, e.g. a robot controller which outputs a PWM signal.

Give me the code

Luckily for us, Arduino PWM code is a no-brainer J all you have to do is connect your project to any of the โ€œanalogโ€ pins on Arduino and use the function analogWrite().

Donโ€™t forget to connect LED to Arduino via 1 kโ„ฆ resistor.

PWM Arduino example code:

int ledPin = 9;  // We will use pin 9

void setup() {
  pinMode(ledPin, OUTPUT);  // set the pin as output
void loop() {
  analogWrite(ledPin,127);  // Set PWM, 255 = 100%

And this is the end of a chapter about PWM by a robot called small bit. But do continue to read his story, how to read PWM signals and explore the world of timers. ๐Ÿ™‚

I promise no spam. ๐Ÿ˜‰