Hi! As an exercise I wrote this code to control 8 leds interfacing with a 74HC595 with the Serial port.
The program is really easy: it allows the user to write on the serial a number from 0 to 7 or 'x'. If the input is one of the numbers, it turns on the corresponding led. If the input is 'x', it turns out all the leds.
I also wanted to add an error message in case the input is different, and here come the troubles.
Here's the code in the loop():
byte leds = 0; // define leds status byte
void loop()
{
if (Serial.available()){// if there are some data to be sent
char ch = Serial.read(); // read them as a char
if (ch >= '0' && ch <= '7'){ // if the char is from 0 to 7
int led = ch - '0'; // evaluate the led to be turned on
bitSet(leds, led); // turn to one the corrispong bit in the 'leds' byte
updateShiftRegister(); // function that saves the byte 'leds' in the 74HC595 register
Serial.print("Turned on LED "); // communicate to user
Serial.println(led);
}
else if (ch == 'x'){ // if char is 'x'
// turn all the leds off
leds = 0;
updateShiftRegister();
Serial.println("Cleared");
}
else { // SOMETHING NOT WORKING HERE
Serial.println("ERROR: You have to enter a LED Number 0 to 7 or 'x' to clear");
}
}
}
Indeed, it looks like Arduino always executes the instruction in the else condition. Here's what I get from the serial in three different cases:
-
If I insert '0':
[/code]
Turned on LED 0
ERROR: You have to enter a LED Number 0 to 7 or 'x' to clear
[/code] -
If I insert 'x':
[/code]
Cleared
ERROR: You have to enter a LED Number 0 to 7 or 'x' to clear
[/code] -
If I enter '9'
[/code]
ERROR: You have to enter a LED Number 0 to 7 or 'x' to clear
ERROR: You have to enter a LED Number 0 to 7 or 'x' to clear
[/code]
Can somebody help me?