It's been a frustrating day of learning from Arduino tuts.
I'm working on setting up a servo motor. I troubleshooted why I couldn't get it to receive data and now I got it reading through the serial port and turning to appropriate degrees. But now it seems every time it loops through it tries to reset it's value to 0 degrees. I haven't assigned the variable to be 0 and the while loop is supposed to act like an interrupt while it waits for user input. So I don't understand why it's doing this.
I've also tried to return the value pos
to keep from changing/resetting values during each loop but keep getting compiling errors. I got one saying that pos
returns void
. And then I got another one when trying to declare the int pos
as a method within the loop and nesting the rest of the code inside the int method.
Also interesting side note: when you launch the serial port window in the IDE it'll rotate the motor by a small amount despite no input being given. After an given input is entered, it'll go to those degrees then it resets as described before.
Code:
#include <Servo.h> //Including the Servo code library
int servoPin = 6;
int servoDelay = 25;
int pos;
Servo myPointer; // Create a Servo object called myPointer
void setup() {
Serial.begin(9600);
//pinMode (servoPin, OUTPUT);
myPointer.attach(servoPin);
Serial.println("Hello");
}
void loop() {
Serial.println ("Where would you like the servo to point?");
while (Serial.available()==0){
}
pos = Serial.parseInt();
Serial.println (pos);
myPointer.write(pos);
}
The servo is running off the 5V power supply on the Arduino and receives instructions OK. It does not reset the position when running through void setup() so this must be the loop causing this. I just don't know why or how to fix it.
You have ensure the entire message is received before you start to parse it. Either set a the inter character gap with Serial.setTimeout()
(default 1s) to a larger value before use:
Serial.setTimeout(2000);
while (Serial.available() == 0) {}
duration = Serial.parseInt();
Or add a delay between Serial.available()
and Serial.parseInt()
if the above does not solve all your problems.
while (Serial.available() == 0) {}
delay(4000);
duration = Serial.parseInt();
Serial.available()
would fall thru on the first character received. So:
Additional characters like \\n
or \\r
could also be present triggering the parse but without there being sensible data. Serial.parseInt()
returns 0 if it fails to convert a number. So:
\\n
or \\r
.Serial.flush()
to get rid of any remaining \\n
or \\r
characters.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.