I am trying to stop servo motor from rotating when I enter 0 in serial. The code is below. Can someone please help?
#include <Servo.h>
Servo myservo; // create servo object to control a servo
// twelve servo objects can be created on most boards
int state;
int pos = 0; // variable to store the servo position
void setup()
{
myservo.attach(9); // attaches the servo on pin 9 to the servo object
Serial.begin (9600);
}
void loop()
{
if (Serial.available () > 0)
{
state = Serial.read ();
if (state == '1')
{
for (pos = 0; pos <= 180; pos += 1)
{
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15);
}
for (pos = 180; pos >= 0; pos -= 1)
{
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
if (Serial.available () > 0)
{
state = Serial.read ();
if (state == '0')
{
myservo.write ('90');
delay (300);
}
}
}
}
}
Peter Bloomfield
11k9 gold badges48 silver badges87 bronze badges
1 Answer 1
From the code you posted it looks like you have the right idea but you've nested the 'IF' statements causing the check for '0' to only happen if you send two bytes and it will only go to 90deg when you send '10'. The loop section should look more like:
if(Serial.available()){
state = Serial.read();
if(state == '1'){
Make motor move;
}else if(state == '0'){
Make motor stop;
}//end of elseif
}//end of if
lang-cpp
state
to 1, don't overwrite with value from Serial, but set to 0 when Serial reads0
.