// Project#5 - Relay GUI
// In this project the python tkinger GUI will send instructions to the RPInoRPI to toggle a relay.
// Try to build on this project.  IF you have a 4 or 8 channel relay board, you can expand this project quite easily.
// Setup instructions:  
// Place jumpers across all 8 LCD header connections (See project video)
// Place a jumper across the "RELAY" header, which will connect the relay driver circuit to GPIO8

#include "LiquidCrystal.h"      // INCLUDE THE LIBRARY THAT HELPS TO DRIVE THE LCD.
LiquidCrystal lcd(2,3,4,5,6,10);// LCD pins RS/E/D4/D5/D6/D7 connected to UNO pins 2,3,4,5,6,10 Respectively.  USING THE LCD QUICK-CONNECT DIP SWITCH DOES ALL OF THIS FOR YOU ON CHIP-A
#define LCD_EN 11               // LCD Backlight controller definition 
#define relay1 8                // Set the relay1 driver pin to GPIO8
byte incomingByte = 0x00;       // This byte stores the incoming information from the PC
int hold = 0;                   // Create int hold, and set to 0
int relay1_state = 0;           // Create relay1_state variable and set to 0

void setup() {                  // Set up electronics
  lcd.begin(16,02);              // THIS SETS UP THE LCD, WHICH CAN SHOW 16 CHARACTERS ACROSS TWO LINES
  lcd.clear();                   // CLEAR THE LCD
  Serial.begin(115200);         // Set up serial monitor and serial comms to a baud rate of 115200.
  pinMode(LCD_EN,OUTPUT);        // Declare LCD_EN as an output
  digitalWrite(LCD_EN,HIGH);     // Turn the LCD backlight on
  pinMode(relay1,OUTPUT);       // Configure RELAY as an output
  digitalWrite(relay1,LOW);     // Turn the relay off
  lcd.print("Relay OFF");
}

void loop(){  // This is the main loop, and will loop forever until the RPInoRPI powers down
    while (Serial.available() > 0) {    // Execute the following code only when an instruction from the PC has been received.
    incomingByte = Serial.read();       // Read the incoming data and store it in incomingByte
    if(incomingByte == 49){             // If the received value was 1 (ASCII 49), then do the following:
     if(relay1_state == 0){             // If relay1_state is 0, change relay1_state to 1, and turn the relay on
       relay1_state = 1;                // Change to 1
       digitalWrite(relay1,HIGH);       // Turn the relay off
       lcd.clear();
       lcd.print("Relay ON");
     }
     else{                              // If relay1_State was 1, and not 0, then change relay1_state to 0, and turn the relay off
       relay1_state = 0;                // Change to 0
       digitalWrite(relay1,LOW);        // Turn the relay off
       lcd.clear();
       lcd.print("Relay OFF");
     }
    }     
}
}



