Abstraction Layer – alSystem

I typically code ESP32, ESP8285, a lot of STM32, Pico, Linux and Windows to mention a few, so I want to be able to move code between those platforms with a minimum of hazle. For this purpose I create a C++ API that I call “Abstraction Layer”. I did not want to use the word “HAL” because it is not always hardware that I abstract away from. Another motivation for this layer is C++. Nearly all code, drivers etc for embedded is in C, while I have a very strong preference for Embedded C++.

The first class (module) I need is “alSystem” that allow me to access platform specific content in a generic way – simple things like sending signals, starting/stopping threads, tasks and timers and measuring time. Both FreeRTOS, Windows and Linux offer these mechanisms, but how do I move code between a non-RTOS, RTOS and Linux/Windows? The answer is that I hide them behind a class called alSystem.

Example:

uint32_t now = alSystem::millis();

This is a simple function to fetch the time in ms since the computer started. It is often used to measure time difference in ms, so I create a 32 bit version and a 64 bit version of this. I also create micosecond versions, but the later are seldom of any usage because we usually don’t maintain time below milliseconds unless we have special needs due to the complexity/cost/performance. The challenge with a 32 bit ms timer is that it wraps in ca 50 days, so if you want to make it secure you use a 64 bit version since uint64_t is supported.

  • millis()
  • millis64()
  • micros()
  • micros64()
  • delay()
  • sleep()
  • CreateTimer()
  • StartTimer()
  • StopTimer()
  • CreateTask()
  • SignalTask()
  • CreateThread()

These are a few of the static functions I always replicate in alSystem that will be guaranteed on any platform I use. Not everything is created inside alSystem as I also have a C++ library with power classes tailored specially for a static, embedded system where new/delete is forbidden – no memory allocation once the system is started.

This C++ layer do come at a cost of more Flash usage, but most MCU’s these days come with a bit of Flash and what I need the least is Flash I don’t use. This means I cannot use this library for very small cost-effective MCU’s, but for those I would code bare-bone C anyway. This library target more intelligent platforms where functionality and AI is in focus.

And least, but not last – generating code from BSA will use this library as a base – that simple trick allows me to generate code for multiple embedded platforms.

Leave a Reply