0

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
asked Mar 13, 2015 at 16:40
1
  • Initialize state to 1, don't overwrite with value from Serial, but set to 0 when Serial reads 0. Commented Mar 13, 2015 at 17:14

1 Answer 1

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
answered Mar 13, 2015 at 17:16
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.