I want to use an ultra-sonic sensor and the led concurrently. I want the led to blink every 0.2 seconds and the ultra-sonic to measure distance without regard to the blinking.
The problem is I have the following code for blinking:
digitalWrite(13, HIGH); delay(1000); digitalWrite(13, LOW); delay(200);
which makes the ultra-sonic sensor to be delayed as well, but I want it to keep measuring distance. Any tips?
2 Answers 2
There is a non-blocking library that works similar to delay()
Virtual Delay. This sketch turns your Uno's built-in LED ON for 1 second, then OFF for 200ms, repeatedly.
#include <Arduino.h>
#include "avdweb_VirtualDelay.h"
VirtualDelay delay1, delay2;
void setup(){
pinMode(LED_BUILTIN, OUTPUT);
digitalWrite(LED_BUILTIN, LOW);
}
void loop(){
// This sequence has a deadlock.
if(delay1.elapsed()){
digitalWrite(LED_BUILTIN, LOW);
delay2.start(200);
}
if(delay2.elapsed()){
digitalWrite(LED_BUILTIN, HIGH);
delay1.start(1000);
}
// This breaks the deadlock. You can start with any
// delay object you want e.g. delay2.start(0);
DO_ONCE(delay1.start(0));
// Your code here.
}
The library's author has an excellent tutorial on their website: avdweb Virtual Delay timer for Arduino.
You could try to use millis(). It is a timer that measures how long your program has been running. With some math, you could use millis to let your LED blink without delaying the ultra sonic sensor.
delay
in the sketch anymore.