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?

  • 3
    look up blink without delay. Which will tell you how to do things concurrently. – ratchet freak Sep 18 '18 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. – Jot Sep 18 '18 at 10:27
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.

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.

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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