1
#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 servo functions start but there is an delay function. Now I want to send 2 then send 1. When I do this, the first servo starts but the LED starts after the servo function. I want to start this too at the same time.

2
  • then send 3 ...
    – jsotola
    Jan 18 at 18:17
  • You have to check for a new instruction in the servo function too, e. g. before and after delay(5000) and splitting it into a while loop running one thousand times delay(5) and checking if there's a new instruction. Jan 18 at 19:38
0

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.

0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.