How to replace the Delay function? (avoid crashes) on arduino


Does anyone know how to override the Delay function, which causes delays, in arduino? It is that I try to measure distances with this code, but at the same time I don't want the whole system to "sleep" that time, I want to do several things at the same time measure distances and that I can continue sending orders to my system.

int Trig=4;
int Echo=3;

//Variable en la que se va a almacenar el valor correspondiente a la distancia
int Dist;

void setup() {
    pinMode (Trig, OUTPUT);
    pinMode (Echo, INPUT);

//Este módulo calcula y devuelve la distancia en cm.
void ultrasonido (int &Distancia){
    //Para estabilizar el valor del pin Trig se establece a LOW
    digitalWrite (Trig, LOW);
    //Se lanzan los 8 pulsos
    digitalWrite (Trig, HIGH);
    digitalWrite (Trig, LOW);
    Distancia= pulseIn (Echo, HIGH);

void loop() {
    delay (250);


Perhaps some of the following will help you depending on what you want to achieve in the long term or what best suits your needs:

There is no multi-threading or multi-processing . On Arduino at least as far as I know, no (hardware) threading is supported.

You can try to simulate multiple threads with some software / library.

For example:

Protothreads , although there are several:

Protothreads can help you in that task as they are extremely lightweight stackless threads designed for memory restricted systems such as small embedded systems.

(link) Protothreads

Or use interruptions , especially timed ones. You can program a timer to interrupt the main routine every so often (micro seconds), in order to simulate what you are looking for by executing one or another specific routine. to do things while doing other things


I have looked for some code similar to the one commented to show you and this is the one that I found you can see it below with its link in the answer of a user of maybe it will help you.

In the example below, the LED blinks without using delay (). When Timer1 runs, the interrupt service routine (ISR) isrBlinker () is called toggling the state of the LED between on / off.

To demonstrate that other things can happen simultaneously, loop () repeatedly writes foo / bar to the serial port independent of the flashing LED.

#include "TimerOne.h" 

int led = 13;

void isrBlinker() {
  static bool on = false;
  digitalWrite( led, on ? HIGH : LOW );
  on = !on;

void setup() {                
  Serial.println("Serial initialized");

  pinMode(led, OUTPUT);

  // initialize the ISR blinker
  Timer1.attachInterrupt( isrBlinker );

void loop() {

videos that might help you

Scroll to Top