Knob Dimmer
Part of the Outputs section of Coddy's Arduino journey. Lesson 5 of 24.
A knob gives analogRead() a number from 0 to 1023, and analogWrite() wants 0 to 255. The two ranges do not match, so convert one into the other with map():
int reading = analogRead(A0);
int brightness = map(reading, 0, 1023, 0, 255);
analogWrite(9, brightness);Knob down gives 0 and the LED is off; knob up gives 1023, which becomes 255, fully on. Every position in between gives a brightness in between.
Writing the reading straight to the LED does not work: analogWrite() only takes 0 to 255, so a reading like 600 comes out as the wrong brightness.
Challenge
EasyThe knob is on A0 and the LED on pin 9. Make the knob set the brightness:
- read the knob
- turn the reading into 0 to 255 with
map() - write it to the LED, then wait 10 ms
Press Run and turn the knob, then Check.
Try it yourself
const int knobPin = A0;
const int ledPin = 9;
void setup() {
pinMode(ledPin, OUTPUT);
}
void loop() {
// read the knob, map it to 0..255 and write it to the LED
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Outputs
Practice on your own: Arduino playground