Arduino-project 004 - Dimmer

In project 003 we saw how you read external digital events and values, i.e. whether something is active or not. In this project we will learn how to read analog values, meaning values that can be almost anything, not just one or zero. This can for example be the water level, light intensity or a distance.  To start off simple we make a dimmer that reads the position of a potentiometer and then sets the light intensity on a LEDto the corresponding value.

The circuit

The circuit we need is very similar to that of project 001, but it also has a potentiometer connected to one of the analog inputs. The value of the potentiometer is not very important in this case, as long as it is somewhere between 1KΩ and 100 KΩ.

Arduino-project 004 - Dimmer


The code is quite simple - we read the voltage on the analog input A0 with the analogRead()function as an integer between 0 and 1023 and we use this value to set the intensity of the LED. Since the outputs of the Arduino uses values between 0 and 255 we use the map() function to scale the value. Unlike in project 003 we don't activate the pull-up-resistor on the input. The potentiometer is connected to both plus and ground which means that it's output and therefore also the input of the Arduinon will always have a stable voltage and it won't pick up interference. Also when reading analog values the pull-up resistor is disabled anyway. Note that it is only the dedicated analog inputs A0-A5 that can measure voltages, all other inputs are digital only.

The code

// Reserve memory for variables to store data in.
int value_in;
int value_out;

void setup() {
  // Set pin 2 to be an output.
  pinMode(2, OUTPUT);
  // Set pi A0 to be an input.
  pinMode(A0, INPUT);

void loop() {
  // Read the position of the potentiometer. This gives a value between 0 and 1023.
  value_in = analogRead(A0);
  // Scale the value so it's between 0 and 255.
  value_out = map(value_in, 0, 1023, 0, 255);
  // Set the intensity of the LED.
  analogWrite(2, value_out);

Lämna ett svar

Din e-postadress kommer inte publiceras.