Embedded firmware · 2018

One sensor board,
two firmwares

Firmware for an ARM Cortex-M4 (Atmel SAM4S) sensor node: first in C on top of the Atmel Software Framework, then rewritten in C++ without vendor libraries, following the layered design of Real-Time C++.

The board monitored an industrial cooling machine. This page is about how the software was built.

// src/sys/app/sys_tick_chrono_test.cpp
mcal::init();

mcal::port::port_pin<std::uint32_t,
                     std::uint32_t,
                     0x400E1200,     // PIOC
                     UINT32_C(23)>  // PC23
    yellow_led_pin;

yellow_led_pin.set_direction_output();

while (1) {
  yellow_led_pin.set_pin_high();
  timer_type::blocking_delay(timer_type::seconds(1U));
  yellow_led_pin.set_pin_low();
  timer_type::blocking_delay(timer_type::seconds(1U));
}
SAM4SCortex-M4
2firmware versions
7device drivers (C)
10SAM4S MCAL modules
19test programs
C++11no exceptions, no RTTI

Overview

A single microcontroller collects a handful of signals and sends them to a server every few minutes. Simple on paper; the interesting part was how to structure the code so it could be tested piece by piece and carried to other boards.

What the board does

  • Two SHT20 temperature/humidity sensors on two I2C buses.
  • Motor current with SCT-013 clamps on the ADC (single or three phase), integrated every 100 ms into energy.
  • Coolant flow from a YF-S201C pulse sensor.
  • A relay to enable the machine, settings kept in internal flash.
  • Telemetry as HTTP POST through a Cinterion BGS2 GPRS modem; configuration downloaded the same way.
  • RS-485 and an RF link planned for remote sensors; an address encoder on GPIO.

Development setup

  • SAM4S Xplained Pro evaluation board, then the custom board (ATSAM4S16C).
  • Atmel Studio 7 and ASF 3.x for the C version, J-Link for debugging.
  • GNU Arm Embedded Toolchain (gcc 7, 2018-q2), plain Makefiles and edbg for the C++ version.
  • The message framework also builds for Linux, so protocol code was tested on the PC with pipes before touching the hardware.
  • PlantUML for the class diagram, ProjectLibre for planning.
System diagram: ATSAM4S16C connected to two temperature/humidity sensors over I2C, a GPRS modem and an RF module over USART, a relay and ADC inputs (flow meter and three current sensors), RS-485 over UART, a JTAG debug port and a GPIO address encoder

System diagram from the design notes (2018). The ADC inputs are multiplexed; RS-485 uses the USART RS485 mode of the SAM4S.

Version 1: C on ASF

The base version that ran on the board. An Atmel Studio project where ASF provides clocks, GPIO, UART, TWI, ADC and flash, and the application is split into devices (one driver per chip) and managers (system services).

Devices

sht20.cTemperature and humidity, two sensors on TWI0 and TWI1
sct-013.cMotor current from the ADC, single or three phase
yf-s201c.cFlow pulses counted on a GPIO interrupt
bgs2.cGPRS modem: AT commands, SIM check, HTTP service, response parsing
flash_memory.cConfiguration stored in internal flash (EFC)
system_actuator.cRelay output
systick_gpt.cSysTick time base

Managers

system_configurationDefaults, flash load/save, remote configuration
system_telemetriesBuilds the telemetry record (14 fields) and uploads it
system_timeSoftware timeouts on top of SysTick
system_watchdogHardware watchdog
system_loggerDebug console on the UART
system_status_codes.hOne status code per module and error

A cooperative super-loop

No RTOS: main() initialises the services and loops forever, running each job when its software timeout expires. The task diagram defined three periods:

100 ms

Read the current sensors and accumulate the energy consumed by each motor.

10 min

Ask the server for a new configuration over GPRS and apply it.

30 min

Read temperature, humidity, flow and pressure, pack the telemetry and send it.

Flow pulses and the configuration switch are handled by interrupts at any time. In the bench build kept in the repository, telemetry goes out every sixth power cycle instead of every 30 minutes.

Version 2: C++ with an MCAL

The rewrite drops ASF and follows the architecture of Christopher Kormanyos's Real-Time C++: the application talks to a thin microcontroller abstraction layer, peripherals are described with templates resolved at compile time, and the startup code is our own.

sys/appApplications and one test program per peripheral
comm · utilMessage framework, timers, circular buffers, STL subset for bare metal
mcal/sam4scpu · pmc · port · led · gpt · irq · uart · i2c · adc · wdt
mcal_reg_accessRegister access templates: address and value are template parameters
sys/start/sam4scrt0, RAM initialisation, vector table and linker scripts

Registers as types

Every register write is a call to a static member of a template. The address and the value are known at compile time, so the compiler emits a single store, with no driver structures in RAM.

// Kormanyos, mcal_reg_access_template.h template<typename addr_t, typename val_t, const addr_t address, const val_t value = val_t(0)> struct access { static void reg_set() { *reinterpret_cast<volatile val_t*>(address) = value; } static void bit_set() { /* |= 1 << value */ } ... };

Used in the I2C driver

The TWI master is configured the same way: master mode, the clock divider for 100 kHz, no interrupts. Each line documents the register it touches.

// src/mcal/sam4s/mcal_i2c.h (excerpt) // TWI baud rate: 0x11 → 10 µs = 100 kHz mcal::reg::access<addr_type, reg_type, clock_generator_register, UINT32_C(0x00001111)>::reg_set(); // Slave mode disabled, master enabled mcal::reg::access<addr_type, reg_type, ctrl_register, UINT32_C(0x00000020)>::reg_set();

Test programs, one per peripheral

Bring-up went bottom-up, each step with its own main() and Makefile under Target/sam4s/: LED on PC23 → clock source → SysTick with util::timer → blocking delays and intervals → software interrupts → UART (polling and interrupts) → I2C → ADC → watchdog. Seven more programs test the buffers and the message classes on Linux.

Built with -std=c++11 -fno-exceptions, -mcpu=cortex-m4, --gc-sections. The MCALs for ATtiny85, ATmega328P and STM32F429 come from the book and served as reference.

A portable message framework

The board speaks three protocols: AT commands to the modem, Modbus over RS-485 and a debug console. Instead of three ad-hoc parsers, the C++ version separates what a message is from how bytes travel.

Design goals

Taken from Alex Robenko's guide to implementing communication protocols in C++ (src/comm/readme.md):

  • No assumptions about the system it runs on: no dynamic memory, exceptions or RTTI required.
  • Efficient dispatch of incoming messages to their handler.
  • Adding a message is a declaration, not new parsing code.
  • Application messages independent of the transport, so the transport can be swapped.

Two hierarchies

  • Message_base: transmit/receive buffers, send(), recv(), Serialize(). Specialised as Modbus, AT command (3G modem) and debug messages.
  • Communication_base: send_n(), recv_n(), Idle(). Implemented over a memory buffer, UART, I2C and RS-485, and over pipes and file descriptors on Linux.
  • A scheduler runs task objects: time-critical tasks and a message-processing task that feeds a Handler.
UML class diagram: scheduler runs tasks (TimeCritical_task, ProcessMessage_task); Message_base with Message_ModBus, Message_Debug and Message_ATCommand; Communication_base with Buffer, UART, I2C and RS485 communication classes; a Handler bound to Message_base

Class diagram (Documentacion/sensor_iot_class.uml, PlantUML).

History

From the commit log of the C++ tree. The C version is the working base it was meant to replace.

Start

Repository with datasheets and the system diagram.

Project structure

Sources, scripts and file templates.

First light

LED on PC23 from the C++ MCAL.

Own startup

Linker scripts and ARM support.

Pipe framework

Communications tested on Linux with pipes.

Communication classes

communication and buffer_communication.

Messages

Messages with send and receive.

The redo

Rewrite merged with the base version and build files.

Documentation

Class and task diagrams, JTAG interface.

Archive

C version added to the repository, references listed, this page.

Code map

PathContents
firmware-c-asf/C version, Atmel Studio 7 solution
src/mcal/sam4s/MCAL for the SAM4S
src/mcal/pc-linux/Host back-end: pipes, file descriptors
src/sys/start/sam4s/Startup code and linker scripts
src/sys/app/Peripheral test programs
src/app/Host tests: buffers, messages, pipes
src/comm/Message framework
src/util/STL subset and utilities (Real-Time C++)
Target/Makefiles per test and platform
Documentacion/Diagrams and plan

Status

Code from 2018, kept as it was and not re-tested. The sensor drivers exist only in the C version; the C++ rewrite covers the peripheral layer and the message framework.

The modem identifier and server addresses of the original deployment are replaced by placeholders.

Licences

Own C++ code: GPLv3. C version: Apache 2.0, ASF files under Microchip's licence. Files from Real-Time C++: Boost Software License 1.0.

Further reading