![]() ![]() ![]() This brightness variable is an integer number between 0 and 255. So now we have computed the brightness to apply to the LED. Apply brightness setting to LED analogWrite(LED_PIN, brightness) ![]() Using map() is great whenever you need to do operations like this, and it works for any integer range. With this line and the 5 arguments in the function, what we’re saying is: take the potentiometerValue from the range 0-1023, to the range 0-255. To do the same thing, you could also use the Arduino map() function which can put a number into a different range. Compute LED brightness with map (option 2) int brightness = map(potentiometerValue, 0, 1023, 0, 255) Nothing fancy here, it’s very simple and it works. So, if we want to put a value from the range 0-1023 to the range 0-255, we can just divide by 4. And as I really like simplicity, you can see that, roughly, 1024 is 255 multiplied by 4 (not exactly this value but this is a good enough approximate for what we need to do). So, before we use this function, we need to make sure the value is in the correct range. This analogWrite() function takes a byte value, or in other words, a number between 0 and 255. In order to control the LED brightness, we are going to use the analogWrite() function on the LED pin (later on). Compute LED brightness (option 1) int brightness = potentiometerValue / 4 For 0V you get 0, and for 5V you get 1023. The higher the voltage, the higher this number. This number corresponds to the voltage we read on the analog pin. In other words, this is a 10 bit number: 2^10 = 1024. We store the value inside an integer variable. To do that we use the analogRead() function, which takes one parameter: the pin number to read from. ![]() We enter the void loop(), and the first thing we do is to read the potentiometer value. Now that everything is setup, we can start to control the brightness of the LED with what we read from the potentiometer. However, for analog pins, no need to use pinMode() as those pins are already in INPUT mode!
0 Comments
Leave a Reply. |