Arduino - AnalogWrite

Arduino

Guide

Tutorials

Reference

Hardware

Software

Forum

Playground

Exhibition

Hacking

FAQ

Buy

Language | Libraries | Comparison

## analogWrite(pin, value)

#### Description

Writes an analog value (PWM wave) to a pin. On normal Arduino boards (e.g. Arduino NG), this works on pins 9, 10, or 11. On the Arduino Mini, this also works on pins 3, 5, and 6.

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).

#### Parameters

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.

#### Returns

nothing

#### Note

Pins taking analogWrite (9-11), unlike standard digital ones (1-8, 12, 13), do not need to be declared as INPUT nor OUTPUT

The frequency of the PWM signal is approximately 490 Hz.

analogWrite only works on pins 9, 10, and 11; on all other pins it will write a digital value of 0 or 5 volts.

#### Example

    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
    }

Sets the output to the LED proportional to the value read from the potentiometer.

#### See also

- pinMode
- digitalWrite
- analogRead

Reference Home Reference Home

Corrections, suggestions, and new documentation should be posted to the Forum.

Edit Page | Page History | Printable View | Recent Site Changes