Skip to content

Arduino project: the analogWrite() function and PWM

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.


download all my books for free

  • javascript handbook
  • typescript handbook
  • css handbook
  • node.js handbook
  • astro handbook
  • html handbook
  • next.js pages router handbook
  • alpine.js handbook
  • htmx handbook
  • react handbook
  • sql handbook
  • git cheat sheet
  • laravel handbook
  • express handbook
  • swift handbook
  • go handbook
  • php handbook
  • python handbook
  • cli handbook
  • c handbook

subscribe to my newsletter to get them

Terms: by subscribing to the newsletter you agree the following terms and conditions and privacy policy. The aim of the newsletter is to keep you up to date about new tutorials, new book releases or courses organized by Flavio. If you wish to unsubscribe from the newsletter, you can click the unsubscribe link that's present at the bottom of each email, anytime. I will not communicate/spread/publish or otherwise give away your address. Your email address is the only personal information collected, and it's only collected for the primary purpose of keeping you informed through the newsletter. It's stored in a secure server based in the EU. You can contact Flavio by emailing [email protected]. These terms and conditions are governed by the laws in force in Italy and you unconditionally submit to the jurisdiction of the courts of Italy.

Related posts about electronics: