Skip to main content
Docs navigation

Garage Door Controller

This tutorial tests the state machine of a garage door opener: a button, a photo-eye and two limit switches in, a motor out. Event-driven logic like this is tested with a sequence: open the door, close it, block the photo-eye halfway, stop it, send it back. The tutorial builds on the two before it and covers:

  • scheduling a test as steps and reusable input profiles, with checks in the steps and the number of the first failing step as the run's result;
  • checking a state machine with a Mode rule (allowed transitions and dwell times), a Response rule (a deadline) and an Always rule (a safety invariant);
  • naming the requirements a simulation verifies.

The controller​

State machine of the garage door: CLOSED, OPENING, OPEN, CLOSING, STOPPED and REVERSING, with the transitions between them

  • A press of the wall button opens a closed door and closes an open one. A press while the door moves stops it, and the next press sends it back the way it came.
  • A limit switch at each end stops the motor.
  • If the photo-eye beam is interrupted while the door closes, the door goes back up. An open door doesn't close while the beam is blocked.
  • The motor rests 0.5 s before it changes direction, in REVERSING after an obstruction and in STOPPED after a press. Reversing a motor under load at once stresses the gearbox and the motor drive.
  • A travel that takes longer than 15 s stops the motor: something is jammed.

These are the requirements, with the IDs the simulation reports:

IDRequirementRule
GD-1The door never runs down while the photo-eye is blocked.never closes on an obstruction (Always)
GD-2An obstruction while closing sends the door back up within 1 s.reopens within 1 s (Response)
GD-3The motor rests at least 0.5 s before it changes direction.mode sequence (Mode)
GD-4No travel lasts longer than 15 s.mode sequence (Mode)

garageDoor.h​

#pragma once
#include <stdint.h>

typedef enum
{
DOOR_CLOSED = 0,
DOOR_OPENING = 1,
DOOR_OPEN = 2,
DOOR_CLOSING = 3,
DOOR_STOPPED = 4,
DOOR_REVERSING = 5,
} DoorMode_te;

typedef struct GarageDoor_s
{
/* Configuration */
uint16_t reversePause_ms; /* the motor is off this long before it runs the other way */
uint16_t maxRunTime_ms; /* the longest a single travel may take */

/* Inputs */
uint8_t button; /* wall button, 1 while pressed */
uint8_t obstruction; /* photo-eye beam interrupted */
uint8_t openLimit; /* limit switch: door fully open */
uint8_t closedLimit; /* limit switch: door fully closed */

/* Outputs */
int8_t motor; /* +1 up, -1 down, 0 off */
DoorMode_te mode;

/* State */
uint8_t lastButton;
int8_t lastDirection;
uint16_t modeTime_ms;
} GarageDoor_ts;

void garageDoorInit(GarageDoor_ts *const ctx, uint16_t reversePause_ms, uint16_t maxRunTime_ms);
void garageDoorCyclic(GarageDoor_ts *const ctx, uint16_t cycle_ms);

garageDoor.c​

#include "garageDoor.h"

static void enter(GarageDoor_ts *const ctx, DoorMode_te mode)
{
ctx->mode = mode;
ctx->modeTime_ms = 0;
if (mode == DOOR_OPENING)
ctx->lastDirection = 1;
else if (mode == DOOR_CLOSING)
ctx->lastDirection = -1;
}

void garageDoorInit(GarageDoor_ts *const ctx, uint16_t reversePause_ms, uint16_t maxRunTime_ms)
{
ctx->reversePause_ms = reversePause_ms;
ctx->maxRunTime_ms = maxRunTime_ms;
ctx->button = 0;
ctx->obstruction = 0;
ctx->openLimit = 0;
ctx->closedLimit = 1;
ctx->motor = 0;
ctx->lastButton = 0;
ctx->lastDirection = -1;
enter(ctx, DOOR_CLOSED);
}

void garageDoorCyclic(GarageDoor_ts *const ctx, uint16_t cycle_ms)
{
uint8_t pressed = ctx->button && !ctx->lastButton;
uint8_t timeout;

ctx->lastButton = ctx->button;
if (ctx->modeTime_ms < 60000)
ctx->modeTime_ms += cycle_ms;
timeout = ctx->modeTime_ms >= ctx->maxRunTime_ms;

switch (ctx->mode)
{
case DOOR_CLOSED:
if (pressed)
enter(ctx, DOOR_OPENING);
break;

case DOOR_OPENING:
if (ctx->openLimit)
enter(ctx, DOOR_OPEN);
else if (pressed || timeout)
enter(ctx, DOOR_STOPPED);
break;

case DOOR_OPEN:
if (pressed && !ctx->obstruction)
enter(ctx, DOOR_CLOSING);
break;

case DOOR_CLOSING:
if (ctx->obstruction)
enter(ctx, DOOR_OPENING); /* something in the way: go back up */
else if (ctx->closedLimit)
enter(ctx, DOOR_CLOSED);
else if (pressed || timeout)
enter(ctx, DOOR_STOPPED);
break;

case DOOR_REVERSING:
if (ctx->modeTime_ms >= ctx->reversePause_ms)
enter(ctx, DOOR_OPENING);
break;

case DOOR_STOPPED:
/* The next press runs the door the other way, once the motor has been off long enough */
if (pressed && ctx->modeTime_ms >= ctx->reversePause_ms)
{
if (ctx->lastDirection > 0 && !ctx->obstruction)
enter(ctx, DOOR_CLOSING);
else if (ctx->lastDirection < 0)
enter(ctx, DOOR_OPENING);
}
break;
}

ctx->motor = ctx->mode == DOOR_OPENING ? 1 : ctx->mode == DOOR_CLOSING ? -1 : 0;
}

The simulation​

The simulation: a test input profile drives the button and the photo-eye; the controller drives the door model&#39;s motor; the door model&#39;s limit switches go back to the controller; the rules watch the run

The door model is one line: the motor moves the door at 10 % of its travel per second between its end stops, and the limit switches report the ends.

The test is a list of steps. Each step is a function called every cycle for the step's duration. A stimulus step sets the button or the photo-eye. A check step returns whether the door is where it should be. A step with no function only waits. Pressing and releasing the button is an input profile of its own, press, written once and used throughout.

SimulateGarageDoor.c​

#include <math.h>
#include <stdio.h>
#include <cppmodel/CModel.h>
#include "garageDoor.h"

#define DOOR_SPEED_PCT_PER_S 10.0 /* full travel in 10 s */

static GarageDoor_ts door;
static double position; /* plant: 0 % closed .. 100 % open */
static uint8_t button, obstruction;
static CppModelRule_t neverIntoObstruction, reopens, modeSequence;

/* ---- Stimuli and checks: each runs once per cycle for its duration, and returns whether the cycle passed ---- */

static uint8_t PressButton(CModelSimulation_ts *self, unsigned long t)
{
(void)self, (void)t;
button = 1;
return 1;
}

static uint8_t BlockPhotoEye(CModelSimulation_ts *self, unsigned long t)
{
(void)self, (void)t;
obstruction = 1;
return 1;
}

static uint8_t PressWhileBlocked(CModelSimulation_ts *self, unsigned long t)
{
(void)self, (void)t;
button = 1;
obstruction = 1;
return 1;
}

static uint8_t IsOpen(CModelSimulation_ts *self, unsigned long t)
{
(void)self, (void)t;
return door.mode == DOOR_OPEN && position >= 100.0;
}

static uint8_t IsClosed(CModelSimulation_ts *self, unsigned long t)
{
(void)self, (void)t;
return door.mode == DOOR_CLOSED && position <= 0.0;
}

static uint8_t IsStopped(CModelSimulation_ts *self, unsigned long t)
{
(void)self, (void)t;
return door.mode == DOOR_STOPPED && door.motor == 0;
}

/* Press and release the wall button: written once, used throughout */
static const CppModelStep_ts pressSteps[] = {
CMODEL_STEP(PressButton, 200),
CMODEL_STEP(NULL, 300),
};
static const CppModelInputProfile_ts press = CMODEL_INPUT_PROFILE(pressSteps);

static const CppModelStep_ts testSteps[] = {
/* Open the door */
CMODEL_STEP_INPUT_PROFILE(press),
CMODEL_STEP(NULL, 11000),
CMODEL_STEP(IsOpen, 0),
/* Close it, and block the photo-eye halfway down: it must go back up */
CMODEL_STEP_INPUT_PROFILE(press),
CMODEL_STEP(NULL, 4000),
CMODEL_STEP(BlockPhotoEye, 1000),
CMODEL_STEP(NULL, 6000),
CMODEL_STEP(IsOpen, 0),
/* With the photo-eye blocked, a press doesn't close the door */
CMODEL_STEP(PressWhileBlocked, 200),
CMODEL_STEP(BlockPhotoEye, 2000),
CMODEL_STEP(IsOpen, 0),
/* Stop it halfway down, then send it back up */
CMODEL_STEP_INPUT_PROFILE(press),
CMODEL_STEP(NULL, 4000),
CMODEL_STEP_INPUT_PROFILE(press),
CMODEL_STEP(NULL, 2000),
CMODEL_STEP(IsStopped, 0),
CMODEL_STEP_INPUT_PROFILE(press),
CMODEL_STEP(NULL, 6000),
CMODEL_STEP(IsOpen, 0),
/* Close it all the way */
CMODEL_STEP_INPUT_PROFILE(press),
CMODEL_STEP(NULL, 11000),
CMODEL_STEP(IsClosed, 0),
};
static const CppModelInputProfile_ts test = CMODEL_INPUT_PROFILE(testSteps);

static void Init(CModelSimulation_ts *self, unsigned long stepTime_ms)
{
(void)stepTime_ms;

garageDoorInit(&door,
CppModel_getParameterU16(self, "ReversePause [ms]", 500),
CppModel_getParameterU16(self, "MaxRunTime [ms]", 15000));
position = 0.0;

/* GD-1: the door never runs down while the photo-eye is blocked */
neverIntoObstruction = CppModel_ruleAlways(self, "never closes on an obstruction", 0.0);
CppModel_ruleSignal(neverIntoObstruction, "Door.Motor [%]");

/* GD-2: an obstruction while closing sends the door back up within 1 s */
reopens = CppModel_ruleResponse(self, "reopens within 1 s", 1.0, 0.0);
CppModel_ruleSignal(reopens, "Door.Motor [%]");

/* GD-3: the motor rests 0.5 s before it changes direction; GD-4: no travel lasts longer than 15 s */
modeSequence = CppModel_ruleMode(self, "mode sequence");
CppModel_modeAllow(modeSequence, DOOR_CLOSED, DOOR_OPENING);
CppModel_modeAllow(modeSequence, DOOR_OPENING, DOOR_OPEN);
CppModel_modeAllow(modeSequence, DOOR_OPENING, DOOR_STOPPED);
CppModel_modeAllow(modeSequence, DOOR_OPEN, DOOR_CLOSING);
CppModel_modeAllow(modeSequence, DOOR_CLOSING, DOOR_CLOSED);
CppModel_modeAllow(modeSequence, DOOR_CLOSING, DOOR_STOPPED);
CppModel_modeAllow(modeSequence, DOOR_CLOSING, DOOR_REVERSING);
CppModel_modeAllow(modeSequence, DOOR_REVERSING, DOOR_OPENING);
CppModel_modeAllow(modeSequence, DOOR_STOPPED, DOOR_OPENING);
CppModel_modeAllow(modeSequence, DOOR_STOPPED, DOOR_CLOSING);
CppModel_modeDwell(modeSequence, DOOR_REVERSING, 0.5, NAN);
CppModel_modeDwell(modeSequence, DOOR_STOPPED, 0.5, NAN);
CppModel_modeDwell(modeSequence, DOOR_OPENING, NAN, 15.0);
CppModel_modeDwell(modeSequence, DOOR_CLOSING, NAN, 15.0);
CppModel_ruleSignal(modeSequence, "Door.Mode");

CppModel_verifyRequirement(self, "GD-1");
CppModel_verifyRequirement(self, "GD-2");
CppModel_verifyRequirement(self, "GD-3");
CppModel_verifyRequirement(self, "GD-4");
}

void RunCyclic(CModelSimulation_ts *self, unsigned long currentTime_ms)
{
double dt_s = self->stepTime_ms / 1000.0;
uint8_t passed, obstructedWhileClosing;

/* The running step sets the stimuli and checks the door */
button = 0;
obstruction = 0;
passed = CppModel_runInputProfile(self, &test, currentTime_ms);

door.button = CppModel_getInputU8(self, "Button", button);
door.obstruction = CppModel_getInputU8(self, "PhotoEye.Blocked", obstruction);
door.openLimit = position >= 100.0;
door.closedLimit = position <= 0.0;
obstructedWhileClosing = door.obstruction && door.motor < 0;

/* Controller under test */
garageDoorCyclic(&door, (uint16_t)self->stepTime_ms);

/* Plant model: the motor moves the door at constant speed between its end stops */
position += door.motor * DOOR_SPEED_PCT_PER_S * dt_s;
position = position < 0.0 ? 0.0 : position > 100.0 ? 100.0 : position;

CppModel_setOutputF64(self, "Door.Position [%]", position);
CppModel_setOutputI8(self, "Door.Motor [%]", (int8_t)(door.motor * 100));
CppModel_setOutputI32(self, "Door.Mode", door.mode);

CppModel_updateAlways(neverIntoObstruction,
CppModel_implies(CppModel_condition(door.obstruction), CppModel_condition(door.motor >= 0)));
CppModel_updateResponse(reopens, obstructedWhileClosing, door.motor > 0);
CppModel_updateMode(modeSequence, door.mode);

CppModel_setOutputU8(self, "CppModel.StepResult", passed);
}

int main(void)
{
CModelSimulation_ts *simulation = CppModel_create("GarageDoor", CppModel_inputProfileDuration(&test, 10), 10);
if (simulation == NULL)
return 1;

CppModel_setInitFunction(simulation, Init);
CppModel_setRunStepFunction(simulation, RunCyclic);
CppModel_Simulate(simulation);

int result = CppModel_getSimulationResult(simulation);
CppModel_destroy(simulation);

if (result != 0)
printf("First failing step: %d\n", result);
return result == 0 ? 0 : 1;
}
  • Every cycle, RunCyclic() clears the stimuli and lets CppModel_runInputProfile() run the current step, which sets them again. The library finds the step from the simulation time, so the steps need no state machine of their own.
  • CppModel_inputProfileDuration(&test, 10) gives the length of the whole test, 50.26 s, to create the simulation with. Adding a step makes the run longer by itself.
  • The checks' results go into CppModel.StepResult. The rules fail their steps by themselves.
  • The Mode rule lists every allowed transition. Any other change of Door.Mode fails, and so does leaving REVERSING or STOPPED before 0.5 s, or staying in OPENING or CLOSING for more than 15 s.
  • CppModel_verifyRequirement() in Init() records that the simulation verifies GD-1 to GD-4 for the whole run.

CMakeLists.txt​

cmake_minimum_required(VERSION 3.21)

project(GarageDoor LANGUAGES C)

list(APPEND CMAKE_PREFIX_PATH "${CMAKE_SOURCE_DIR}/dependencies")
find_package(cppmodel REQUIRED)

enable_testing()

add_executable(SimulateGarageDoor garageDoor.c SimulateGarageDoor.c)
target_link_libraries(SimulateGarageDoor PRIVATE cppmodel::cppmodel)
cppmodel_deploy_runtime(SimulateGarageDoor)

add_test(NAME GarageDoor COMMAND SimulateGarageDoor)
cmake -S . -B build
cmake --build build
./build/SimulateGarageDoor

The CMake file assumes the CppModel library is extracted into a dependencies folder (see Installation).

Results​

Every check passes. The door opens, goes back up when the photo-eye is blocked, stays open while it is blocked, stops and reverses, and closes. But a rule fails, and the program exits with 1:

CppModel.Verify.never closes on an obstruction: PASS held at 5027 checked step(s)
CppModel.Verify.reopens within 1 s: PASS 1 trigger(s) answered, slowest in 0 s (deadline 1 s)
CppModel.Verify.mode sequence: FAIL illegal transition 3 → 1 at t=16.01 s
CppModel.Verify: 2 of 3 rules passed
CppModel.Requirements: GD-1, GD-2, GD-3, GD-4
...
First failing step: 8

A failed run's result is the number of its first failing step, and main() prints it. Step 8 is BlockPhotoEye, so a CI log already says where to look, without opening the workspace. The exit code itself is only 0 or 1: exit codes keep 8 bits, so a failure at step 256 would otherwise exit with 0 and pass CI.

The door is closing when the photo-eye is blocked at 16 s; the motor goes from −100 % to +100 % in one cycle, and the mode rule marks the illegal transition from CLOSING to OPENING

The mode strip under the graph shows the transition: CLOSING to OPENING in one 10 ms cycle, and the motor from full down to full up with it. The door does go back up, so a test that only checks that it reopens passes. reopens within 1 s passed too, with a response time of 0 s. But GD-3 requires a rest before the motor changes direction, and the Mode rule doesn't allow CLOSING to OPENING.

The bug is one line: the controller has a REVERSING state for exactly this case, and DOOR_CLOSING never enters it.

The fix​

 
case DOOR_CLOSING:
if (ctx->obstruction)
- enter(ctx, DOOR_OPENING); /* something in the way: go back up */
+ enter(ctx, DOOR_REVERSING); /* something in the way: stop, then go back up */
else if (ctx->closedLimit)
enter(ctx, DOOR_CLOSED);
else if (pressed || timeout)
CppModel.Verify.never closes on an obstruction: PASS held at 5027 checked step(s)
CppModel.Verify.reopens within 1 s: PASS 1 trigger(s) answered, slowest in 0.5 s (deadline 1 s)
CppModel.Verify.mode sequence: PASS 11 transition(s), all allowed; lowest dwell margin 0 s
CppModel.Verify: 3 of 3 rules passed
CppModel.Requirements: GD-1, GD-2, GD-3, GD-4

After the fix: the motor stops when the photo-eye is blocked, rests for 0.5 s in REVERSING, then opens the door; the response arrives 0.5 s into the 1 s window

The motor now stops in the same cycle as the photo-eye is blocked, rests 0.5 s in REVERSING and then opens the door. The response arrives 0.5 s into the 1 s allowed. The whole test, with the step number of each part under the graph:

The whole test: open, close with an obstruction, a press while blocked, stop and reverse, and close

Reading the margins​

lowest dwell margin 0 s means that the rest in REVERSING is exactly the 0.5 s GD-3 asks for, with nothing to spare. The run passes, but any shorter pause fails. Try it without rebuilding:

short-pause.json

{ "parameters": { "ReversePause [ms]": 300 } }
./build/SimulateGarageDoor --inputs short-pause.json
CppModel.Verify.mode sequence: FAIL left mode 5 after 0.3 s at t=16.31 s (min dwell 0.5 s)

A margin tells you how close a passing run came to failing, so you know which requirements a change of parameters or timing could break.

Requirement coverage​

Every run writes the requirements it verified, and whether it passed, to cppmodel-requirements.json in the working directory:

{
"GarageDoor": {
"passed": true,
"requirements": {
"GD-1": { "from_s": null, "steps": 0, "to_s": null, "whole_run": true },
"GD-2": { "from_s": null, "steps": 0, "to_s": null, "whole_run": true },
...

A CI job that runs all simulations can collect this file into a coverage report: which requirements are verified, by which simulation, and whether they passed. See Requirements.

Try it yourself​

  • Add a step that presses the button twice within 0.3 s while the door is moving. The second press must be ignored, and the Mode rule checks that the motor rests in STOPPED.
  • Jam the door: make the model stop moving between 40 % and 50 % while the motor runs down. The 15 s run-time limit must stop the motor.
  • Record GD-2 only while the door is closing with the photo-eye blocked, by calling CppModel_verifyRequirement() in RunCyclic() at those steps instead of in Init(). The coverage file then shows when it was exercised.

More on the API: Steps and Input Profiles and Verification Rules.

Source code​

The complete project, with short-pause.json, is on GitHub: Control-Edge/garage-door-controller, under the MIT license.