In this article we will see how we can control the speed of the DC motor using Arduino. With this value we will be able to choose the corresponding color for the RGB LED.This is part 4 of my “ Building Robots using Arduino” tutorial series, explaining how you can create robots using Arduino. Note: in programming we usually start to count from 0, not 1. īecause we want to choose between 7 different options, we use the map() function to transform this value from the range 0-1023 to the range 0-6. In the void loop(), we first read the potentiometer’s value with analogRead(). Read potentiometer and choose a mode void loop() By calling this function, instead of 3 redundant lines, you just have one line, which is digitalWriteRGB() with 3 parameters. This function will help us reduce the code we write in the following.Įvery time you need to change the color of the RGB LED, you will need to call digitalWrite() 3 times. digitalWriteRGB() function void digitalWriteRGB(byte red, byte blue, byte green) Nothing to do for the potentiometer, as an analog pin is already in input mode by default. In the void setup(), we initialize all LEDs (in fact, the 3 legs of the RGB LED) to OUTPUT mode. One for the potentiometer, and one for each color of the LED – we write the code as if we were controlling 3 different LEDs. Setup RGB and potentiometer pins #define RGB_RED_PIN 11Īt first, as a best practice, we create a define for each pin we are going to use. Int mode = map(potentiometerValue, 0, 1023, 0, 6) Int potentiometerValue = analogRead(POTENTIOMETER_PIN) Void digitalWriteRGB(byte red, byte blue, byte green) We are going to use digitalWrite() – LED fully powered on/off, which means that we have a combination of 7 colors: You can see the RGB LED as a combination of 3 different LEDs that you control separately. In this first application, we are going to modify the color of the RGB LED when we turn the potentiometer knob. Connect the middle leg to an analog pin.Ĭontrol the RGB LED with the potentiometer – digitalWrite() – 7 colors.The other extreme leg should be connected to 5V on the Arduino. Connect one of the extreme leg (for example left) to the ground.Add a 220 Ohm resistor in between for each leg. Connect each of these legs to a PWM compatible digital pin on the Arduino (with a “~” next to the number, like on the picture). The 3 other legs correspond to red, blue, and green colors.If it’s an anode, plug it to 5V on the Arduino. So, if it’s a cathode, plug this to the ground (GND). If no instructions, you can first try the “cathode mode” and see if it works. How to find out? Simply check the manual or description of what you’ve bought. Depending on your RGB LED, this can be a cathode or an anode.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |