EAZYLife STEM LAB · MODULE 18

Embedded Systems Design and Real-Time Control

Move from writing code that works to engineering a system that behaves predictably. Define requirements, structure firmware, schedule recurring work, manage deadlines and design safe responses to faults.

Free open lesson System design Real-time concepts
SENSE · DECIDE · ACT · VERIFY
01 · FROM IDEA TO REQUIREMENTS

Design the behaviour before writing the code

An embedded system is a combination of hardware, firmware, power, mechanical interfaces and the environment in which it operates. A clear requirement describes what the system must do, under what conditions, and how success will be measured.

Typical embedded-system architecture

PhysicalprocessSensors /inputsControllerfirmwarelogic + timingDrivers /outputsActuators/ displayPower, protection and resetsupports every blockFeedback from the physical process closes the control loop.Physical response is measured again

Conceptual architecture. Real products may include multiple controllers, communication links, safety interlocks, power domains and independent protection.

Turn vague ideas into testable requirements

Instead of “the pump should work automatically”, specify the sensed condition, start/stop thresholds, response time, maximum run duration, manual override, sensor-failure response and how operation is indicated.

Separate functional and non-functional requirements

Functional requirements describe actions and modes. Non-functional requirements include timing, reliability, power consumption, environmental range, maintainability, cost, safety and security.

Example requirement checklist

  • Inputs: which sensors, switches and communication messages are accepted?
  • Outputs: which indicators, drivers and actuators are controlled?
  • Timing: how quickly must each input be sampled and each action occur?
  • Faults: what if a sensor is disconnected, a value is implausible or communication stops?
  • Recovery: does the system retry, enter a safe state, require reset or report a fault?
  • Verification: what measurement or test proves each requirement is met?
02 · FIRMWARE STRUCTURE

Divide the program into clear responsibilities

A maintainable controller separates hardware access, input processing, decision logic, output control, communications and diagnostics. Each part should have a clear purpose and well-defined data passed between it and the rest of the program.

Layered firmware structure

Application logic / state machineServices: scheduling, filtering, communicationDrivers: GPIO, ADC, timers, busesHardware: MCU, sensors, drivers, actuators

This is a design aid, not a required software architecture. Small sketches may not need formal layers, but separating responsibilities still improves clarity.

Keep hardware details out of decisions

Convert a raw ADC count into a meaningful engineering value in one place. Let the application logic use that value and avoid scattering pin numbers and register details throughout the decision code.

Use explicit interfaces

Functions should state what they read, calculate or change. Avoid hidden side effects, unexplained global variables and multiple parts of the program writing the same actuator command.

03 · STATE MACHINES

Make operating modes explicit

A finite-state machine (FSM) represents a system using a limited set of named states and defined transitions. It is useful for machines with startup, standby, running, paused, fault and recovery modes.

Example: controller state flow

STARTUPIDLERUNNINGFAULTchecks passstart requestfault detectedsafe resetstop request

Illustrative state flow. A fault transition should put outputs into a defined safe condition; resetting the software state does not automatically remove a physical hazard.

Simple state-machine code pattern

enum State { STARTUP, IDLE, RUNNING, FAULT };
State state = STARTUP;

void loop() {
  readInputs();
  updateMeasurements();

  switch (state) {
    case STARTUP:
      setSafeOutputs();
      if (selfChecksPass()) state = IDLE;
      else state = FAULT;
      break;

    case IDLE:
      setSafeOutputs();
      if (startRequested()) state = RUNNING;
      break;

    case RUNNING:
      if (faultDetected()) {
        setSafeOutputs();
        state = FAULT;
      } else if (stopRequested()) {
        setSafeOutputs();
        state = IDLE;
      } else {
        runControlAction();
      }
      break;

    case FAULT:
      setSafeOutputs();
      reportFault();
      if (safeResetRequested() && selfChecksPass())
        state = STARTUP;
      break;
  }
}

The functions are placeholders to show structure. Real fault handling must be designed for the physical system, including independent hardware protection where needed.

04 · REAL-TIME SYSTEMS

Correct results must arrive at the right time

A real-time system is one whose correctness depends on both the result and when that result is produced. Real-time does not simply mean “fast”. A predictable response within a defined deadline can matter more than maximum processing speed.

Hard real-time

Missing a deadline is considered system failure. Examples can include certain protection or motion-control functions, depending on the system's safety and performance requirements.

Soft real-time

Late results reduce quality but may not cause total failure. Examples include user-interface refresh, audio buffering and non-critical telemetry.

Latency

The time from an event occurring to the system responding. It includes sampling delay, processing, scheduling, communication and output-driver response.

Jitter

Variation in the timing of repeated events. A periodic task scheduled every 10 ms but sometimes running after 9 ms and sometimes after 15 ms has timing variation.

Timing budget

Event receivedSample inputCompute decisionCommunicateUpdate outputDeadlineIllustrative timing budget, not to scale

Measure worst-case execution time and account for interrupts, communication waits and competing tasks. Average execution time alone does not prove a deadline will always be met.

05 · SCHEDULING AND TASK DESIGN

Coordinate recurring work

Small microcontrollers often run a cooperative superloop: each task performs a bounded amount of work and returns. Larger systems may use a real-time operating system (RTOS) with tasks, priorities, queues, semaphores and a scheduler.

Cooperative superloop

  • Simple and has low overhead.
  • Tasks must avoid long blocking operations.
  • One slow task delays everything after it.
  • Good for modest projects with manageable timing demands.

RTOS-based design

  • Separates work into independently scheduled tasks.
  • Can support priorities, synchronisation and message queues.
  • Introduces stack, scheduling and concurrency complexity.
  • Requires careful protection of shared resources.

Example periodic task plan

TaskExample periodPurposeDesign note
Input sampling5 msRead button or fast sensorFilter/debounce separately as appropriate.
Control update10 msUpdate control outputKeep timing consistent; validate the control algorithm.
Display update100 msRefresh user displayDo not let display writes block urgent work.
Telemetry500 msReport statusBuffer or limit communication work.

These periods are illustrative only. Choose real periods from sensor dynamics, actuator response, system bandwidth and deadline analysis.

Interactive task timing estimator

Estimate how much of a repeating schedule is consumed by the execution time of one task.

CPU time used by this task15%
Time remaining in period17 ms
Deadline statusWithin period

Single-task estimate only. It excludes interrupts, other tasks, blocking and scheduling overhead.

06 · WATCHDOGS, FAULTS AND SAFE STATES

Plan for things to go wrong

A robust controller detects abnormal conditions and responds deliberately. A watchdog timer can reset a controller if the firmware stops servicing it, but it is not a substitute for fault detection, safe output design or independent protection.

Fault detection and recovery path

MonitorsystemDetectfaultSafe outputstateRecoverychecksReturn to operation only when recovery conditions are satisfied

Watchdog timer

A watchdog expects firmware to refresh it within a configured interval. If the system hangs and fails to refresh it, the watchdog can trigger a reset. Feed it only after critical tasks have demonstrated healthy progress; blindly refreshing it from a timer interrupt can hide a stalled application.

Safe-state design

Define the output condition that reduces risk when a fault occurs. Depending on the machine, that may mean de-energising an actuator, closing a valve, applying a controlled stop or maintaining power to a safety function. “All outputs off” is not universally safe.

Independent protection

Use hardware limits, fuses, thermal cut-outs, interlocks and emergency-stop circuits where the hazard analysis requires them. Software alone should not be the only barrier against dangerous energy or motion.

Fault logging

Record fault codes, time, relevant sensor values and reset cause where practical. Avoid repeatedly writing non-volatile memory at high frequency; consider endurance and power-loss behaviour.

07 · CONTROL LOOPS AND FEEDBACK

Measure the result, not just the command

Open-loop control issues a command without measuring the result. Closed-loop control measures the process output and compares it with a desired reference. The difference is the error signal used by the controller to adjust the actuator command.

Closed-loop control block diagram

ΣControllerDriverPlantSensor / feedbackSetpointOutputError

Sampling period

The controller samples the process at defined intervals. Too slow a sample rate can miss changes; too fast a rate can waste resources or amplify measurement noise. Select it from the process dynamics and control design.

Stability and saturation

Actuator limits, delays, sensor filtering and excessive controller gain can cause oscillation or poor response. A real controller must account for output limits, startup, faults and recovery, not just its ideal equation.

08 · PRACTICAL BUILD

Build a timed pedestrian-crossing controller

This low-voltage model uses LEDs and a button to demonstrate state machines, event handling, non-blocking timing and predictable sequences. It is an educational tabletop model, not a certified traffic-control device.

Connection schematic

Arduino Uno*D8 · REDD9 · AMBERD10 · GREEND2 · REQUEST330Ω330Ω330ΩButtonGNDLEDsD2 to GND

*For a 5 V Uno-compatible board. Each LED needs its own correctly calculated current-limiting resistor; 330 Ω is an example for common indicator LEDs. LED anodes face the resistor/output pin and cathodes go to GND. Button uses INPUT_PULLUP. Verify your board pinout.

Parts and wiring

  • Arduino Uno-compatible board, USB cable and breadboard.
  • Three LEDs: red, amber and green; three suitable resistors.
  • One normally-open push button and jumper wires.
  • LEDs from D8, D9 and D10 through separate resistors to GND.
  • Button between D2 and GND; enable internal pull-up.

Controller behaviour

  1. Startup shows green vehicle signal.
  2. A button press requests a pedestrian crossing.
  3. Green changes to amber, then red.
  4. Red remains on for the crossing interval.
  5. Amber then green returns the model to normal.
  6. Further requests are queued only as one pending request.

Arduino sketch: non-blocking state machine

const byte redPin = 8;
const byte amberPin = 9;
const byte greenPin = 10;
const byte requestPin = 2;

enum State { VEHICLE_GREEN, VEHICLE_AMBER,
             PEDESTRIAN_RED, RETURN_AMBER };
State state = VEHICLE_GREEN;

const unsigned long greenMinMs = 3000;
const unsigned long amberMs = 1500;
const unsigned long crossingMs = 4000;
unsigned long stateStarted = 0;
bool requestPending = false;
bool previousButton = HIGH;

void showLamps(bool red, bool amber, bool green) {
  digitalWrite(redPin, red);
  digitalWrite(amberPin, amber);
  digitalWrite(greenPin, green);
}

void enterState(State next, unsigned long now) {
  state = next;
  stateStarted = now;
  switch (state) {
    case VEHICLE_GREEN: showLamps(LOW, LOW, HIGH); break;
    case VEHICLE_AMBER: showLamps(LOW, HIGH, LOW); break;
    case PEDESTRIAN_RED: showLamps(HIGH, LOW, LOW); break;
    case RETURN_AMBER: showLamps(LOW, HIGH, LOW); break;
  }
}

void setup() {
  pinMode(redPin, OUTPUT);
  pinMode(amberPin, OUTPUT);
  pinMode(greenPin, OUTPUT);
  pinMode(requestPin, INPUT_PULLUP);
  enterState(VEHICLE_GREEN, millis());
}

void loop() {
  unsigned long now = millis();
  bool button = digitalRead(requestPin);

  if (previousButton == HIGH && button == LOW)
    requestPending = true;
  previousButton = button;

  switch (state) {
    case VEHICLE_GREEN:
      if (requestPending &&
          now - stateStarted >= greenMinMs) {
        requestPending = false;
        enterState(VEHICLE_AMBER, now);
      }
      break;

    case VEHICLE_AMBER:
      if (now - stateStarted >= amberMs)
        enterState(PEDESTRIAN_RED, now);
      break;

    case PEDESTRIAN_RED:
      if (now - stateStarted >= crossingMs)
        enterState(RETURN_AMBER, now);
      break;

    case RETURN_AMBER:
      if (now - stateStarted >= amberMs)
        enterState(VEHICLE_GREEN, now);
      break;
  }
}

Educational sequence only. This sketch omits certified pedestrian indicators, conflict monitoring, fault-tolerant lamp drivers, independent safety circuits and formal timing validation. It must not control a real road crossing.

Observe and investigate

  1. Upload the sketch and observe the startup state.
  2. Press the request button during green. Confirm the minimum green time is respected.
  3. Press again while a sequence is running. Observe the single pending-request behaviour.
  4. Change one timing constant and document how the sequence changes.
  5. Temporarily disconnect the button and observe the pull-up input behaviour.
  6. Draw the state transition diagram from the code and identify the timing deadline for each transition.
09 · TESTING AND VERIFICATION

Prove the system meets its requirements

Unit testing

Test a small function or module independently, such as a sensor conversion, filter, state transition or communication parser.

Integration testing

Check that sensors, firmware, drivers and actuators work together, including their voltage levels, timing and failure responses.

Boundary testing

Try minimum and maximum values, threshold edges, invalid inputs, time rollover and communication timeouts.

Fault injection

In a safe test setup, simulate a disconnected sensor, stuck input, invalid reading or lost message. Confirm the documented response occurs.

Timing verification

Measure task duration and response latency using a GPIO timing marker, logic analyser or oscilloscope. Test under the busiest expected operating conditions.

Regression testing

Repeat earlier tests after changes to catch faults introduced by new features, libraries, configuration or wiring.

10 · SAFETY AND KNOWLEDGE CHECK

Engineering responsibility is part of the design

Safety boundaries

  • Keep this practical at extra-low voltage and use indicator LEDs only.
  • Never use this educational sketch for real traffic signals, machinery or life-safety control.
  • Use independent hardware interlocks and protection where a hazard analysis requires them.
  • Do not assume a watchdog guarantees a safe shutdown.
  • Verify power, grounding, driver ratings, thermal limits and component datasheets.
  • Test faults in a controlled setup that cannot cause injury or equipment damage.

Professional design record

Keep requirements, block diagrams, state charts, pin maps, timing budgets, test cases, firmware versions, known limitations and change history together. This makes the system easier to review, reproduce and maintain.

1. What makes a system real-time?

2. Why use a finite-state machine?

3. What does a watchdog timer help detect?

4. Does turning every output off always create a safe state?

KEEP LEARNING · GO FURTHER

Free to learn. More support when you need it.

Explore these open lessons at your own pace. For personalised explanations, project-specific troubleshooting, guided practical training or masterclasses, EazyLife offers paid support tailored to your learning goals.

Free or sponsored lesson referrals may be available through active programmes; they are not guaranteed.

Enquire about guidance