New Basic Arduino Serial Communication

This is an updated example of basic serial communication between Arduinos, the old example can be found here.

Sender code:

[Arduino]

// SENDER
int b1 = 7;
int b2 = 8;

void setup()
{
Serial.begin(9600);
pinMode(b1, INPUT);
pinMode(b2, INPUT);
digitalWrite(b1, HIGH);
digitalWrite(b2, HIGH);
}

void loop()
{
byte val1 = (byte)digitalRead(b1);
byte val2 = (byte)digitalRead(b2);
Serial.write(‘a’); //SYNC char
Serial.write(val1);
Serial.write(‘b’); //SYNC char
Serial.write(val2);
delay(50);
}

 

[/Arduino]

Receiver Code:

// RECIEVER
byte led1;
byte led2;

void setup() {
Serial.begin(9600);
pinMode(8, OUTPUT);
pinMode(9, OUTPUT);
delay(1000);
}

void loop() {
if(Serial.available() > 0)
{
char inChar = Serial.read();
while(Serial.available()<=0);

if (inChar == ‘a’)
{
led1 = Serial.read();
}

if (inChar == ‘b’)
{
led2 = Serial.read();
}
}

digitalWrite(9, led1);
digitalWrite(8, led2);
delay(10);
}