Arduino Circuit to Dim LED with Potentiometer

Circuit to Dim LED

In Lesson 8 you learned to write analog voltages on the Arduiono, and in Lesson 10 you learned to read analog voltages from the arduino. In this lesson we will combine what you did in lessons 8, 9, and 10 to create an LED with adjustable brightness. The brightness will be set based on the position of the potentiometer. In order to do this, we need to set the potentiometer up as a voltage divider, and we need to drive the LED from one of the analog pins. For this example, I am using pin 9. The circuit schematic I am using is shown below.

Circuit to Dim LED

In placing the LED into the circuit, remember that you must always put the longer leg towards the positive voltage. In the case above, the longer leg should be connected to the resistor, and the shorter leg connected to ground. Also remember that we are using a 330 ohm resistor in the circuit to limit the current through the LED.

The goal now is to use what you learned in the last three lessons. You will want to read a value from the potentiometer, and then write a voltage to the LED based on the reading from the potentiometer. Remember that when you read an analog voltage between 0 and 5 volts, the arduino will report a number between 0 and 1023, with 0 representing 0 volts, and 1023 representing 5 volts.

Similarly, when you are writing an analog voltage between 0 and 5 volts, you must write a number between 0 and 255. If you write a “0” value, that corresponds to 0 volts. If you write a value of 255, that will output 5 volts. So, you must scale your write values between 0 and 255 to get voltages between 0 and 5 volts.

Circuit to Dim LED schematic (1)

The tricky thing now is that we want to dim the LED based on what value we read from the potentiometer. If we read a 0 value from the potentiometer, we want to write a value of 0, which corresponds to a voltage of 0. If we read a value of 1023 from the potentiometer, then we will want to write our maximum voltage of 5 volts, which means we need to write a value of 255. Basically, we need to scale our read values, which will be between 0 and 1023 to suitable write values, which should be between 0 and 255.

Like in the earlier lessons, this is a simple linear relationship and allows us to use the skills we have learned in math class. This sheet explains the math:

So, from the math above, we can see that the Write Value that we should write to the LED should be the value that we are reading from the potentiometer X (255/1023).

With the math out of the way we can write the program. This code is designed for the schematic above where the potentiometer center leg is read with pin A0 and the LED is written from pin 9.

 

Read more: Arduino Circuit to Dim LED with Potentiometer

Leave a Comment

Your email address will not be published. Required fields are marked *