In this tutorial we will going to control the LED using keys of your keyboard via serial communication, sending a command from the PC to the Arduino using the Serial Monitor in the Arduino IDE. This project is also introduces how we manipulate the text string.
Parts Required
Arduino UNO/MEGA/PRO/MINI
3x LED Any Color
3x 220 Ohms Resistor
Jumper Wires
Solder-less Breadboard
Wiring the LED to the Arduino
The Sketch Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 |
/* 14CORE Starter Kit, Controlling your RGB LED Using Serial Communication */ char buffer[18]; int red, green, blue; int RedPin = 10; int GreenPin = 8; int BluePin = 9; void setup() { Serial.begin(9600); Serial.flush(); pinMode(RedPin, OUTPUT); pinMode(GreenPin, OUTPUT); pinMode(BluePin, OUTPUT); } void loop() { if (Serial.available() > 0) { int index=0; delay(100); // let the buffer fill up int numChar = Serial.available(); if (numChar>15) { numChar=15; } while (numChar--) { buffer[index++] = Serial.read(); } splitString(buffer); } } void splitString(char* data) { Serial.print("Data entered: "); Serial.println(data); char* parameter; parameter = strtok (data, " ,"); while (parameter != NULL) { setLED(parameter); parameter = strtok (NULL, " ,"); } // Clear the text and serial buffers for (int x=0; x<16; x++) { buffer[x]='\0'; } Serial.flush(); } void setLED(char* data) { if ((data[0] == 'r') || (data[0] == 'R')) { int Ans = strtol(data+1, NULL, 10); Ans = constrain(Ans,0,255); analogWrite(RedPin, Ans); Serial.print("Red is set to: "); Serial.println(Ans); } if ((data[0] == 'g') || (data[0] == 'G')) { int Ans = strtol(data+1, NULL, 10); Ans = constrain(Ans,0,255); analogWrite(GreenPin, Ans); Serial.print("Green is set to: "); Serial.println(Ans); } if ((data[0] == 'b') || (data[0] == 'B')) { int Ans = strtol(data+1, NULL, 10); Ans = constrain(Ans,0,255); analogWrite(BluePin, Ans); Serial.print("Blue is set to: "); Serial.println(Ans); } } |
After you upload the code you need to open the serial monitor and type the value of each LED if you type R255 Brightness will be High the same thing with other LED here is the example > R200 | G250 | B150 here is another example > enter R127, G100, B255 and you will get a nice purplish color. If you type R0, G0 B0 all 3 LED will be off.