Search code examples
loopsarduinoiot

Arduino run 2 commands at the same time


I have connected 3 devices to my Arduino Uno: Servo Motor, LED and a Distance Sensor. Now when the distance is 10cm or smaller then my led is going off. My led is going on when the distance is larger then 10cm this is working fine. But now when I have added my Servo motor I need to wait when my loop is done before my distance sensor is sending the signal to my led. How can I fix this ?

#include <Servo.h>

int servoPin = 9;

const int trigPin = 7;
const int echoPin = 8;
int led = 13;
long duration, cm;
Servo servo;
int angle = 0;

void setup()
{
    // initialize serial communication:
    Serial.begin(9600);

    pinMode(led, OUTPUT);
    pinMode(echoPin, INPUT);

    servo.attach(servoPin);
}

void loop()
{

    if (afstandTotmuur() >= 10) {
        digitalWrite(led, HIGH);
    }
    else {
        digitalWrite(led, LOW);
    }

    for (angle = 0; angle < 180; angle++) {
        servo.write(angle);
        delay(15);
    }
}

long afstandTotmuur()
{
    pinMode(trigPin, OUTPUT);
    // digitalWrite(trigPin, LOW);
    // delayMicroseconds(2);
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(trigPin, LOW);

    duration = pulseIn(echoPin, HIGH);

    // convert the time into a distance
    cm = microsecondsToCentimeters(duration);

    return cm;
}

long microsecondsToCentimeters(long microseconds)
{
    return microseconds / 29 / 2;
}

Solution

  • This is a common problem. Here is a great answer I found in the Adafruit tutorial section.

    The solution explained in the link, in short, shows you how to use the millis() function and not the delay() and why this is much better for multitasking.