Hello!
I have recently started toying with while, switch and if functions. The thing is, when nesting a while inside an if, it just won´t work.
For example, when ordering the arduino to turn an LED off when it reads a '0' from the Serial Port, on when a '1', or blink when receiving either 4 or 5 or 6, it will turn on or off, but won´t blink.
Any ideas as to what could be wrong?
Thanks so much,
Daartist.
Sketch_Serial.ino.ino (544 Bytes)
('4' || '5' || '6') I believe will evaluate to something other than 4 or 5 or 6.
while(infopc == 4 || infopc == 5 || infopc == 6)
{
digitalWrite(led, HIGH);
delay(1000);
digitalWrite(led, LOW);
delay(1000);
}
But then it will just be stuck inside that while loop forever and blink forever since it is no longer reading the serial any more once it enters the loop...
... or:
while(infopc == 4 || infopc == 5 || infopc == 6)
{
digitalWrite(led, HIGH);
delay(1000);
digitalWrite(led, LOW);
delay(1000);
if (Serial.available() > 0)
{
infopc = Serial.read();
}
}
@ty_ger07: I don't think that will work because Serial.read() returns an ASCII value and infopc is an int.
OP: I don't understand exactly what you expect to do with the while, but I don't see a way out of it. An alternative might be:
const int led = 9; // You could use the onboard LED on pin 13
int infopc;
void setup() {
Serial.begin(9600); // Señala puerto serie
pinMode(led, OUTPUT); // Setea al led como una salida
}
void loop() {
if (Serial.available() > 0) {
infopc = Serial.read() - '0'; // Converts to a numeric value
}
switch (infopc) {
case 0:
digitalWrite(led, LOW);
break;
case 1:
digitalWrite(led, HIGH);
break;
case 4:
case 5:
case 6:
digitalWrite(led, HIGH);
delay(1000);
digitalWrite(led, LOW);
delay(1000);
break;
default:
Serial.print("Error, infopc = ");
Serial.println(infopc);
break;
}
}
@econjack
Thanks for the code! That may fix the nesting. I'll try it tomorrow morning.
As to your question, I wanted to use the while to loop the blinking. Otherwise, it would only run the blink proccess once.