Deep Dive: PWM
Although the name of
analogWrite() may lead you to believe it is generating an analog value (between 0 V and 5 V) on an output pin, the microcontroller in your Arduino (the ATmega328P) does not have the ability to do this. What it is really doing is something called pulse-width modulation (or “PWM”) which involves quickly turning the pin on and off while varying the amount of time spent on or off (the duty cycle) depending on the “analog value” written.
This is very different from a true analog output that can generate any voltage between 0 V and 5 V, and PWM can not be used in every situation that calls for a proper analog signal. For something like an LED, however, this is perfectly fine; although the LED is technically flashing on and off, it is going so fast that persistence of vision prevents you from seeing it. Instead, you just see the light get brighter or dimmer as the LED spends more or less time turned on.