I'm working on a code where in one section, the user is asked to input a number. This number is defined as one of the arduino pins, which later in the code is set to high and then low.
Below is what I have and it's not working (cries forever). I would appreciate it so so much if one of you lovely people could help me figure out why it isn't working.. ?
My code is longer than this, but this is the relevant part of the code:
char junk = ' ';
int Pin;
void setup()
{
Serial.begin(9600);// set up Serial library at 9600 bps
Serial.flush();
pinMode(Pin,OUTPUT);
}
void loop()
{
Serial.println("Enter value for the chosen pin (pins 2-7), press ENTER");
while (Serial.available() == 0) ;// Wait here until input buffer has a character
{
int Pin = Serial.parseInt();
Serial.print("The chosen pin is= "); Serial.println(Pin);
while (Serial.available() > 0)
{
junk = Serial.read() ;
}
}
digitalWrite(Pin, HIGH);
delay(Time3);
digitalWrite(Pin, LOW);
}
Have a loot at Robin2's Serial Basic Input example And now you're reading, have a look at How to use the forum and please edit your post correspondingly (namely the code-tags).
Couple of things
flush() is useless here.
Why read "junk" while you don't even know is there is serial?
And after you read, the availability probably is 0 again so it will start over...
How can you set Pin output before you even know what it is?
parseInt() is a blocking function. I personally thing of the parse functions like a piece of crap...
What if the user doesn't enter a number between 2 and 7? Just trust him?
Thanks for getting back to me so quickly- I really appreciate it.
I'm new to all of this, so I apologize for the mistakes I made.
The fact that the code starts over after each time, with different inputs is exactly what I need. My problem is that there are a few other input the user has to include (mainly the amount of time each pin should be set to high) and I don't want the code to run till all of these inputs were specified. These other inputs work just fine, but I'm struggling with defining the pin.
Set the pinMode in loop when you know the pin number. Do not redeclare Pin when you set it to Serial.parseInt
as pinMode will only have local scope in that case.
char junk = ' ';
int Pin;
void setup()
{
Serial.begin(9600);// set up Serial library at 9600 bps
Serial.flush();
//pinMode(Pin,OUTPUT);
}
void loop()
{
Serial.println("Enter value for the chosen pin (pins 2-7), press ENTER");
while (Serial.available() == 0) ;// Wait here until input buffer has a character
{
//int Pin = Serial.parseInt();
Pin = Serial.parseInt();
Serial.print("The chosen pin is= ");
Serial.println(Pin);
pinMode(Pin,OUTPUT);
while (Serial.available() > 0)
{
junk = Serial.read() ;
}
}
digitalWrite(Pin, HIGH);
delay(5000);
digitalWrite(Pin, LOW);
}