We use the analogWrite() function provided by the Arduino language to output an analog signal.

Ok, not really an analog signal, but a PWM signal.

If you take an Arduino Uno for example, you will notice there are 6 analog input pins, A0-A5, but no analog output pins.

We use digital output pins in a particular way to simulate an analog output.

PWM means Pulse Width Modulation, and it’s a technique we use to simulate an analog output from digital devices. We basically emit a HIGH signal for a tiny amount of time, then we emit a LOW signal, and we keep repeating that, very fast. The analog device will see an average value based on the period. The shorter the HIGH period, the less the average value.

To simulate a 0V analog signal, use

analogWrite(0)

To simulate a HIGH analog signal (5V on the Arduino Uno), use

analogWrite(255)

Anything in between is between those 2 values. A 2.5V analog signal is analogWrite(127).

This is on devices that output 5V. Some Arduino devices like the Arduino MKR 1010 WiFi output 3.3V max, so those values will adapt to the highest voltage that can be emitted by the output pins.

Not all digital output pins can do that. In particular the pins we can use with analogWrite() are marked with a tilde ~. On the Arduino Uno, we can use pins 3, 5, 6, 9, 10, 11.

On the Arduino MKR 1010 Wifi we can use pins 0-8, 10, 11, A3, A4.

On the official specs of each board you will find the list of the PWM pins.

Want to become a better Web Developer? Join the 2022 Web Development Bootcamp!

⭐️⭐️⭐️ Join the 2022 Web Development Bootcamp ⭐️⭐️⭐️