Reference Language (extended) | Libraries | Comparison
Writes an analog value (PWM wave) to a pin. On newer Arduino boards (including the Mini and BT) with the ATmega168 chip, this function works on pins 3, 5, 6, 9, 10, and 11. Older USB and serial Arduino boards with an ATmega8 only support analogWrite() on pins 9, 10, and 11.
Can be used to light a LED at varying brightnesses or drive a motor at various speeds. After a call to analogWrite, the pin will generate a steady wave until the next call to analogWrite (or a call to digitalRead or digitalWrite on the same pin).
pin: the pin to write to.
value: the duty cycle: between 0 and 255. A value of 0 generates a constant 0 volts output at the specified pin; a value of 255 generates a constant 5 volts output at the specified pin. For values in between 0 and 255, the pin rapidly alternates between 0 and 5 volts - the higher the value, the more often the pin is high (5 volts). For example, a value of 64 will be 0 volts three-quarters of the time, and 5 volts one quarter of the time; a value of 128 will be at 0 half the time and 255 half the time; and a value of 192 will be 0 volts one quarter of the time and 5 volts three-quarters of the time.
nothing
You do not need to call pinMode() to set the pin as an output before calling analogWrite().
The frequency of the PWM signal is approximately 490 Hz.
Sets the output to the LED proportional to the value read from the potentiometer.
int ledPin = 9; // LED connected to digital pin 9 int analogPin = 3; // potentiometer connected to analog pin 3 int val = 0; // variable to store the read value void setup() { pinMode(ledPin, OUTPUT); // sets the pin as output } void loop() { val = analogRead(analogPin); // read the input pin analogWrite(ledPin, val / 4); // analogRead values go from 0 to 1023, analogWrite values from 0 to 255 }
Corrections, suggestions, and new documentation should be posted to the Forum.
The text of the Arduino reference is licensed under a Creative Commons Attribution-ShareAlike 3.0 License. Code samples in the reference are released into the public domain.