analogWrite(pin, value)

Description

Writes an analog value (PWM wave) to pins 9, 10, or 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).

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 30769 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

Reference Home