Homework 2

Posted by prayag

prayag's picture

The idea is to be able to change the color of the LEDs from the console. Consists of two parts. A python code which sends the string while Arduino code which parses the string a lights up the LEDs.

 

Arduino code

 

 

char input[100];
 
int green = 9;
int blue = 10;
int red = 11;
int greenValue;
int redValue;
int blueValue;
 
boolean changed;
 
void setup()
{
  pinMode(green, OUTPUT);
  pinMode(blue,OUTPUT);
  pinMode(red,OUTPUT);
  
  Serial.begin(9600);
  changed= false;
  
  analogWrite(green,127);
  analogWrite(blue,127);
  analogWrite(red,127);
  
  Serial.println("enter color command (e.g. 'r043g098b089') :");
}
 
void loop()
{
  memset(input,0,100);
  readSerialString(input);
  
  if(changed)
  {
    Serial.print(input);
    char valRed[4], valGreen[4], valBlue[4];
    int grenValue, blueValue, redValue;
    
    valRed[0] = input[1]; valRed[1] = input[2]; valRed[2] = input[3]; valRed[3] = '\0';
    valGreen[0] = input[5]; valGreen[1] = input[6]; valGreen[2] = input[7]; valGreen[3] = '\0';
    valBlue[0] = input[9]; valBlue[1] = input[10]; valBlue[2] = input[11]; valBlue[3] = '\0';
    
    redValue = (valRed[0] - '0') * 100 + (valRed[1] - '0') * 10 + (valRed[2] - '0');
    greenValue = (valGreen[0] - '0') * 100 + (valGreen[1] - '0') * 10 + (valGreen[2] - '0');
    blueValue = (valBlue[0] - '0') * 100 + (valBlue[1] - '0') * 10 + (valBlue[2] - '0');
    
    Serial.print(redValue);
    Serial.print(greenValue);
    Serial.print(redValue);
    
    analogWrite(green,greenValue);
    analogWrite(blue,blueValue);
    analogWrite(red,redValue);
  }
  delay(100);
  
 
}
 
void readSerialString (char *strArray) {
  int i = 0;
  if(!Serial.available()) {
    changed = false;
    return;
  }
  while (Serial.available()) {
    strArray[i] = Serial.read();
    i++;
    changed = true;
  }
}
 
 
 
Python Code
 
import serial
import sys
 
def SendData(string,port,baudrate):
    ser = serial.Serial(port, baudrate, timeout=1)
    ser.write(string)
    ser.close()
    
 
if __name__ == "__main__":
    SendData(sys.argv[1],'/dev/ttyACM0',9600)
    
The LED color selector using a plastic mug as a diffuser
Screenshot of desktop application interacting with arduino
0
Your rating: None