motor · 3radio · 2log · 1CPU1lock = xSemaphoreCreateBinary();2xSemaphoreTake(lock, LIMIT);3readSensor(); // I2C bus4xSemaphoreGive(lock);I2C sensorbinaryblockedHML
motor 3radio 2log 1024681012ms33deadline 7 ms5 ms late1 ms sparemissed
Back: three tasks, the CPU, the lock and the I2C sensor it guardsFront: the code and a timeline of who ran in each 1 ms tickMovers: a puck per task on the CPU, the key to the lockThree FreeRTOS tasks on one CPU share an I2C bus guarded by one lock: motor (priority 3, deadline 7 ms), radio (2) and log (1). With a binary semaphore, log holds the lock, motor waits for it, and radio runs in between: motor finishes at 12 ms, 5 ms late. With a mutex, log inherits priority 3 while motor waits, so radio cannot cut in and motor finishes at 6 ms.

Locks and priorities

  1. One core runs three FreeRTOS tasks. motor has priority 3, radio 2, log 1; a bigger number is more urgent. The scheduler always runs the most urgent task that is ready. Each tick is 1 ms.

The inversion

Inheritance

What happens

;; step 1/11 · tasks
priority   bigger number = more urgent (0 is the idle task)
  motor  3   drives the motor; must finish 6 ms after it wakes
  radio  2   sends a radio packet; never touches the bus
  log    1   reads a sensor on the I2C bus for the log
rule       run the highest-priority task that is ready
tick       1 ms  (configTICK_RATE_HZ 1000)

The task lengths are our example, chosen to make the effect easy to see, on an STM32F407 (single-core Arm Cortex-M4) with a 1 ms tick. readSensor() and sendPacket() stand for real I2C and radio drivers. With one core only one task can run at a time; dual-core chips such as the ESP32 add more cases. A binary semaphore made with xSemaphoreCreateBinary() starts empty: it must be given once before anyone can take it. Used as a lock it works, but it has no priority inheritance. That is why FreeRTOS tells you to guard shared parts with a mutex.