4-bit Serial Optical Communication using IR LED and pin diode between two Arduinos

 
////////////////////////////////////////////////////////////
//
// *** Arduino Uno 1 ***
//
// Transmitter (sender) code
//
// Infrared LED is connected to the Arduino Digital pin 13.
// Data is transferred by using this LED in binary form.
// Maximum transfer rate is found to be 1000 bit/sec.
// Dec 2015
////////////////////////////////////////////////////////////
byte   ch = 0; 
byte  led = 13;
int  wait = 1000; // us

void setup() {
  pinMode(led,OUTPUT);
  Serial.begin(9600);
}

void loop() 
{
  // ready for communication
  digitalWrite(led, HIGH);

  if(Serial.available()>0)
  {
     ch = Serial.read();
     Serial.print("I received: ");
     Serial.println(ch);

     // if 1 is pressed
     if(ch==49){
       digitalWrite(led,LOW);  delayMicroseconds(wait);
       digitalWrite(led,HIGH); delayMicroseconds(wait); // 1
       digitalWrite(led,HIGH); delayMicroseconds(wait); // 1
       digitalWrite(led,LOW);  delayMicroseconds(wait); // 0
       digitalWrite(led,HIGH); delayMicroseconds(wait); // 1
       digitalWrite(led,HIGH);
     }
     // if 2 is pressed
     if(ch==50){
       digitalWrite(led,LOW);  delayMicroseconds(wait);
       digitalWrite(led,HIGH); delayMicroseconds(wait); // 1
       digitalWrite(led,LOW);  delayMicroseconds(wait); // 0
       digitalWrite(led,LOW);  delayMicroseconds(wait); // 0
       digitalWrite(led,HIGH); delayMicroseconds(wait); // 1
       digitalWrite(led,HIGH);
     }
     // if 3 is pressed
     if(ch==51){
       digitalWrite(led,LOW);  delayMicroseconds(wait);
       digitalWrite(led,HIGH); delayMicroseconds(wait); // 1
       digitalWrite(led,LOW);  delayMicroseconds(wait); // 0
       digitalWrite(led,HIGH); delayMicroseconds(wait); // 1
       digitalWrite(led,HIGH); delayMicroseconds(wait); // 1
       digitalWrite(led,HIGH);
     }
  }

} // end of loop function
 
////////////////////////////////////////////////////////////
//
// *** Arduino Uno 2 ***
//
// Receiver code
//
// Pin diode (which is sensitive to infrared region of emw)
// is connected to Arduino Analog input (A5).
// Maximum transfer rate is found to be 1000 bit/sec.
// Dec 2015
////////////////////////////////////////////////////////////

byte  minimum = 200, start, i;
byte  data[] = {0, 0, 0, 0};
int   wait = 1000; // us

void setup() {
 Serial.begin(9600);
}

void loop()
{
  start = 1;
  while(start){
    start = analogRead(A5) > minimum;
  }
  delayMicroseconds(wait);
  
  for(i=0; i<4; i++){
    data[i] = analogRead(A5) > minimum;
    delayMicroseconds(wait);
  }

  if(data[0]==1 && data[1]==1 && data[2]==0 && data[3]==1){
    Serial.print("1");
  }
  else if(data[0]==1 && data[1]==0 && data[2]==0 && data[3]==1){
    Serial.print("2");
  }
  else if(data[0]==1 && data[1]==0 && data[2]==1 && data[3]==1){
    Serial.print("3");
  }

} // end of loop function