#include <Servo.h>
Servo myservo;
int pos = 0;
int servo_pin = 3;
int led_pin = 4;
void setup() {
myservo.attach(servo_pin);
Serial.begin(9600);
pinMode(led_pin,OUTPUT);
}
void loop() {
if (Serial.available()) {
char serial = Serial.read();
if (serial == '2') {
servo();
}
if (serial == '1') {
digitalWrite(led_pin,HIGH);
} else if (serial == '0') {
digitalWrite(led_pin,LOW);
}
}
delay(100);
}
void servo() {
for (pos = 0; pos <= 180; pos += 1) {
myservo.write(pos);
delay(5);
}
delay(5000); // problem is here
for (pos = 180; pos >= 0; pos -= 1)
myservo.write(pos);
delay(5);
}
When I run this code and send '2', the servo()
functions start, but it includes a delay function.
Now I want to send '2' and then send '1'. When I do this, the first servo starts, but the LED starts after the servo function. I want to start this at the same time.
3
...delay(5000)
and splitting it into a while loop running one thousand timesdelay(5)
and checking if there's a new instruction.