Go Down

Topic: Help with Serial Communication (Read 290 times) previous topic - next topic

jreeve17

Feb 02, 2013, 04:44 am Last Edit: Feb 02, 2013, 04:46 am by jreeve17 Reason: 1
 I have this code
Code: [Select]


int led3 = 3;
int led4 = 4;
int led5 = 5;
int led6 = 6;

int input = 0;    

void setup() {
pinMode(led3,OUTPUT);
pinMode(led4,OUTPUT);
pinMode(led5,OUTPUT);
pinMode(led6,OUTPUT);

\
 Serial.begin(9600);    
}

void loop () {
 input = Serial.read();  


 if (input == 'q' ) {
   digitalWrite(led3,HIGH);
   Serial.println("1 is ON");
 }
 if (input == 'a'){
     digitalWrite(led3, LOW);
     Serial.println("1 is OFF");
 }
    if (input == 'w' ) {
   digitalWrite(led4,HIGH);
   Serial.println("2 is ON");
 }
 if (input == 's'){
     digitalWrite(led4, LOW);
     Serial.println("2 is OFF");
 }
   if (input == 'e' ) {
   digitalWrite(led5,HIGH);
   Serial.println("3 is ON");
 }
 if (input == 'd'){
     digitalWrite(led5, LOW);
     Serial.println("3 is OFF");
 }
   if (input == 'r' ) {
   digitalWrite(led6,HIGH);
   Serial.println("4 is ON");
 }
 if (input == 'f'){
     digitalWrite(led6, LOW);
     Serial.println("4 is OFF");
 }
}


      I am using it to turn LED's in and off via serial. The only problem is that I would like to be able to use multiple characters and this code only allows for one character. For example, right now, i can only say "q" or "d" to turn LED's on and off. I would like to be able to say "red on " or "green off" o turn them on or off. Any help would be appreciated.

zoomkat

Test code that uses a delimiter.

Code: [Select]

//zoomkat 3-5-12 simple delimited ',' string parce
//from serial port input (via serial monitor)
//and print result out serial port
// CR/LF could also be a delimiter

int ledPin = 13;
String readString;

void setup() {
  Serial.begin(9600);
  pinMode(ledPin, OUTPUT);
  Serial.println("serial LED on/off test with , delimiter"); // so I can keep track
}

void loop() {

  if (Serial.available())  {
    char c = Serial.read();  //gets one byte from serial buffer
    if (c == ',') {
      //if (readString.length() >0) {
        Serial.println(readString); //prints string to serial port out
        //do stuff with the captured readString
        if(readString.indexOf("on") >=0)
        {
          digitalWrite(ledPin, HIGH);
          Serial.println("LED ON");
        }
        if(readString.indexOf("off") >=0)
        {
          digitalWrite(ledPin, LOW);
          Serial.println("LED OFF");
        }       
        readString=""; //clears variable for new input
      //}
    } 
    else {     
      readString += c; //makes the string readString
    }
  }
}

Google forum search: Use Google Advanced Search and use Http://forum.arduino.cc/index in the "site or domain:" box.

Go Up