#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.
2 Answers 2
Make little task using millis
function.
// GLOBAL VARIABLE
uint32_t taskMillis = 0;
....
// IN LOOP
if (taskMillis && millis() - taskMillis >= 5000)
{ /* SWITCHES DIRECTION */ }
With that code you can make two tasks(one to switch direction, second to move Servo by X deg). Here is video about this topic.
https://www.youtube.com/watch?v=v5SpPXMmHJE
I hope this anwser will help you.
The short answer is no. Delay causes your Arduino to stop dead in its tracks, and do NOTHING else until the specified time has passed. (You can still service interrupt service routines, but ignore that.)
The answer is to rewrite your code to use millis()
instead of delay. You record the current millis()
value, and compare the new time to millis()
to see if enough time has passed.
For the most part you should stop using the delay()
function and forget exists. It will get you into trouble.
Do a Google search on "Arduino blink without delay" and study the project that comes up to learn this approach.
3
...delay(5000)
and splitting it into a while loop running one thousand timesdelay(5)
and checking if there's a new instruction.