Home Learning Paths ECU Lab Assessments Interview Preparation Arena Pricing Log In Sign Up

Binary and Counting Semaphores

Csemaphores.c
#include "FreeRTOS.h"
#include "semphr.h"

/* Binary semaphore: signal between ISR and task */
/* ISR "gives" (signals); task "takes" (waits) */
static SemaphoreHandle_t g_can_rx_sem;
static StaticSemaphore_t g_can_rx_sem_buf;

void Init(void) {
    g_can_rx_sem = xSemaphoreCreateBinaryStatic(&g_can_rx_sem_buf);
}

/* ISR: give semaphore (non-blocking, from ISR context) */
void CAN0_RX_ISR(void) {
    BaseType_t higher_prio_woken = pdFALSE;
    xSemaphoreGiveFromISR(g_can_rx_sem, &higher_prio_woken);
    portYIELD_FROM_ISR(higher_prio_woken);  /* yield if higher-prio task unblocked */
}

/* Task: wait for semaphore (blocks until ISR signals) */
void Task_ProcessCan(void *p) {
    (void)p;
    for (;;) {
        if (xSemaphoreTake(g_can_rx_sem, pdMS_TO_TICKS(10u)) == pdTRUE) {
            process_can_message();  /* process the received frame */
        }
        /* else: timeout — handle missing message */
    }
}

/* Counting semaphore: track available resources or event count */
static SemaphoreHandle_t g_free_buf_count;

void Pool_Init(void) {
    /* 8 free buffers initially */
    g_free_buf_count = xSemaphoreCreateCounting(8u, 8u);
}
uint8_t *Pool_Alloc(void) {
    if (xSemaphoreTake(g_free_buf_count, 0u) == pdTRUE) {
        return get_next_free_buffer();
    }
    return NULL;  /* no buffers available */
}
void Pool_Free(uint8_t *buf) {
    return_buffer(buf);
    xSemaphoreGive(g_free_buf_count);  /* increment count */
}

Mutexes: Mutual Exclusion with Priority Inheritance

Cmutexes.c
#include "FreeRTOS.h"
#include "semphr.h"

/* Mutex: protects shared resource; prevents priority inversion via inheritance */
static SemaphoreHandle_t g_spi_mutex;
static StaticSemaphore_t g_spi_mutex_buf;

void Spi_Init(void) {
    g_spi_mutex = xSemaphoreCreateMutexStatic(&g_spi_mutex_buf);
}

/* Both tasks share SPI bus; mutex ensures one at a time */
Std_ReturnType Spi_Transfer(const uint8_t *tx, uint8_t *rx, uint8_t len)
{
    if (xSemaphoreTake(g_spi_mutex, pdMS_TO_TICKS(50u)) != pdTRUE) {
        return E_NOT_OK;  /* timeout: SPI bus busy */
    }

    /* Critical section: exclusive SPI access */
    Std_ReturnType ret = Spi_DoTransfer_Internal(tx, rx, len);

    xSemaphoreGive(g_spi_mutex);  /* ALWAYS release, even if transfer failed */
    return ret;
}

/* NEVER take a mutex from ISR context — use binary semaphore instead */
/* NEVER take mutex from ISR: causes priority inversion + potential deadlock */

/* Key difference: mutex vs semaphore
   Mutex: ownership (only the taker can release); priority inheritance
   Semaphore: no ownership (any task/ISR can give); no priority inheritance */

Message Queues: Inter-Task Data Transfer

Cmessage_queues.c
#include "FreeRTOS.h"
#include "queue.h"

typedef struct {
    uint16_t id;
    uint8_t  dlc;
    uint8_t  data[8];
} CanFrame_t;

#define CAN_QUEUE_DEPTH  16u
static QueueHandle_t g_can_rx_queue;
static StaticQueue_t g_can_rx_queue_buf;
static uint8_t       g_can_rx_queue_storage[CAN_QUEUE_DEPTH * sizeof(CanFrame_t)];

void CanQueue_Init(void) {
    g_can_rx_queue = xQueueCreateStatic(
        CAN_QUEUE_DEPTH, sizeof(CanFrame_t),
        g_can_rx_queue_storage, &g_can_rx_queue_buf);
}

/* ISR: enqueue received frame */
void CAN0_RX_ISR(void) {
    CanFrame_t frame;
    frame.id  = CAN0_RXID_REG & 0x7FFu;
    frame.dlc = (uint8_t)(CAN0_RXCTRL_REG & 0x0Fu);
    read_can_data(frame.data, frame.dlc);

    BaseType_t hp_woken = pdFALSE;
    if (xQueueSendFromISR(g_can_rx_queue, &frame, &hp_woken) != pdTRUE) {
        /* Queue full: increment overflow counter */
        g_can_rx_overflow++;
    }
    portYIELD_FROM_ISR(hp_woken);
}

/* Task: dequeue and process */
void Task_CanProcess(void *p) {
    CanFrame_t frame;
    for (;;) {
        if (xQueueReceive(g_can_rx_queue, &frame, portMAX_DELAY) == pdTRUE) {
            App_ProcessCanFrame(&frame);
        }
    }
}

Summary

Binary semaphores signal events between ISRs and tasks; mutexes protect shared resources with ownership semantics and priority inheritance; message queues transfer data copies between tasks. The ownership rule for mutexes is non-negotiable: never give a mutex from a different task than the one that took it, and never take a mutex from an ISR context. For AUTOSAR OSEK, Queues are replaced by event flags (AUTOSAR OS events) and resource locks (Res/GetResource); FreeRTOS queues map conceptually to AUTOSAR message queues (COM) and RTE buffers.

🔬 Deep Dive — Core Concepts Expanded

This section builds on the foundational concepts covered above with additional technical depth, edge cases, and configuration nuances that separate competent engineers from experts. When working on production ECU projects, the details covered here are the ones most commonly responsible for integration delays and late-phase defects.

Key principles to reinforce:

  • Configuration over coding: In AUTOSAR and automotive middleware environments, correctness is largely determined by ARXML configuration, not application code. A correctly implemented algorithm can produce wrong results due to a single misconfigured parameter.
  • Traceability as a first-class concern: Every configuration decision should be traceable to a requirement, safety goal, or architecture decision. Undocumented configuration choices are a common source of regression defects when ECUs are updated.
  • Cross-module dependencies: In tightly integrated automotive software stacks, changing one module's configuration often requires corresponding updates in dependent modules. Always perform a dependency impact analysis before submitting configuration changes.

🏭 How This Topic Appears in Production Projects

  • Project integration phase: The concepts covered in this lesson are most commonly encountered during ECU integration testing — when multiple software components from different teams are combined for the first time. Issues that were invisible in unit tests frequently surface at this stage.
  • Supplier/OEM interface: This is a topic that frequently appears in technical discussions between Tier-1 ECU suppliers and OEM system integrators. Engineers who can speak fluently about these details earn credibility and are often brought into critical design review meetings.
  • Automotive tool ecosystem: Vector CANoe/CANalyzer, dSPACE tools, and ETAS INCA are the standard tools used to validate and measure the correct behaviour of the systems described in this lesson. Familiarity with these tools alongside the conceptual knowledge dramatically accelerates debugging in real projects.

⚠️ Common Mistakes and How to Avoid Them

  1. Assuming default configuration is correct: Automotive software tools ship with default configurations that are designed to compile and link, not to meet project-specific requirements. Every configuration parameter needs to be consciously set. 'It compiled' is not the same as 'it is correctly configured'.
  2. Skipping documentation of configuration rationale: In a 3-year ECU project with team turnover, undocumented configuration choices become tribal knowledge that disappears when engineers leave. Document why a parameter is set to a specific value, not just what it is set to.
  3. Testing only the happy path: Automotive ECUs must behave correctly under fault conditions, voltage variations, and communication errors. Always test the error handling paths as rigorously as the nominal operation. Many production escapes originate in untested error branches.
  4. Version mismatches between teams: In a multi-team project, the BSW team, SWC team, and system integration team may use different versions of the same ARXML file. Version management of all ARXML files in a shared repository is mandatory, not optional.

📊 Industry Note

Engineers who master both the theoretical concepts and the practical toolchain skills covered in this course are among the most sought-after professionals in the automotive software industry. The combination of AUTOSAR standards knowledge, safety engineering understanding, and hands-on configuration experience commands premium salaries at OEMs and Tier-1 suppliers globally.

← PreviousRTOS Concepts: Tasks, Scheduling & PrioritiesNext →Deadlock Prevention & Priority Inversion