Arduino PWM example

In this example we connect an LDR to analog 0 and depending on the value read in we then vary the brightness of an LED connected to Pin 9 using PWM.

The input read from the analog pins will be in the range 0 to 1023. But the PWM function has a the width parameter ranging from 0 to 25 so in this case we use the map() function to convert the values ranging from 0-1023 to 0-255.


arduino pwm led

arduino pwm led


const int analogInPin = A0;  // Analog input pin that the potentiometer is attached to
const int PWMOutPin = 9; // Analog output pin that the LED is attached to

int sensorValue = 0;        // value read from the pot
int outputValue = 0;        // value output to the PWM (analog out)

void setup()

void loop()
// read the analog in value:
sensorValue = analogRead(analogInPin);
// map it to the range of the analog out:
outputValue = map(sensorValue, 0, 1023, 0, 255);
// change the analog out value:
analogWrite(PWMOutPin, outputValue);
// wait 2 milliseconds for the a/d converter to settle



Comments are closed.