Esta página também está disponível em outros 2 idiomas.

Entity Title

[Subcategory Name]

Description

Writes an analog value (PWM wave) to a pin. 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 square wave of the specified duty cycle until the next call to analogWrite() (or a call to digitalRead() or digitalWrite() on the same pin). The frequency of the PWM signal on most pins is approximately 490 Hz. On the Uno and similar boards, pins 5 and 6 have a frequency of approximately 980 Hz.

ArduinoUno R3 Front 450px
A beautiful Arduino UNO

Syntax

analogWrite(pin, value)

Parameters

pin: the number of the pin to write to. Allowed data types: int.
value: the duty cycle between 0 (always off) and 255 (always on). Allowed data types: int.

Returns

Nothing

Example Code

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
}

Notes and Warnings

This is because of interactions with the millis() and delay() functions.

ArduinoUno R3 Front 450px
A beautiful Arduino UNO

See also

  • DEFINITION PWM