analogWrite()
Description
Writes an analog value (PWM wave) to a pin. Can be used to light a LED at varying brightness or drive a motor at various speeds. After a call to
analogWrite()
, the pin will generate a steady rectangular wave of the specified duty cycle until the next call to analogWrite()
(or a call to digitalRead()
or digitalWrite()
) on the same pin.Check your board pinout to know which are the officially supported PWM pins. While some boards have additional pins capable of PWM, using them is recommended only for advanced users that can account for timer availability and potential conflicts with other uses of those pins.
In addition to PWM capabilities some boards have true analog output when using
analogWrite()
on the DAC
marked pins. Check your board pinout to find out if the DAC is available.Only 4 different pins can be used at the same time. Enabling PWM on more than 4 pins will abort the running sketch and require resetting the board to upload a new sketch again.
You do not need to call
pinMode()
to set the pin as an output before calling analogWrite()
. The analogWrite
function has nothing to do with the analog pins or the analogRead
function.Syntax
Use the following function to generate a PWM signal on a given pin:
analogWrite(pin, value)
Parameters
The function admits the following parameters:
: the Arduino pin to output the PWM signal. Allowed data types:pin
int
: the duty cycle: between 0 (always off) and 255 (always on). Allowed data types:value
int
Returns
The function returns nothing.
Example Code
Sets the PWM duty cycle that controls the LED proportional to the value read from the potentiometer (connected to A3).
1int ledPin = 9; // LED connected to digital pin 92int analogPin = A3; // potentiometer connected to analog pin 3 (A3)3int val = 0; // variable to store the read value4
5void setup() {6 pinMode(ledPin, OUTPUT); // sets the pin as output7}8
9void loop() {10 val = analogRead(analogPin); // read the input pin11 analogWrite(ledPin, val / 4); // analogRead values go from 0 to 1023, analogWrite values from 0 to 25512}
Notes and Warnings
The PWM outputs generated on pins 5 and 6 may have higher-than-expected duty cycles. This is because of interactions with the
millis()
and delay()
functions, which share the same internal timer used to generate those PWM outputs. This will be noticed mostly on low duty-cycle settings (e.g. 0 - 10) and may result in a value of 0 not fully turning off the output on pins 5 and 6.See also
Suggest changes
The content on docs.arduino.cc is facilitated through a public GitHub repository. If you see anything wrong, you can edit this page here.
License
The Arduino documentation is licensed under the Creative Commons Attribution-Share Alike 4.0 license.