Zig Embedded
Embedded programming means writing code for small computers inside other things: a thermostat, a keyboard, a drone’s motor controller. These microcontrollers have no operating system, a few kilobytes of RAM, and flash memory measured in kilobytes too. Zig suits this world well: it has no hidden allocations, it cross-compiles to ARM and RISC-V out of the box, and the same language runs on your laptop and on the chip. This page builds a tiny firmware for an ARM Cortex-M chip and explains every part of it.
What “freestanding” means
Section titled “What “freestanding” means”When you build for your PC, Zig targets an operating system: x86_64-linux, aarch64-macos, and so on. For a microcontroller, the OS part of the target is freestanding: there’s no operating system at all. That changes what’s available:
- No files, no stdout, no terminal. Nothing like
std.Io.File.stdout()exists, because there’s nobody to write to. You talk to the outside world through hardware: pins, serial ports, displays. - No heap unless you bring one. There’s no OS to ask for memory. You use fixed arrays, or a
std.heap.FixedBufferAllocatorover a buffer you set aside. - No
maincalled for you. The chip starts at whatever address the hardware says, and your code takes it from there.
What does work is everything in the standard library that only computes: std.mem, std.math, std.fmt into a buffer, sorting, hashing, your own structs and comptime code. The language reference on freestanding shows a minimal example.
Test the logic on your PC first
Section titled “Test the logic on your PC first”That split is good news. Code that only computes doesn’t care where it runs, so you can test it on your computer with zig test, then build the very same file for the chip. Here’s a helper that smooths noisy sensor readings with no heap at all:
const std = @import("std");
/// Average of the last readings, without any heap: a fixed array on the stack.pub fn Smoother(comptime n: usize) type { return struct { values: [n]u16 = @splat(0), next: usize = 0, count: usize = 0,
const Self = @This();
pub fn add(self: *Self, value: u16) void { self.values[self.next] = value; self.next = (self.next + 1) % n; self.count = @min(self.count + 1, n); }
pub fn average(self: Self) u16 { if (self.count == 0) return 0; var sum: u32 = 0; for (self.values[0..self.count]) |v| sum += v; return @intCast(sum / self.count); } };}
test "Smoother keeps the last 4" { var s: Smoother(4) = .{}; try std.testing.expectEqual(@as(u16, 0), s.average()); for ([_]u16{ 10, 20, 30, 40, 100 }) |v| s.add(v); // 10 fell out; the last four are 20, 30, 40, 100. try std.testing.expectEqual(@as(u16, 47), s.average());}Output:
1/1 main.test.Smoother keeps the last 4...OKAll 1 tests passed.The size is a comptime parameter, so a Smoother(8) is a plain 16-byte array plus two counters, decided at compile time. That’s the kind of code embedded projects are full of, and testing it on a laptop is much faster than flashing a board after every change. Zig Generic Structs explains the fn Smoother(comptime n: usize) type pattern.
Choosing a target
Section titled “Choosing a target”A microcontroller target has three parts plus a CPU model. For the common ARM Cortex-M chips:
zig build-exe main.zig -target thumb-freestanding-eabi -mcpu cortex_m3thumb: Cortex-M chips run ARM’s compact “Thumb” instruction set.freestanding: no operating system.eabi: the ARM calling convention for embedded code (eabihfon chips with a floating-point unit).-mcpu cortex_m3: the exact core, so Zig only uses instructions it has. Others includecortex_m0,cortex_m0plus,cortex_m4andcortex_m7.
RISC-V microcontrollers use riscv32-freestanding with their own -mcpu. zig targets prints everything Zig knows about, and Zig Cross-Compilation explains target triples in general. Your chip’s datasheet tells you which core it has.
Talking to hardware: volatile pointers
Section titled “Talking to hardware: volatile pointers”On a microcontroller, hardware is controlled through memory-mapped registers: special addresses where writing a number turns on a pin, starts a timer or sends a byte down a serial line. In Zig, you make a pointer to that address with @ptrFromInt, and mark it volatile:
// A made-up register address for this example.// On a real chip, it comes from the datasheet.const led: *volatile u32 = @ptrFromInt(0x4000_0000);volatile tells the compiler that every read and write to this address matters. Without it, Zig could see led.* = 1; led.* = 0;, decide the first write is pointless because it’s overwritten right away, and delete it. For normal memory that would be a fine optimization. For a hardware register, it means your LED never turns on. The reference has a short section on volatile.
A whole (tiny) firmware
Section titled “A whole (tiny) firmware”Here’s a complete program for a Cortex-M chip. It “blinks” by writing 1 and 0 to our pretend LED register, with a busy-wait loop in between:
// A made-up register address for this example.// On a real chip, it comes from the datasheet.const led: *volatile u32 = @ptrFromInt(0x4000_0000);
fn delay() void { var i: u32 = 0; while (i < 500_000) : (i += 1) { asm volatile ("nop"); }}
export fn resetHandler() callconv(.c) noreturn { while (true) { led.* = 1; delay(); led.* = 0; delay(); }}
// Set by the linker script: the top of RAM.extern const _stack_top: anyopaque;
// The first words the chip reads at power-on: where the stack starts,// and which function to jump to.const VectorTable = extern struct { initial_stack: *const anyopaque, reset: *const fn () callconv(.c) noreturn,};
export const vector_table: VectorTable linksection(".vectors") = .{ .initial_stack = &_stack_top, .reset = resetHandler,};The parts, from the bottom up:
- The vector table. When a Cortex-M chip powers on, it reads two words from the very start of flash: the address to use as the top of the stack, and the address of the code to run.
vector_tableis exactly those two words.extern structkeeps the fields in that order, andlinksection(".vectors")puts it in a section the linker script will place first. (A real table continues with handlers for interrupts and faults.) resetHandleris our “main”. It’snoreturnbecause firmware never ends: there’s nothing to return to.callconv(.c)gives it the standard calling convention the hardware expects.asm volatile ("nop")is a one-instruction inline assembly block. It keeps the optimizer from deleting the empty delay loop._stack_topisn’t defined in Zig at all. It’s a symbol the linker script creates, andexternsays “someone else provides this”.
The linker script, at a high level
Section titled “The linker script, at a high level”On a PC, the operating system decides where your program lives in memory. On a microcontroller, you do, with a linker script. It describes the chip’s memory and says which parts of the program go where. Here’s a small one, link.ld:
MEMORY{ FLASH (rx) : ORIGIN = 0x08000000, LENGTH = 256K RAM (rwx) : ORIGIN = 0x20000000, LENGTH = 64K}
ENTRY(resetHandler)
SECTIONS{ .vectors : { KEEP(*(.vectors)) } > FLASH .text : { *(.text*) } > FLASH .rodata : { *(.rodata*) } > FLASH .bss : { *(.bss*) } > RAM
_stack_top = ORIGIN(RAM) + LENGTH(RAM);}MEMORYlists where flash (for code, read and execute) and RAM (for variables) are, and how big. These addresses match many STM32 chips, but check your own datasheet: they differ between chips.SECTIONSputs the vector table first in flash (KEEPstops the linker from throwing it away as unused), then code (.text) and constants (.rodata). Zeroed variables (.bss) go in RAM._stack_topis set to the end of RAM, because the stack grows downward.
A real startup also has to copy initial values of global variables (.data) from flash to RAM and zero .bss before running your code. Our program has no global variables, so we skipped that. Libraries like MicroZig write that startup code for you.
Building it
Section titled “Building it”Build with the target, the linker script (-T), the entry symbol and a small build mode:
zig build-exe blink.zig -target thumb-freestanding-eabi -mcpu cortex_m3 -T link.ld -fentry=resetHandler -O smallsize blink text data bss dec hex filename 74 0 0 74 4a blinkThe whole firmware is 74 bytes. Let’s check that the vector table came out right:
objdump -s -j .vectors blinkContents of section .vectors: 8000000 00000120 21000008 ... !...The bytes are little-endian, so read each group backwards: the stack starts at 0x20010000 (the end of our 64K of RAM), and the reset handler is at 0x08000021. That odd last digit is correct: on ARM, the lowest bit of a code address says “this is Thumb code”, and the real function starts at 0x08000020. A disassembler shows the loop storing to our register:
08000020 <.text>: 8000020: b570 push {r4, r5, r6, lr} 8000022: f04f 4480 mov.w r4, #0x40000000 8000026: 2501 movs r5, #0x1 8000028: 2600 movs r6, #0x0 800002a: 6025 str r5, [r4] 800002c: f000 f804 bl 0x8000038 8000030: 6026 str r6, [r4] 8000032: f000 f801 bl 0x8000038 8000036: e7f8 b 0x800002amov.w r4, #0x40000000 loads our register address, str r5, [r4] writes 1, a call to the delay, str r6, [r4] writes 0, another delay, and b jumps back forever. Both writes are there, thanks to volatile. (That listing is from llvm-objdump -d --triple=thumbv7m-none-eabi blink, trimmed.)
Most flashing tools want a raw binary or a hex file, not an ELF. Zig can make one:
zig objcopy -O binary blink blink.binThat gives a 74-byte blink.bin, ready for a flashing tool like OpenOCD or your board’s own uploader.
When something panics
Section titled “When something panics”On your PC, a panic prints a message and a stack trace. On a chip with no screen, there’s nowhere to print. For freestanding targets, Zig’s default panic just executes a trap instruction, which on a Cortex-M usually lands in a fault handler. You can replace it by declaring panic in your root file:
const std = @import("std");
// On a chip there is nowhere to print a message, so a panic just stops here.pub const panic = std.debug.FullPanic(struct { fn panic(_: []const u8, _: ?usize) noreturn { while (true) {} }}.panic);A real handler might turn on a red LED, write the message to a serial port, or reset the chip. An endless loop is a fine start, because a debugger attached to the board shows you exactly where it stopped.
The same build in build.zig
Section titled “The same build in build.zig”For a real project, put the target and flags in build.zig:
const std = @import("std");
pub fn build(b: *std.Build) void { const target = b.resolveTargetQuery(.{ .cpu_arch = .thumb, .os_tag = .freestanding, .abi = .eabi, .cpu_model = .{ .explicit = &std.Target.arm.cpu.cortex_m3 }, });
const firmware = b.addExecutable(.{ .name = "blink", .root_module = b.createModule(.{ .root_source_file = b.path("src/main.zig"), .target = target, .optimize = .small, }), }); firmware.setLinkerScript(b.path("link.ld")); firmware.entry = .{ .symbol_name = "resetHandler" };
b.installArtifact(firmware);
// Also make a raw binary, the format many flashing tools want. const bin = firmware.addObjCopy(.{ .format = .binary }); const install_bin = b.addInstallBinFile(bin.getOutput(), "blink.bin"); b.getInstallStep().dependOn(&install_bin.step);}zig build then puts both zig-out/bin/blink (the ELF, for debuggers) and zig-out/bin/blink.bin (74 bytes, for flashing) in place. The optimize mode is fixed to .small here because a debug build doesn’t fit, as you saw.
Where to go from here
Section titled “Where to go from here”Writing vector tables, linker scripts and register addresses by hand is a great way to learn, but nobody wants to do it for every chip. MicroZig is a community project that does this work for supported microcontrollers: its site says it generates register bindings from the chip’s description files and a default linker script, and gives you higher-level APIs on top. Its README says it targets Zig 0.17.1, and also that it’s still in development and its API will change. Expect the same from most of the Zig embedded world: it works, people ship with it, and it moves fast.
To actually run code, you’ll need a development board (Raspberry Pi Pico, STM32 “Nucleo” and “Blue Pill” boards, and nRF boards are common choices), its datasheet, and a way to flash it.
Practice
Section titled “Practice”1. Test a sensor helper on your PC
Section titled “1. Test a sensor helper on your PC”Write toMillivolts(raw: u12) u16 that turns a 12-bit reading (0 to 4095) into millivolts for a 3300 mV reference, and test it for 0, 4095 and 2047.
Hint: do the math in a u32 so raw * 3300 can’t overflow: @as(u32, raw) * 3300 / 4095, then @intCast back to u16.
Show solution
const std = @import("std");
/// Turns a 12-bit reading (0 to 4095) into millivolts, for a 3300 mV reference.pub fn toMillivolts(raw: u12) u16 { return @intCast(@as(u32, raw) * 3300 / 4095);}
test "toMillivolts" { try std.testing.expectEqual(@as(u16, 0), toMillivolts(0)); try std.testing.expectEqual(@as(u16, 3300), toMillivolts(4095)); try std.testing.expectEqual(@as(u16, 1649), toMillivolts(2047));}Output:
1/1 main.test.toMillivolts...OKAll 1 tests passed.The u12 parameter type means nobody can pass 5000 by mistake. The same file builds for the chip too: zig build-obj adc.zig -target thumb-freestanding-eabi -mcpu cortex_m0 -O small made a 528-byte object file here.
2. Build for another core
Section titled “2. Build for another core”Build the blink firmware for a Cortex-M0 instead of a Cortex-M3, and check its size with size.
Hint: only -mcpu changes. The M0 has a smaller instruction set, so the code may come out slightly different.
Show solution
zig build-exe blink.zig -target thumb-freestanding-eabi -mcpu cortex_m0 -T link.ld -fentry=resetHandler -O smallsize blinkYou’ll see something like:
text data bss dec hex filename 78 0 0 78 4e blinkFour bytes bigger than the Cortex-M3 build: the M0 has fewer instructions, so the compiler needs a couple more to do the same work. Same source, same linker script, different core: switching chips is one flag, not a new toolchain.
- Microcontrollers use a
freestandingtarget: no OS, so no files, no stdout and no heap unless you bring them. - Pure logic can be tested on your PC with
zig test, then built for the chip unchanged. - Cortex-M targets look like
thumb-freestanding-eabiwith-mcpu cortex_m3(orm0,m4, …). - Hardware registers are
*volatilepointers made with@ptrFromInt, so writes aren’t optimized away. - A vector table tells the chip where the stack and the reset handler are; a linker script places code in flash and data in RAM.
- Build with
-O smallor-O safe:debugbuilds can overflow the chip’s flash. MicroZig does much of this setup for supported chips.
Next up: Zig Networking & HTTP, fetching a web page and writing a tiny web server with the standard library.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Zig language reference: Freestanding: building without an operating system.
- Zig language reference: volatile: what
volatilepointers guarantee. - Zig language reference: Targets: the target triples Zig supports.
- MicroZig: the community toolbox for Zig on microcontrollers, with board support and generated register code.
- GNU ld: linker scripts: the full reference for the
MEMORYandSECTIONSsyntax used above.