|

|  How to set up a non-blocking delay function in C without using delay loops?

How to set up a non-blocking delay function in C without using delay loops?

October 14, 2024

Learn to implement non-blocking delays in C efficiently using timers and interrupts, perfect for firmware developers looking to optimize code performance.

How to set up a non-blocking delay function in C without using delay loops?

 

Understanding Non-Blocking Delay

 

In firmware development, using a non-blocking delay allows the CPU to execute other tasks while waiting, thereby improving the efficiency of your program. This is particularly useful in embedded systems, where resources can be limited, and tasks often run concurrently. Instead of blocking the CPU with a busy loop, you can achieve non-blocking behavior using timer-based interrupts or scheduling with a state machine.

 

Using Timer Interrupts

 

To implement a non-blocking delay using timer interrupts, you'll need to utilize hardware timers provided by most microcontroller platforms. This often involves setting up a timer to trigger an interrupt at a specific interval.

Here's a basic outline of steps to achieve this:

  • Initialize the Timer:

    • Enable the timer peripheral.
    • Configure the timer to the desired frequency based on the system clock and required delay.
    • Enable the timer interrupt.
  • Timer Interrupt Service Routine (ISR):

    • Increment a global counter whenever the ISR is triggered.
    • Check if the counter has reached the desired delay time.
    • If so, execute the delayed code and reset the counter.

Example code in C might look like the following:

#include <stdint.h>
#include <stdbool.h>

volatile uint32_t timerCounter = 0;
volatile bool delayCompleted = false;

void Timer_Init(void) {
    // Configuration code for your specific microcontroller timer
    // Set the timer frequency and enable the interrupt
}

void Timer_IRQ_Handler(void) {
    // This function is called when the timer interrupt occurs
    timerCounter++;
    if (timerCounter >= DESIRED_DELAY) {
        delayCompleted = true;
        timerCounter = 0;
    }
}

void NonBlocking_Delay(void) {
    if (delayCompleted) {
        // Execute code after delay
        delayCompleted = false;
    }
}

int main(void) {
    Timer_Init();
    
    while (1) {
        NonBlocking_Delay();
        // Other tasks
    }
}

This code snippet outlines the basic structure for implementing a non-blocking delay with a timer interrupt, though details will vary based on the specific microcontroller architecture and toolchain used.

 

Leveraging a State Machine

 

Another viable approach is to use a state machine pattern, which allows you to check the passage of time at intervals and proceed based on state conditions. This is particularly useful for more complex systems with multiple states or activities.

  • Define States:

    • Establish different states in your firmware where different activities occur based on elapsed time.
  • Use the System Tick:

    • Utilize a system tick timer, often available in real-time operating systems (RTOS) or as part of a microcontroller's peripheral features.

Example code utilizing a simple state machine might look like:

#include <stdint.h>
#include <stdbool.h>

typedef enum {
    STATE_IDLE,
    STATE_DELAY,
    STATE_ACTION
} SystemState;

SystemState currentState = STATE_IDLE;
uint32_t startTime = 0;

uint32_t Get_System_Tick(void) {
    // Function to return system tick or milliseconds since startup
}

void Update_State(void) {
    switch (currentState) {
        case STATE_IDLE:
            // Initialization
            startTime = Get_System_Tick();
            currentState = STATE_DELAY;
            break;
        
        case STATE_DELAY:
            if (Get_System_Tick() - startTime >= DESIRED_DELAY) {
                currentState = STATE_ACTION;
            }
            break;
        
        case STATE_ACTION:
            // Action to be taken after delay
            currentState = STATE_IDLE; // Reset to idle or next state
            break;
    }
}

int main(void) {
    while (1) {
        Update_State();
        // Handle other tasks here
    }
}

This example demonstrates how a state machine can control transitions and timing without blocking the CPU. Again, function implementations would need to be tailored to the specific hardware platform.

 

For both approaches, the non-blocking delay frees up the processor to handle other tasks during the waiting period, making this approach ideal for real-time systems where responsiveness is key. Understanding different methods of implementing non-blocking delay will overall enhance your efficiency as a firmware developer by ensuring that system resources are optimally utilized.

Pre-order Friend AI Necklace

Limited Beta: Claim Your Dev Kit and Start Building Today

Instant transcription

Access hundreds of community apps

Sync seamlessly on iOS & Android

Order Now

Turn Ideas Into Apps & Earn Big

Build apps for the AI wearable revolution, tap into a $100K+ bounty pool, and get noticed by top companies. Whether for fun or productivity, create unique use cases, integrate with real-time transcription, and join a thriving dev community.

Get Developer Kit Now

OMI AI PLATFORM
Remember Every Moment,
Talk to AI and Get Feedback

Omi Necklace

The #1 Open Source AI necklace: Experiment with how you capture and manage conversations.

Build and test with your own Omi Dev Kit 2.

Omi App

Fully Open-Source AI wearable app: build and use reminders, meeting summaries, task suggestions and more. All in one simple app.

Github →

Join the #1 open-source AI wearable community

Build faster and better with 3900+ community members on Omi Discord

Participate in hackathons to expand the Omi platform and win prizes

Participate in hackathons to expand the Omi platform and win prizes

Get cash bounties, free Omi devices and priority access by taking part in community activities

Join our Discord → 

OMI NECKLACE + OMI APP
First & only open-source AI wearable platform

a person looks into the phone with an app for AI Necklace, looking at notes Friend AI Wearable recorded a person looks into the phone with an app for AI Necklace, looking at notes Friend AI Wearable recorded
a person looks into the phone with an app for AI Necklace, looking at notes Friend AI Wearable recorded a person looks into the phone with an app for AI Necklace, looking at notes Friend AI Wearable recorded
online meeting with AI Wearable, showcasing how it works and helps online meeting with AI Wearable, showcasing how it works and helps
online meeting with AI Wearable, showcasing how it works and helps online meeting with AI Wearable, showcasing how it works and helps
App for Friend AI Necklace, showing notes and topics AI Necklace recorded App for Friend AI Necklace, showing notes and topics AI Necklace recorded
App for Friend AI Necklace, showing notes and topics AI Necklace recorded App for Friend AI Necklace, showing notes and topics AI Necklace recorded

OMI NECKLACE: DEV KIT
Order your Omi Dev Kit 2 now and create your use cases

Omi 開発キット 2

無限のカスタマイズ

OMI 開発キット 2

$69.99

Omi AIネックレスで会話を音声化、文字起こし、要約。アクションリストやパーソナライズされたフィードバックを提供し、あなたの第二の脳となって考えや感情を語り合います。iOSとAndroidでご利用いただけます。

  • リアルタイムの会話の書き起こしと処理。
  • 行動項目、要約、思い出
  • Omi ペルソナと会話を活用できる何千ものコミュニティ アプリ

もっと詳しく知る

Omi Dev Kit 2: 新しいレベルのビルド

主な仕様

OMI 開発キット

OMI 開発キット 2

マイクロフォン

はい

はい

バッテリー

4日間(250mAH)

2日間(250mAH)

オンボードメモリ(携帯電話なしで動作)

いいえ

はい

スピーカー

いいえ

はい

プログラム可能なボタン

いいえ

はい

配送予定日

-

1週間

人々が言うこと

「記憶を助ける、

コミュニケーション

ビジネス/人生のパートナーと、

アイデアを捉え、解決する

聴覚チャレンジ」

ネイサン・サッズ

「このデバイスがあればいいのに

去年の夏

記録する

「会話」

クリスY.

「ADHDを治して

私を助けてくれた

整頓された。"

デビッド・ナイ

OMIネックレス:開発キット
脳を次のレベルへ

最新ニュース
フォローして最新情報をいち早く入手しましょう

最新ニュース
フォローして最新情報をいち早く入手しましょう

thought to action.

Based Hardware Inc.
81 Lafayette St, San Francisco, CA 94103
team@basedhardware.com / help@omi.me

Company

Careers

Invest

Privacy

Events

Manifesto

Compliance

Products

Omi

Wrist Band

Omi Apps

omi Dev Kit

omiGPT

Personas

Omi Glass

Resources

Apps

Bounties

Affiliate

Docs

GitHub

Help Center

Feedback

Enterprise

Ambassadors

Resellers

© 2025 Based Hardware. All rights reserved.