In Arduino projects, we often need to output analog signals. However, Arduino boards like the Uno do not have dedicated analog output pins. Thankfully, we can use the analogWrite()
function provided by the Arduino language to simulate analog output using a technique called Pulse Width Modulation (PWM).
PWM involves rapidly changing the output signal between a HIGH state and a LOW state. By varying the amount of time the signal spends in the HIGH state relative to the LOW state, we can create the illusion of an analog signal with varying average voltage levels.
To achieve a 0V analog signal, we use the following code:
analogWrite(0);
To simulate a HIGH analog signal (5V on the Arduino Uno), we use:
analogWrite(255);
Any value between 0 and 255 will produce an analog signal between 0V and 5V, with 2.5V corresponding to analogWrite(127)
.
It’s important to note that the output voltage levels depend on the capabilities of the board. Boards like the Arduino MKR 1010 WiFi can output a maximum voltage of 3.3V, so the corresponding values will be adjusted accordingly.
Not all digital output pins on Arduino boards support PWM. The pins compatible with analogWrite()
are marked with a tilde (~). For example, on the Arduino Uno, we can use pins 3, 5, 6, 9, 10, and 11. On the Arduino MKR 1010 WiFi, pins 0-8, 10, 11, A3, and A4 are compatible with PWM.
Make sure to consult the official specifications of your Arduino board to determine the PWM-compatible pins for your specific board.
Tags: Arduino, analogWrite(), PWM, Arduino Uno, Arduino MKR 1010 WiFi