|

|  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

Pre-Order Friend Dev Kit

Open-source AI wearable
Build using the power of recall

Order 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 Dev Kit 2

Endless customization

OMI DEV KIT 2

$69.99

Make your life more fun with your AI wearable clone. It gives you thoughts, personalized feedback and becomes your second brain to discuss your thoughts and feelings. Available on iOS and Android.

Your Omi will seamlessly sync with your existing omi persona, giving you a full clone of yourself – with limitless potential for use cases:

  • Real-time conversation transcription and processing;
  • Develop your own use cases for fun and productivity;
  • Hundreds of community apps to make use of your Omi Persona and conversations.

Learn more

Omi Dev Kit 2: build at a new level

Key Specs

OMI DEV KIT

OMI DEV KIT 2

Microphone

Yes

Yes

Battery

4 days (250mAH)

2 days (250mAH)

On-board memory (works without phone)

No

Yes

Speaker

No

Yes

Programmable button

No

Yes

Estimated Delivery 

-

1 week

What people say

“Helping with MEMORY,

COMMUNICATION

with business/life partner,

capturing IDEAS, and solving for

a hearing CHALLENGE."

Nathan Sudds

“I wish I had this device

last summer

to RECORD

A CONVERSATION."

Chris Y.

“Fixed my ADHD and

helped me stay

organized."

David Nigh

OMI NECKLACE: DEV KIT
Take your brain to the next level

LATEST NEWS
Follow and be first in the know

Latest news
FOLLOW AND BE FIRST IN THE KNOW

thought to action

team@basedhardware.com

company

careers

invest

privacy

products

omi

omi dev kit

personas

resources

apps

affiliate

docs

github

help