top of page

Discover Learn Arduino

Search

Serial controlled mood lamp

  • jpatel
  • Dec 27, 2018
  • 2 min read


 

When you upload the program nothing seems to happen. This is because the program is waiting for your input. Start the Serial Monitor by clicking its icon in the Arduino IDE taskbar. In the Serial Monitor text window, you’ll enter the R, G, and B values for each of the three LEDs manually. The LEDs will change to the color you have input. If you enter R255, the Red LED will display at full brightness. If you enter R255, G255, both the red and green LEDs will display at full brightness. Now enter R127, G100, B255. You get a nice purplish color.


Typing r0, g0, b0 will turn off all of the LEDs. The input text is designed to accept a lowercase or uppercase R, G, and B and then a value from 0 to 255. Any value over 255 will be dropped down to 255 by default. You can enter a comma or a space between parameters and you can enter one, two, or three LED values at any once; for example:

r255 b100

r127 b127 g127

G255, B0

B127, R0, G255


 

CODE

//Serial controlled mood lamp

char buffer[18];

int red, green, blue;

int RedPin = 11;

int GreenPin = 10;

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,

Ans = constrain(Ans,0,255);

analogWrite(BluePin, Ans);

Serial.print("Blue is set to: ");

Serial.println(Ans);

}

}

 
 
 

Comentários


Home: Blog2

Subscribe

Home: GetSubscribers_Widget

Contact

Your details were sent successfully!

Components Inside of Mobile Phone
Home: Contact

©2018 by Learn Arduino. Proudly created with Wix.com

bottom of page