I've been trying to control some LED diodes via digital pins but the code is acting weird. I hope there's some mistake that I'm not seeing.
Here's the code:
int led=7;
void setup() {
Serial.begin(9600);
pinMode(led, OUTPUT);
}
int y=0;
void loop() {
if (Serial.available()){
int y=Serial.read();}
if (y==1){
digitalWrite(led,HIGH);}
else digitalWrite(led,LOW);
}
On the other hand, here's a similar code that works perfectl:
int led=7;
void setup() {
Serial.begin(9600);
pinMode(led, OUTPUT);
}
int y=0;
void loop() {
digitalWrite(led,HIGH); //works
delay(400);
digitalWrite(led,LOW); //works
delay(400);
if (Serial.available()){
Serial.write(Serial.read());} //works
}
It works fine, I've forgotten to copy the line: Serial.write(y);.
It reads the input successfully, and prints it back to the Serial monitor. So it's not the y I suppose.
You can suppose all you like, but I don't see the point in assigning a value to a variable that's going to go out of scope in a few hundred nanaoseconds.
I am writing in the Serial Monitor bar via keyboard. I don't think the if clause there is making any problem, because it works alright just like that reading integers.
I've actually found the problem. While pressing EOL (Enter) it gives a few values. For example "1" + Enter will eventually send: 1 + \n + \r. Just need to trim them. It immediately changed the value after pressing Enter. Thanks for the help.