AnalogWrite

From chipKIT
Jump to: navigation, search

Synopsis

void analogWrite(uint8_t pin, int val)

Description

analogWrite() is used to control the PWM functionality of pins which are connected to (or can be routed to) the hardware Output Compare module within the main MCU. Pins which do not support PWM will be either set to a constant HIGH or LOW value depending on the value input to the function. A 50% threshold value is used to decide if the pin should be HIGH or LOW.

The PWM generated is at an 8-bit resolution and typically in the region of 500Hz carrier frequency. The input value 0 and 255 are equivalent to a constant LOW and constant HIGH signal respectively. Values from 1 to 254 inclusive represent a duty cycle for the generated square wave. The percentage value of the duty cycle is equivalent to (val ÷ 255) × 100 so 127 represents a 50% duty cycle.

Return Value

None

Conforming To

analogWrite() conforms to the Arduino 1.6.x API.

Examples

"Fade" an output from minimum to maximum:

 for (int i = 0; i < 255; i++) {
     analogWrite(5, i);
     delay(10);
 }

See Also

analogRead(), analogReference()