Connect with us

Servo motor Arduino code

Discussion in 'Microcontrollers, Programming and IoT' started by Chr5, Feb 22, 2015.

  1. Chr5

    Chr5

    3
    0
    Feb 22, 2015
    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)   
        }
      }
    } 
     
  2. Arouse1973

    Arouse1973 Adam

    5,164
    1,078
    Dec 18, 2013
    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 likes this.
  3. Chr5

    Chr5

    3
    0
    Feb 22, 2015
    Thanks for that, yeah that looks like the route I need to investigate. Cheers.
     
Ask a Question
Want to reply to this thread or ask your own question?
You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.
Electronics Point Logo
Continue to site
Quote of the day

-