กลับไปหน้ารวมไฟล์
using-millis-function-as-an-alternative-to-using-delay-4a74ef-en.md

In this tutorial I am looking at using the millis() function in the code, describing the architectural advantages it has over using the blocking delay() function.

Project Overview

This "Async-Core" approach addresses the single most critical bottleneck in embedded systems development: the Blocking Delay. While the delay() function is intuitive, it halts the CPU's instruction pointer, rendering the system "deaf" to external interrupts and inputs. This project documents the architectural shift to Non-Blocking Multitasking using the millis() function, enabling an Arduino to handle multiple high-speed tasks—such as blinking an LED, reading a sensor, and processing serial data—simultaneously without latency.

Technical Deep-Dive

  • Hardware Timer Forensics:
    • Timer0 Overflow: Under the hood, the Arduino core utilizes Timer0 (an 8-bit hardware timer) to increment a 32-bit unsigned long counter every millisecond. This process is handled via an Interrupt Service Routine (ISR) that runs in the background, independent of the main loop() execution.
    • The Subtraction Rule (Overflow Protection): A common forensic pitfall is fearing the "49-day rollover" where the 32-bit counter resets to zero. This project highlights the mathematical beauty of (currentTime - startTime >= interval). Because of unsigned integer roll-over behavior, this subtraction always yields the correct elapsed time, even during a rollover event.
  • Asynchronous State Management:
    • Finite State Machine (FSM) Logic: Instead of a linear script, the code is structured as an event-loop. The CPU "Checks" the time, executes a micro-task if the threshold is met, and immediately continues to the next instruction. This allows the system to remain 100% responsive to a Potentiometer Input or Button Press even while a 5-second LED timer is running.
  • CPU Cycle Analysis:
    • Eliminating Idle Wait: In a typical 1000ms delay, the CPU wastes 16,000,000 clock cycles doing nothing. With Async-Core, those 16 million cycles are repurposed to monitor sensors, manage serial buffers, and perform complex math, effectively increasing the system's "Intelligence Density."

Engineering & Implementation

  • Concurrent Task Design:
    • The implementation demonstrates two concurrent tasks:
      1. Task A: Blinking an LED at a fixed 1000ms interval.
      2. Task B: Reading and serial-plotting a potentiometer's analog value every 10ms.
    • By using millis(), the serial plotter shows a smooth, real-time graph of the potentiometer, whereas using a delay(1000) for the LED would cause the graph to "Freeze" and drop data for a full second.
  • Software Design Pattern:
    • The project introduces the "Polling Pattern":
      unsigned long currentMillis = millis();
      if (currentMillis - previousMillis >= interval) {
          previousMillis = currentMillis;
          // Execute non-blocking task here
      }
      
    • This pattern is the foundational building block for complex operating systems and RTOS kernels.

Conclusion

Async-Core is the gateway to Professional Embedded Development. By mastering Non-Blocking Logic and Hardware Timer Forensics, developers transition from writing simple scripts to engineering robust, multi-threaded applications capable of real-time environmental awareness.


Time Mastery: Conquering the CPU through asynchronous forensics.

Full tutorial can be found in the video below:

ข้อมูล Frontmatter ดั้งเดิม

apps:
  - "Serial Plotter (for visualizing concurrency)"
author: "Dziubym"
category: "Lab Stuff"
components:
  - "1x Arduino Nano R3 (AVR Timer Host)"
  - "1x Linear Potentiometer (Asynchronous Input Node)"
  - "1x LED (Asynchronous Output Node)"
  - "1x 220 Ohm Resistor (Current Limiting)"
description: "A comprehensive deep-dive into asynchronous state management and hardware timer forensics, demonstrating how to replace blocking delay logic with high-efficiency event-driven multitasking."
difficulty: "Easy"
documentationLinks: []
downloadableFiles: []
encryptedPayload: "U2FsdGVkX1+HVuv9+b/eDw/yFG3yBHwOsJDRcb5UmVrsDQJJmDcQS3jwg8P6B2Nnc1eCkCp619SgZsB8w60wRZgFy4/uAT4Kpb/BeQYwMmA="
heroImage: "https://cdn.jsdelivr.net/gh/bigboxthailand/arduino-assets@main/images/projects/using-millis-function-as-an-alternative-to-using-delay-4a74ef_cover.jpg"
lang: "en"
likes: 4
passwordHash: "5741b065aadd2a61545c88cc32e2d48a4086ec916bec34ceb828a89ba0373c6a"
price: 299
seoDescription: "Learn to use the millis() function in Arduino as a non-blocking alternative to delay() for better multitasking and performance."
tags:
  - "millis-function"
  - "non-blocking-logic"
  - "multitasking"
  - "finite-state-machines"
  - "overflow-handling"
  - "asynchronous-programming"
title: "Using millis() Function as an Alternative to Using Delay"
tools:
  - "Arduino IDE 2.0 (High-Speed Debugging)"
videoLinks:
  - "https://www.youtube.com/embed/dCku8BabPx4"
views: 24544