Hi, is it possible to run 2 functions in a loop, function A every 10s and function B every 20s? how should I approach this?
//use this
unsigned long previousMillis1 = 0; // will store last time
unsigned long previousMillis2 = 0; // will store last time
// constants won't change:
const long interval1 = 10000; //10s interval at which to blink (milliseconds)
const long interval2 = 20000; //20s interval at which to blink (milliseconds)
void setup() {
// set the digital pin as output:
}
void loop() {
if (millis() - previousMillis1 >= interval1) {
previousMillis1 = millis();
//function1();
}
if (millis() - previousMillis2 >= interval2) {
previousMillis2 = millis();
//function2();
}
}
@hareendra
Yes, of course
There are many ways to do it.
Please see the "blink without delay" example in the IDE
That example contains some bad practices even if it gets away with them.
Here is a complete, common sense explained tutorial on the subject.
consider
void funcA (void) { Serial.println (" funcA"); }
void funcB (void) { Serial.println (" funcB"); }
void funcC (void) { Serial.println (" funcC"); }
struct Job {
void (*func) (void);
unsigned long period;
unsigned long msecLst;
};
Job jobs [] {
{ funcA, 1000 },
{ funcB, 750 },
{ funcC, 1200 },
};
#define Njob (sizeof(jobs)/sizeof(Job))
// -----------------------------------------------------------------------------
void
loop (void)
{
unsigned long msec = millis ();
Job *j = jobs;
for (unsigned n = 0; n < Njob; n++, j++) {
if ( msec - j->msecLst > j->period) {
j->msecLst = msec;
j->func ();
}
}
}
// -----------------------------------------------------------------------------
void
setup (void)
{
Serial.begin (9600);
}
With an ESP32
#include "certs.h" // include the connection info for WiFi and MQTT
#include "sdkconfig.h" // used for log printing
#include "esp_system.h"
#include "freertos/FreeRTOS.h" //freeRTOS items to be used
#include "freertos/task.h"
void setup()
{
xTaskCreatePinnedToCore( loop1, "loop1", 10000, NULL, 2, NULL, 1 );
xTaskCreatePinnedToCore( loop2, "loop2", 10000, NULL, 2, NULL, 1 ); // assign all to core 1, WiFi in use.
}
//loop runs once every 1000 millis seconds times 10
void loop1( void * PVparameter )
{
TickType_t xLastWakeTime = xTaskGetTickCount();
const TickType_t xFrequency = 1000 * 10; //delay for mS
for (;;)
{
///do the things
xLastWakeTime = xTaskGetTickCount();
vTaskDelayUntil( &xLastWakeTime, xFrequency );
} // for (;;)
vTaskDelete( NULL );
}
//loop runs once every 1000 millis seconds times 20
void loop2( void * PVparameter )
{
TickType_t xLastWakeTime = xTaskGetTickCount();
const TickType_t xFrequency = 1000 * 20; //delay for mS
for (;;)
{
///do the things
xLastWakeTime = xTaskGetTickCount();
vTaskDelayUntil( &xLastWakeTime, xFrequency );
} // for (;;)
vTaskDelete( NULL );
}
void loop() {}
Easy peasy.
This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.