I am trying to read data serially from a computer and send data to arduino. Based on my selection, I want to send HIGH to pins on arduino. I am using arduino mega 2560 to do this. I wrote some code and it was working fine until i made some changes and since then it doesnt work properly.
My code is:
// Read value from computer
// check if the value is greater than zero
// select the pin number matching to that value
/*
Send Data from computer to arduino and control the gpio pins
*/
int out[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13};
int val_on;
int PinCount = 13;
void setup()
{
for (int thisPin = 0; thisPin < PinCount; thisPin++)
{
pinMode(out[thisPin], OUTPUT);
}
// set baud rate for serial communication
Serial.begin(9600);
}
void loop()
{
Serial.println("\nEnter a number from 0 to 13: ");
val_on = Serial.parseInt();
// Check of there is data availabe in serial buffer
while (Serial.available() == 0)
{
if (val_on > 0 && val_on <= 13)
{
digitalWrite(out[val_on], HIGH);
Serial.print("\nTurned on Pin: ");
Serial.print(val_on);
}
}
}
jkprog:
Can anyone please tell me what i am doing wrong?
You did not use any [ code ] tags. Please read the "how to use this forum" post at the top. Without code tags, the forum software eats a little bit of your code.
OK, what do you mean "doesn't work properly"? What did you expect it to do? What does it actually do?
It looks like the first time around it will wait up to 1 second for the input, which probably isn't coming that fast if you have to type it. So parseInt() will return zero. That gets us into the while() loop which ignores the zero. As soon as something arrives by serial, then it reprints the prompt and starts to parse the integer. So long as you type faster than 1 character per second it will even parse two-digit numbers.
All good? Well, it depends on the line-ending setting of the serial monitor. With the usual CR-LF, it will send two characters after each thing you type. The first one ends the integer parsing because it's not a digit 0-9. The second one will kick you out of the while() loop and into the parsing attempt again. But there's no integer to be parsed and parseInt() will return zero, after waiting one second.
You also have the possibility of writing to pin 1, which is the serial transmit pin. That will block all serial communication after that point.
parseInt is a blocking method with a timeout of 1 second (as described above); one usually wants to write non-blocking code so the code can do useful other things. The linked thread handles that and contains an example how to convert text to a number.