PLS HELP! 2 function at the same time in arduino

Hi, i want to run 2 functions in the loop at the same time without stalling any either functions, basically what i am trying to get is , i have a code which turn on the 1st led for 5sec ,2nd led for 1sec and 3rd led for 5 sec and the cycle repeats until the data from ultrasonic sensor which is measured every time is less than 5 then it turns off 1st and 2nd leds and turn on 3 led

Your post was MOVED to its current location as it is more suitable.

Could you also take a few moments to Learn How To Use The Forum.

Other general help and troubleshooting advice can be found here.
It will help you get the best out of the forum in the future.

const int trigPin = 10;
const int echoPin = 11;
int ledred = 7;
int ledyellow = 8;
int ledgreen = 9;

long duration;
int distance;
int safetyDistance;

void setup() {
pinMode(trigPin, OUTPUT); 
pinMode(echoPin, INPUT);
pinMode(ledred, OUTPUT);
pinMode(ledyellow, OUTPUT);
pinMode(ledgreen, OUTPUT);
Serial.begin(9600);
}



void loop() { 

digitalWrite(trigPin, LOW);
delayMicroseconds(2);

digitalWrite(trigPin, HIGH);
delayMicroseconds(10);

digitalWrite(trigPin, LOW);

duration = pulseIn(echoPin, HIGH);

distance= duration*0.034/2;

safetyDistance = distance;

if (safetyDistance <= 5){
digitalWrite(ledred,LOW);
digitalWrite(ledyellow,LOW);
digitalWrite(ledgreen,HIGH);
}
else{
digitalWrite(ledred,HIGH);
delay(5000);
digitalWrite(ledred,LOW);
delay(10);

digitalWrite(ledyellow,HIGH);
delay(1000);
digitalWrite(ledyellow,LOW);
delay(10);

digitalWrite(ledgreen,HIGH);
delay(5000);
digitalWrite(ledgreen,LOW);
delay(10);

digitalWrite(ledyellow,HIGH);
delay(1000);
digitalWrite(ledyellow,LOW);
delay(10); 
}
Serial.print("Distance: ");
Serial.println(distance);
  
}
   





Get rid of the delays.
Take a look at the blink without delay example in the IDE.

The pin should already be LOW from last time you wrote to it

What is your second function? You only described one. You mean you want to continue sensing ultrasonic while the LEDs are blinking?

Also, 5 seconds is a long time for an indicator light. It forces the viewer to sit and wait to see what it's doing. Why this particular pattern? Is it a traffic light? If so, why not just tell us.

Also, when is the assignment due?

yes just like a traffic light and the 2 functions are sensing the ultrasonic sensor and blink the leds

i need the delay it is important

No, the effect of the delay is important.
The delays themselves are stopping you do what you want.

The delay() function is badly named. It should really be called freeze().

3 Likes

Did you read?

Did you get curious about what is meant by blink WITHOUT delay? I assure you @TheMemberFormerlyKnownAsAWOL is not leading you astray but to water. All you have to do is drink. The path you want is based upon the framework presented in the blink without delay example.

If you are using a ESP32 there is an alternate way to run multiple things at the same time. Till then take the advice and directions being offered. Peace.

but i need it is there any other way

i also have an esp32 can u say me how to acheive it but i for sure need a 5 sec delay before the led turns on

No, you do not need to use the delay function.
You need the effect it creates, but there are other, better ways.
See reply #4

No what you need is a 5 second gap between the different actions of the LEDs.

Because you want 'other stuff to be running' during the gap time, delay() is holding you back because as described above it literally freezes the code execution.

Have you even LOOKED at the "Blink Without Delay" example as suggested?

All evidence suggests that your coding abilities do not support use of the ESP32 / FreeRTOS alternative.

Hello
I think it isn´t nesseccary to run a OS for blinking LEDs.

My first attempt not tested.

I will help some with the debugging but I will NOT maintain it.

There are many things I'd change but its a start.

long duration;
int distance;
int safetyDistance;

#include "sdkconfig.h" // used for log printing
#include "esp_system.h"
#include "freertos/FreeRTOS.h" //freeRTOS items to be used
#include "freertos/task.h"
////
#define evtDoUltraSonics     ( 1 << 0 ) // declare an event
#define evtSonicsTrigger     ( 1 << 1 )
EventGroupHandle_t eg; //
////
esp_timer_handle_t oneshot_timer; //veriable to store the hardware timer handle
////
void IRAM_ATTR oneshot_timer_callback( void* arg )
{
  BaseType_t xHigherPriorityTaskWoken;
  xEventGroupSetBitsFromISR( eg, evtDoUltraSonics, &xHigherPriorityTaskWoken ); //freeRTOS event trigger made for ISR's
} //void IRAM_ATTR oneshot_timer_callback( void* arg )
////
const int trigPin = 10;
const int echoPin = 11;
int ledred = 7;
int ledyellow = 8;
int ledgreen = 9;

int duration;
int distance;
int safetyDistance;

void setup()
{
  eg = xEventGroupCreate(); // get an event group handle
  Serial.begin(9600);
  //
  // https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/system/esp_timer.html?highlight=hardware%20timer High Resoultion Timer API
  esp_timer_create_args_t oneshot_timer_args = {}; // initialize High Resoulition Timer (HRT) configuration structure
  oneshot_timer_args.callback = &oneshot_timer_callback; // configure for callback, name of callback function
  esp_timer_create( &oneshot_timer_args, &oneshot_timer ); // assign configuration to the HRT, receive timer handle
  //
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(ledred, OUTPUT);
  pinMode(ledyellow, OUTPUT);
  pinMode(ledgreen, OUTPUT);
  //
  xTaskCreatePinnedToCore( taskDoSafetyDance, "taskDoSafetyDance", 10000,  NULL, 5, NULL, 1 );
  xTaskCreatePinnedToCore( taskDoUltrasonicSensor, "taskDoUltrasonicSensor", 10000, NULL, 4, NULL, 1 );

}

void taskDoSafetyDance( void *pvParameters )
{

  for (;;)
  {
    if (safetyDistance <= 5) {
      digitalWrite(ledred, LOW);
      digitalWrite(ledyellow, LOW);
      digitalWrite(ledgreen, HIGH);
    }
    else {

      digitalWrite(ledred, HIGH);
      vTaskDelay(5000); ///<<this delay does not freeze the system
      digitalWrite(ledred, LOW);
      vTaskDelay(10);

      digitalWrite(ledyellow, HIGH);
      vTaskDelay(1000);
      digitalWrite(ledyellow, LOW);
      vTaskDelay(10);

      digitalWrite(ledgreen, HIGH);
      vTaskDelay(5000);
      digitalWrite(ledgreen, LOW);
      vTaskDelay(10);

      digitalWrite(ledyellow, HIGH);
      vTaskDelay(1000);
      digitalWrite(ledyellow, LOW);
      vTaskDelay(10);
    }
    Serial.print("Distance: ");
    Serial.println(distance);
    xEventGroupSetBits( eg, evtDoUltraSonics ); //<<signal ultrasonics ready for a new reading.
  }
  vTaskDelete( NULL );
}
////
void taskDoUltrasonicSensor( void *pvParameters )
{
  //TickType_t xLastWakeTime = xTaskGetTickCount();
  //const TickType_t xFrequency = 100; //delay for mS
  for (;;)
  {
    xEventGroupWaitBits (eg, evtDoUltraSonics, pdTRUE, pdTRUE, portMAX_DELAY );
    digitalWrite(trigPin, LOW);
    //delayMicroseconds(2);
    esp_timer_start_once( oneshot_timer, 2 ); // trigger one shot timer for a 2uS timeout.
    xEventGroupWaitBits (eg, evtSonicsTrigger, pdTRUE, pdTRUE, portMAX_DELAY ); // event will be triggered by the timer expiring, wait here for the 280uS
    digitalWrite(trigPin, HIGH);
    //delayMicroseconds(10);
    esp_timer_start_once( oneshot_timer, 10 ); // trigger one shot timer for a 10uS timeout.
    xEventGroupWaitBits (eg, evtSonicsTrigger, pdTRUE, pdTRUE, portMAX_DELAY ); // event will be triggered by the timer expiring, wait here for the 280uS
    digitalWrite(trigPin, LOW);
    duration = pulseIn(echoPin, HIGH);
    distance = duration * 0.034 / 2;
    safetyDistance = distance;
    //xLastWakeTime = xTaskGetTickCount();
    //vTaskDelayUntil( &xLastWakeTime, xFrequency );
  }
  vTaskDelete( NULL );
}


void loop() {}

As the OP may see it its a whole lot more complicated to do it this way.

Other tasks may be added and none of the above code will block other tasks from running.

i think i have to use millis but i dont have any experience about it can u explain and give me some examples

Have you looked at the blink without delay example in the IDE?

If not, do so, without delay.

It's taking a while but as the options close down the choices get less and less.