I'm new to Arduino and I'm a bit confused about the analogWrite() function.
From what I understand, the analogWrite() command is used to generate a PWM (Pulse Width Modulation) signal, which can be used to control devices like LEDs and motors. However, I noticed that this function is used on digital pins that support PWM, rather than the analog pins.
- Why is the
analogWrite()command used on PWM digital pins and not on analog pins even though the command name suggest it work for analog?
It would be great if someone could explain the technical reasons behind this.
So, analogWrite() is indeed used to create a PWM signal, which can dim LEDs, control motor speed, etc. The name is a bit misleading because it sounds like it should be used on the analog pins, but it's actually meant for digital pins that support PWM.
So PWM or analogWrite only turns the digital pins ON and OFF at a very high frequency creating a dummy analog signal. And there are 6 digital pins on UNO that supports this behavior- with a "~" symbol next to them (like 3, 5, 6, 9, 10, 11)
When you use analogWrite(pin, value), you're controlling the duty cycle of the PWM signal
- A value of 0 means the pin is off all the time.
- A value of 255 means the pin is on all the time.
- Values in between control how long the pin stays on during each cycle, effectively simulating an analog voltage between 0 and 5V.
So analogWrite function has nothing to do with the analog pins. The term analogWrite() was chosen to make it easier for beginners to understand that this function controls something in an analog-like way (variable output), even though it uses digital pins.
I hope this clears up the confusion.
To expand on what @ankunegi said, here’s a simple example of how analogWrite() works on a PWM pin in practice:
void setup() {
pinMode(9, OUTPUT); // Pin 9 supports PWM
}
void loop() {
analogWrite(9, 128); // 50% duty cycle (128 out of 255)
}
This will make an LED connected to pin 9 glow at half brightness because the average voltage is 2.5V (on a 5V Arduino). If you try this on an analog pin like A0, it won’t work because analog pins are meant for input, not output.
It’s just a quirk of how Arduino names function. Once you get used to it, it’s not a big deal.