2

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?

asked Sep 18, 2018 at 8:39
2
  • 3
    look up blink without delay. Which will tell you how to do things concurrently. Commented Sep 18, 2018 at 8:45
  • 1
    The NewPing library does not use pulseIn. With the blink-without-delay ( arduino.cc/en/Tutorial/BlinkWithoutDelay ) for the led and the NewPing (it is in the library manager) for the ultra-sonic sensor, you can do many other things as well, but don't use delay in the sketch anymore. Commented Sep 18, 2018 at 10:27

2 Answers 2

1

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.

answered Sep 20, 2018 at 21:30
0
0

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.

answered Sep 20, 2018 at 20:28

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.