Maker Pro
Maker Pro

Servo motor Arduino code

Chr5

Feb 22, 2015
3
Joined
Feb 22, 2015
Messages
3
Hello. I am trying to control a servo motor using an Android device. At the moment, I can type into the device either 0, 1, 2 or 3 and each of these will make the motor do something different. However, if I press 0 and then press 2, for example, I have to wait until 0 has finished moving before anything else can be done. I want the motor to change straight away, rather than having to wait.

I am pretty sure it has something to do with millis(), but I haven't been able to work it out. Any help would be great, thanks!

Code:
#include <Servo.h>

Servo myservo;  // create servo object to control a servo

void setup()
{
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
  Serial.begin(9600); //begins serial communication
}
void loop()
{
  int pos;
  if (Serial.available()){
    delay(100);
    while(Serial.available()>0){
      pos=Serial.read();     //reads the value sent from Visual Basic 
      if(pos=='0'){
   myservo.write(45);  // Turn Servo Left to 45 degrees
   delay(1000);          // Wait 1 second
   myservo.write(0);   // Turn Servo Left to 0 degrees
   delay(1000);          // Wait 1 second
   myservo.write(90);  // Turn Servo back to center position (90 degrees)
   delay(1000);          // Wait 1 second
   myservo.write(135); // Turn Servo Right to 135 degrees
   delay(1000);          // Wait 1 second
   myservo.write(180); // Turn Servo Right to 180 degrees
   delay(1000);          // Wait 1 second
   myservo.write(90);  // Turn Servo back to center position (90 degrees)
   delay(1000);}          // Wait 1 second
      else if(pos=='1')
        myservo.write(-90);  //rotates the servo 90 degrees (right)
      else if(pos=='2')
        myservo.write(180);  //rotates the servo 180 degrees (Left)
      else if(pos=='3')
        myservo.write(-180); //rotates the servo 180 degrees (right)   
    }
  }
}
 

Arouse1973

Adam
Dec 18, 2013
5,178
Joined
Dec 18, 2013
Messages
5,178
Hello
When you press a 0 you will have to wait until it has done all the myservo write routines after then. You need a get out which could be as simple as just checking for a 1 2 or 3 within each routine.
Adam
 

Chr5

Feb 22, 2015
3
Joined
Feb 22, 2015
Messages
3
Hello
When you press a 0 you will have to wait until it has done all the myservo write routines after then. You need a get out which could be as simple as just checking for a 1 2 or 3 within each routine.
Adam
Thanks for that, yeah that looks like the route I need to investigate. Cheers.
 
Top