C / C++ Port
HIL targets embedded C/C++ through two paths: transpilation from LISP to Arduino-compatible C++ for AVR (ATmega328P) and ARM (ESP32, STM32), and native C++ evaluation using std::variant for AST representation. The C++ port enables direct register manipulation, memory-mapped I/O, and RAII-based hardware resource management (Stroustrup, 2013).
Arduino Framework
HIL transpiles directly to Arduino .ino sketches. The transpiler emits #include <Arduino.h>, maps (WRITE D 13 1) to digitalWrite(13, HIGH), and wraps HIL control flow in void loop() (Arduino Foundation, 2024):
#include <Arduino.h>
#include <Servo.h>
// Generated from HIL LISP:
// (SET led 13)
// (SET sensor A0)
// (DEFUN blink (pin ms)
// (WRITE D pin 1) (DELAY ms)
// (WRITE D pin 0) (DELAY ms))
// (DEFUN read-temp ()
// (READ A sensor))
static int led = 13;
static int sensor = A0;
Servo myservo;
void blink(int pin, int ms);
int readTemp();
void setup() {
Serial.begin(9600);
pinMode(led, OUTPUT);
myservo.attach(9);
}
void blink(int pin, int ms) {
digitalWrite(pin, HIGH);
delay(ms);
digitalWrite(pin, LOW);
delay(ms);
}
int readTemp() {
int raw = analogRead(sensor);
return map(raw, 0, 1023, 0, 500);
}
void loop() {
static bool _hil_ran = false;
if (_hil_ran) return;
_hil_ran = true;
int temp = readTemp();
Serial.println(temp);
if (temp > 300) {
for (int i = 0; i < 5; i++) {
blink(led, 200);
}
} else {
myservo.write(90);
}
}
AVR-GCC vs TinyGo
| Feature | AVR-GCC (native) | TinyGo |
|---|---|---|
| Binary size | ~2KB runtime | ~8KB runtime |
| Concurrency | ISR-based | Goroutines (limited) |
| Memory model | Direct register | Abstracted |
| Timers | Hardware timers | Timer/ticker |
| Best for | Minimal targets | Go-native workflow |
ESP-IDF for ESP32
For ESP32 targets, HIL generates ESP-IDF C++ components. The transpiler emits app_main() instead of setup()/loop() and uses ESP-IDF's GPIO and ADC APIs:
#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "driver/gpio.h"
#include "driver/adc.h"
#include "esp_log.h"
static const char *TAG = "hil";
#define LED_PIN GPIO_NUM_2
#define SENSOR_PIN ADC1_CHANNEL_0
#define SERVO_PIN GPIO_NUM_13
// HIL-generated: (SET led 2) (SET sensor A0)
static int led = LED_PIN;
static int sensor = SENSOR_PIN;
void blink_task(void *arg) {
int ms = *(int *)arg;
while (1) {
gpio_set_level(led, 1);
vTaskDelay(pdMS_TO_TICKS(ms));
gpio_set_level(led, 0);
vTaskDelay(pdMS_TO_TICKS(ms));
}
}
int read_temp() {
int raw = adc1_get_raw(SENSOR_PIN);
return (raw * 500) / 4095;
}
extern "C" void app_main(void) {
// Configure GPIO
gpio_config_t io_conf = {};
io_conf.pin_bit_mask = (1ULL << led);
io_conf.mode = GPIO_MODE_OUTPUT;
gpio_config(&io_conf);
// Configure ADC
adc1_config_width(ADC_WIDTH_BIT_12);
adc1_config_channel_atten(SENSOR_PIN, ADC_ATTEN_DB_11);
ESP_LOGI(TAG, "HIL evaluator starting");
int temp = read_temp();
ESP_LOGI(TAG, "Temperature: %d", temp);
if (temp > 300) {
int delay_ms = 200;
xTaskCreate(blink_task, "blink", 2048, &delay_ms, 5, NULL);
vTaskDelay(pdMS_TO_TICKS(2000));
}
}
PlatformIO Build System
PlatformIO automates cross-compilation for multiple targets. Define platformio.ini:
[env:nano]
platform = atmelavr
board = nanoatmega328
framework = arduino
build_flags = -D HIL_TARGET_AVR
[env:esp32]
platform = espressif32
board = esp32dev
framework = espidf
build_flags = -D HIL_TARGET_ESP32
[env:stm32]
platform = ststm32
board = nucleo_f446re
framework = stm32cube
build_flags = -D HIL_TARGET_ARM
Build for any target:
# Transpile HIL to C++
hil-cli firmware build script.hil --output script.cpp
# Compile for Arduino Nano
pio run -e nano
# Compile for ESP32
pio run -e esp32
# Compile for STM32
pio run -e stm32
# Flash to connected device
pio run -e nano -t upload
Direct Register Manipulation
The C++ port supports direct register access for performance-critical applications. HIL's (WRITE D 13 1) can compile to register-level operations:
// HIL: (WRITE D 13 1)
// Fast path: direct register write
PORTB |= (1 << PB5); // Set pin 13 HIGH (ATmega328P)
// HIL: (WRITE D 13 0)
PORTB &= ~(1 << PB5); // Set pin 13 LOW
// HIL: (READ D 12)
// Fast path: direct register read
uint8_t val = (PINB & (1 << PB4)) ? 1 : 0; // Read pin 12
// Memory-mapped I/O for ESP32
#define GPIO_OUT_W1TS_REG (*(volatile uint32_t *)0x3FF44004)
#define GPIO_OUT_W1TC_REG (*(volatile uint32_t *)0x3FF44008)
// HIL: (WRITE D 2 1)
GPIO_OUT_W1TS_REG = (1 << 2); // Set GPIO2 HIGH
C++ RAII for Hardware Resources
C++ RAII ensures hardware resources are properly initialized and released. The HIL transpiler wraps pin configurations and peripherals in RAII classes:
#include <Arduino.h>
class DigitalPin {
public:
DigitalPin(uint8_t pin, uint8_t mode) : pin_(pin) {
pinMode(pin, mode);
}
~DigitalPin() {
pinMode(pin_, INPUT);
}
void write(uint8_t val) {
digitalWrite(pin_, val);
}
uint8_t read() {
return digitalRead(pin_);
}
DigitalPin(const DigitalPin&) = delete;
DigitalPin& operator=(const DigitalPin&) = delete;
private:
uint8_t pin_;
};
class AnalogSensor {
public:
AnalogSensor(uint8_t pin) : pin_(pin) {
// No explicit init needed for analog
}
int read() {
return analogRead(pin_);
}
float readVoltage() {
return analogRead(pin_) * (5.0 / 1023.0);
}
private:
uint8_t pin_;
};
class ServoControl {
public:
ServoControl(uint8_t pin) {
servo_.attach(pin);
}
~ServoControl() {
servo_.detach();
}
void angle(int deg) {
servo_.write(constrain(deg, 0, 180));
}
private:
Servo servo_;
};
// HIL-generated main using RAII
void setup() {
Serial.begin(9600);
DigitalPin led(13, OUTPUT);
DigitalPin button(2, INPUT_PULLUP);
AnalogSensor sensor(A0);
ServoControl servo(9);
led.write(HIGH);
int temp = sensor.read();
Serial.println(temp);
if (temp > 512) {
servo.angle(90);
} else {
servo.angle(0);
}
// All resources released automatically at scope end
}
C++ Variant-Based Evaluator
For host-side evaluation, the HIL AST uses std::variant for type-safe node representation. This eliminates manual type tags and leverages C++17 pattern matching (Koenig & Moo, 2013):
#include <variant>
#include <vector>
#include <string>
#include <map>
#include <functional>
#include <memory>
#include <stdexcept>
struct Number { int value; };
struct Symbol { std::string name; };
struct Bool { bool value; };
struct List {
std::vector<std::variant<Number, Symbol, Bool, List>> elements;
};
using ASTNode = std::variant<Number, Symbol, Bool, List>;
struct FuncDef {
std::vector<std::string> params;
List body;
};
class HILEvaluator {
public:
using BuiltinFunc = std::function<ASTNode(const std::vector<ASTNode>&)>;
HILEvaluator() {
builtins["+"] = [](const std::vector<ASTNode>& args) -> ASTNode {
int result = 0;
for (const auto& a : args) {
if (auto* n = std::get_if<Number>(&a)) {
result += n->value;
}
}
return Number{result};
};
builtins["-"] = [](const std::vector<ASTNode>& args) -> ASTNode {
if (args.empty()) return Number{0};
int result = std::get<Number>(args[0]).value;
for (size_t i = 1; i < args.size(); i++) {
if (auto* n = std::get_if<Number>(&args[i])) {
result -= n->value;
}
}
return Number{result};
};
builtins["*"] = [](const std::vector<ASTNode>& args) -> ASTNode {
int result = 1;
for (const auto& a : args) {
if (auto* n = std::get_if<Number>(&a)) {
result *= n->value;
}
}
return Number{result};
};
builtins["="] = [](const std::vector<ASTNode>& args) -> ASTNode {
if (args.size() < 2) return Bool{false};
int a = std::get<Number>(args[0]).value;
int b = std::get<Number>(args[1]).value;
return Bool{a == b};
};
builtins["<"] = [](const std::vector<ASTNode>& args) -> ASTNode {
if (args.size() < 2) return Bool{false};
int a = std::get<Number>(args[0]).value;
int b = std::get<Number>(args[1]).value;
return Bool{a < b};
};
}
ASTNode eval(const ASTNode& expr) {
return std::visit([this](auto&& val) -> ASTNode {
using T = std::decay_t<decltype(val)>;
if constexpr (std::is_same_v<T, Number> ||
std::is_same_v<T, Bool>) {
return val;
}
else if constexpr (std::is_same_v<T, Symbol>) {
auto it = vars.find(val.name);
if (it != vars.end()) return it->second;
throw std::runtime_error("undefined: " + val.name);
}
else if constexpr (std::is_same_v<T, List>) {
return evalList(val);
}
}, expr);
}
private:
std::map<std::string, ASTNode> vars;
std::map<std::string, FuncDef> funcs;
std::map<std::string, BuiltinFunc> builtins;
ASTNode evalList(const List& list) {
if (list.elements.empty()) return List{};
auto& head = list.elements[0];
if (auto* sym = std::get_if<Symbol>(&head)) {
if (sym->name == "SET") {
auto varName = std::get<Symbol>(list.elements[1]).name;
ASTNode val = eval(list.elements[2]);
vars[varName] = val;
return val;
}
if (sym->name == "IF") {
auto cond = eval(list.elements[1]);
bool truthy = true;
if (auto* b = std::get_if<Bool>(&cond)) {
truthy = b->value;
} else if (auto* n = std::get_if<Number>(&cond)) {
truthy = n->value != 0;
}
return truthy ? eval(list.elements[2]) : eval(list.elements[3]);
}
if (sym->name == "DEFUN") {
auto fname = std::get<Symbol>(list.elements[1]).name;
auto paramsList = std::get<List>(list.elements[2]);
FuncDef fd;
for (const auto& p : paramsList.elements) {
fd.params.push_back(std::get<Symbol>(p).name);
}
fd.body = std::get<List>(list.elements[3]);
funcs[fname] = fd;
return Symbol{fname};
}
auto it = builtins.find(sym->name);
if (it != builtins.end()) {
std::vector<ASTNode> args;
for (size_t i = 1; i < list.elements.size(); i++) {
args.push_back(eval(list.elements[i]));
}
return it->second(args);
}
auto fit = funcs.find(sym->name);
if (fit != funcs.end()) {
// Save and restore scope
auto savedVars = vars;
for (size_t i = 0; i < fit->second.params.size(); i++) {
vars[fit->second.params[i]] = eval(list.elements[i + 1]);
}
ASTNode result = eval(ASTNode{fit->second.body});
vars = savedVars;
return result;
}
}
throw std::runtime_error("invalid form");
}
};
CMake Build Example
For non-Arduino CMake projects (ESP-IDF, STM32, bare-metal):
cmake_minimum_required(VERSION 3.16)
project(hil_evaluator CXX)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
# Source files
set(HIL_SOURCES
src/main.cpp
src/evaluator.cpp
src/parser.cpp
src/serial.cpp
)
add_executable(hil ${HIL_SOURCES})
# Serial library
find_library(SERIAL_LIB serial)
if(SERIAL_LIB)
target_link_libraries(hil ${SERIAL_LIB})
endif()
# ESP-IDF target
if(ESP_PLATFORM)
idf_component_register(
SRCS ${HIL_SOURCES}
INCLUDE_DIRS "include"
REQUIRES driver esp_adc_cal
)
endif()
# STM32 target
if(STM32)
target_link_libraries(hil
stm32_hal
cmsis
)
target_compile_definitions(hil PRIVATE
HIL_TARGET_ARM
HIL_SERIAL_DMA
)
endif()
References
Arduino Foundation. (2024). Arduino reference. https://www.arduino.cc/reference/en/
Koenig, A., & Moo, B. E. (2013). Accelerated C++: Practical programming by example. Addison-Wesley.
Stroustrup, B. (2013). The C++ programming language (4th ed.). Addison-Wesley.