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!
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)
}
}
}