Hello, I have this simple code which turns on/off LEDs based on serial input. Everything is working as a I want it to but for one thing: I need to establish a "current state" that keeps the code from rerunning if the same input is made as the last input. For example, in this code, if input is 3 all LED's are turned on and serial message is printed. But in this case I want: if 3 was inputted again, for the program to not rerun, and the serial message to not reprint, and just keep the LEDs on until a different input is made. How do I do this? thank you
here's my code:
// Global Variable Declarations
const int LED_GREEN = 13; // GREEN LED is connected to this pin
const int LED_YELLOW = 12; // Yellow LED is connected to this pin
const int LED_RED = 11; // RED LED is connected to this pin
int readByte; //set variable 'readByte' to equal the read of incoming bytes
void setup()
{
// Setup up serial communication as 9600 baud
// Default config parameter is 8 data bits, no parity, 1 stop bit
Serial.begin(9600);
// When writing to a pin, its mode must be set to OUTPUT
// to lower the input resistance on the pin
pinMode(LED_GREEN, OUTPUT);
pinMode(LED_RED, OUTPUT);
pinMode(LED_YELLOW, OUTPUT);
//program starts at case 0, iValue = 0
digitalWrite(LED_GREEN, LOW);
digitalWrite(LED_RED, LOW);
digitalWrite(LED_YELLOW, LOW);
Serial.println("State: 0");
}
void loop()
{
// will be true if 1 or more characters are available to read.
if( Serial.available()> 0 )
{
// Local declaration of variable readByte
int readByte = Serial.read();
// Verify character read is an ASCII digit in range 0 - 9
if(isDigit(readByte))
{
int iValue = ( readByte - '0'); // Convert ASCII to numeric
//conditional: turn LED's on/off by inputs in serial monitor
if(iValue==0){
digitalWrite(LED_GREEN, LOW);
digitalWrite(LED_RED, LOW);
digitalWrite(LED_YELLOW, LOW);
Serial.print("State: ");
Serial.println(iValue);
}
else if(iValue==1){
digitalWrite(LED_GREEN, LOW);
digitalWrite(LED_RED, HIGH);
digitalWrite(LED_YELLOW, LOW);
Serial.print("State: ");
Serial.println(iValue);
}
else if(iValue==2){
digitalWrite(LED_GREEN, HIGH);
digitalWrite(LED_RED, HIGH);
digitalWrite(LED_YELLOW, LOW);
Serial.print("State: ");
Serial.println(iValue);
}
else if(iValue==3){
digitalWrite(LED_GREEN, HIGH);
digitalWrite(LED_RED, HIGH);
digitalWrite(LED_YELLOW, HIGH);
Serial.print("State: ");
Serial.println(iValue);
}
else{
Serial.println(" Error: Input Must Be Number Between 0 and 3 ");
}
}
else if(readByte ==10){ //add this so the 'enter' key ascii value is ignored
}
else{
Serial.print(" Error: Input Must Be Number Between 0 and 3 ");
}
}
}