Easy and transparent non-blocking code using millis()
How to implement non-blocking code
How to implement non-blocking code
Project Supporter Team
Posted by
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.
Support to get the Source Code for this project
ประเมินราคาอัตโนมัติ + Reference Code
กรอกข้อมูลให้ครบ ระบบจะสร้างรหัสอ้างอิงและประเมินราคา/ระยะเวลาคร่าว ๆ จากรายละเอียดงาน แล้วให้กด Add LINE พร้อมพิมพ์รหัสนี้เพื่อคุยต่อ
ส่งข้อมูลเรียบร้อย
ขั้นตอนต่อไป: กดปุ่มด้านล่าง ระบบจะคัดลอกข้อความพร้อม Reference Code ให้ แล้วพาไปหน้า LINE ทันที เอาข้อความนั้นส่งใน LINE เพื่อให้ทีมงานดึงข้อมูลจากฟอร์มนี้มาต่อได้เลย
Reference Code
รีวิวจากคนใช้งานจริง
ถ้าเคยสั่งงาน เคยอ่านหน้านี้แล้วได้ประโยชน์ หรือมีข้อเสนอแนะ ฝากรีวิวไว้ได้เลย
ยังไม่มีรีวิวบนหน้านี้ ถ้าเคยใช้งานหรือมีข้อเสนอแนะ เขียนเป็นคนแรกได้เลย