Posts Tagged ‘arduino toggling leds serial’

things

Arduino: toggling leds through SERIAL monitor

ok here is a sample code which receives data from serial and toggles devices to test it you can plug in led’s to test it,

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
//for keeping the current status of leds
int status1 = 0;
int status2 = 0;
int status3 = 0;
int status4 = 0;
//leds connected to Arduino int pin1 = 2;
int pin2 = 4;
int pin3 = 6;
int pin4 = 8;
void setup() {
//open serial ports
Serial.begin(9600);
Serial.println("Serial Ready.");
Serial.println("Waiting...");
//open led ports
pinMode(pin1, OUTPUT);
pinMode(pin2, OUTPUT);
pinMode(pin3, OUTPUT);
pinMode(pin4, OUTPUT);
}
void loop() {
//keep the incoming byte, in readByte
int readByte;
boolean readSomething = false;
//read serial data
while(Serial.available() > 0 ){
readByte =  Serial.read();
readSomething = true;
Serial.println(readByte);
}
//if something was read toggle the selective device
if(readSomething){
readSomething = false;
if(readByte==1){ status1^=1; digitalWrite(pin1,status1);}
if(readByte==2){ status2^=1; digitalWrite(pin2, status2);}
if(readByte==3){ status3^=1; digitalWrite(pin3, status3);}
if(readByte==4){ status4^=1; digitalWrite(pin4, status4);}
}// status^=1 is xoring if its 0 it will be 1 and if its 1 it will be 0..
}