system
July 28, 2011, 12:06pm
1
void setup()
{
pinMode(13,OUTPUT);
Serial.begin(9600);
}
void loop()
{
while(Serial.available() == 0);
int i= Serial.read()-48;
if(i==1)
digitalWrite(13,HIGH);
else if(i==0)
digitalWrite(13,LOW);
else
Serial.println("invalid!");
}
Why does this code always show invalid no matter what the serial ip is???
the led (pin 13) works properly though...
system
July 28, 2011, 12:38pm
2
The problem is not println the problem is the code. It was good to post the code, be sure to use the # icon above to put code tags around your code.
A book on C++ may be in order based on your code. Notice the code below - the if statement has the {} around it - very good practice and C++ 101.
Notice the output shows the result when not valid so you can see what is going on. When ever you have a question about the results of your code you should use serial.print to show the results. Now that you can see the results, making adjustments should be simple.
void setup()
{
pinMode(13,OUTPUT);
Serial.begin(9600);
}
void loop()
{
while(Serial.available() == 0);
int i= Serial.read()-49;
if(i==1){
digitalWrite(13,HIGH);
} else if (i==0) {
digitalWrite(13,LOW);
} else {
Serial.print("invalid ");
Serial.println(i, DEC);
}
}
system
July 28, 2011, 1:38pm
3
Hey i tried out your code... there is a small mistake though it should be 48, so i changed that but still getting invalid...
int i= Serial.read()-48;
invalid -38
invalid -38
invalid 6
invalid -38
This is the output i got on the serial monitor for 3 inputs, The inputs were 1 0 6
system
July 28, 2011, 1:45pm
4
Carriage return, line feed?
there is a small mistake though it should be 48,
No, it should be '0' .
system
July 28, 2011, 1:55pm
5
What you should do is grab the actual value and show it / take action on the actual value. Why do you want to subtract a hard coded value?
Example: A or a turns on .... B or b turns off - else invalid.
void setup()
{
pinMode(13,OUTPUT);
Serial.begin(9600);
}
void loop()
{
while(Serial.available() == 0);
int i= Serial.read();
//if A or B pressed
if(i==97 || i==65){
digitalWrite(13,HIGH);
//if A or B pressed
} else if (i==98 || i==66) {
digitalWrite(13,LOW);
} else {
Serial.print("invalid ");
Serial.println(i, DEC);
}
}
system
July 28, 2011, 2:08pm
6
if(i==97 || i==65){
Isn't
if(i=='a' || i=='A'){ much easier to read?
system
July 28, 2011, 2:11pm
7
thanx madworm, I had to select "no line end" in the serial monitor.... MY BAD