Home All Projects
Easy

Easy and transparent non-blocking code using millis()

How to implement non-blocking code

Easy and transparent non-blocking code using millis()

Components, Tools and Machines

1x Arduino Nano
🛒 Buy Now

Apps and platforms

1x Arduino IDE 2.0 (beta)
Official Site

Project description

Probably you already know how to use millis() not to block your code. In this shor article I am going to show how to use it very easily in the code to have it more transparent and effective.

In the next code we are going to run 3 processes, where the first process executes every 200 milliseconds, the second process executes every 5 seconds and the 3rd process executes every 29 seconds.

The core of the solution is in the following function WaitMillis:

bool WaitMillis(unsigned long* t, long waitMillis) {

if ((millis() - *t) > waitMillis) {

*t = millis();

return true;

}

if (millis() < *t) *t = millis(); //this row treats overflow of millis()

return false;

}

This function returns true if the time (the value waitMillis) has expired and false if the right time did not come yet. As we know, millis() counts from zero every millisecond and overflows after 50 days when it starts to count from zero again. In the function we treat this with the last if sentence.

If we have this function then the code is very transparent and simple:

First we define unsigned long variables for counting and we initialize them in the setup:

unsigned long every200millis, every5seconds, every29seconds;

void setup() {

every200millis = millis();

every5seconds = every200millis;

every29seconds = every200millis;

}

And the finaly we run our 3 processes in the loop:

void loop() {

if (WaitMillis(&every200millis, 200)) DoProcess1();

if (WaitMillis(&every5seconds, 5000)) DoProcess2();

if (WaitMillis(&every29seconds, 29000)) DoProcess3();

}

This code runs these 3 processes independantly. Of course, if you do not block the code in processes with delay() or "while" of "for" sentences.

Code

🔒 Unlock Code

Support to get the Source Code for this project

Project Reference Code: easy-and-transparent-non-blocking-code-using-millis-5bf837-en
99 THB
PromptPay QR Code

ประเมินราคาอัตโนมัติ + Reference Code

อยากได้งานคล้ายโปรเจคนี้ ให้ AI ประเมินราคาก่อน

กรอกข้อมูลให้ครบ ระบบจะสร้างรหัสอ้างอิงและประเมินราคา/ระยะเวลาคร่าว ๆ จากรายละเอียดงาน แล้วให้กด Add LINE พร้อมพิมพ์รหัสนี้เพื่อคุยต่อ

คำถามให้ AI ประเมินแม่นขึ้น

หลังส่งฟอร์ม ระบบจะโชว์ Reference Code ให้ copy แล้วกด Add LINE เพื่อคุยต่อ ข้อมูลส่วนตัวจะไม่ถูกส่งเข้า GA4

รีวิวจากคนใช้งานจริง

รีวิวจากลูกค้าและคนที่เคยใช้งาน

ถ้าเคยสั่งงาน เคยอ่านหน้านี้แล้วได้ประโยชน์ หรือมีข้อเสนอแนะ ฝากรีวิวไว้ได้เลย

กำลังโหลดรีวิว...