Arduino & AVR
The Uno R3 target, the 1 KB arena, scratch on the AVR stack, and the complete arduino.* binding surface.
The Arduino Uno R3 (ATmega328P) is Vyne's first non-desktop target. The same .vy source that runs under the interpreter or compiles to a desktop binary can be lowered to firmware:
The target has a 1 KB static arena, a 16-deep checkpoint stack, and a hard halt on arena exhaustion. Region semantics do not change: the arena is a bump allocator with checkpoint / rewind, exactly like the desktop runtime, only smaller.
A first sketch
For a new project, select the board once and use the project workflow:
hardware.toml stores the board and port. Existing Uno pinout and budget fields remain accepted. vynec run --monitor explicitly enables monitoring. ESP32 and HW-950 initialization use the same short commands; see Projects & Tooling for presets, overrides and setup, and ESP32 & Hardware for the ESP32 runtime and peripheral surface.
scratch lowers to a raw array on the AVR stack, not the arena. On AVR, Float64 is a 32-bit float and Int64 is emulated over 32-bit hardware; prefer Float64 for numerical work.
Quick reference
| Header | Functions | Surface |
|---|---|---|
mcu_hardware.h | 14 | Pin mode, digital/analog I/O, delays, base trig, arena_used |
mcu_serial.h | 7 | Available, read, read_line, parse, println, flush |
mcu_timing.h | 2 | Pulse width, Timer1 read |
mcu_math.h | 34 | Transcendentals (boxed + unboxed _f64), constrain, map, lerp, smoothstep, random |
mcu_pins_ext.h | 9 | ADC voltage/reference/resolution, oversampling, toggle, pulse, shift, count |
mcu_memory.h | 4 | Arena peak/free, free RAM, stack free |
mcu_bits.h | 9 | Bit set/clear/toggle/read, byte split/merge, popcount, CRC-8 |
mcu_eeprom.h | 4 | Read/write Int64 and Float64 across resets |
mcu_i2c.h | 8 | I2C master via Wire: byte/register read-write, clock |
mcu_spi.h | 6 | SPI master via SPI: settings, byte/word transfer |
mcu_realtime.h | 5 | @realtime watchdog and telemetry (opt-in) |
mcu_interrupts.h | 8 | Counter-based external interrupts (D2/D3) + watchdog |
Total exposed to Vyne source: 110 functions (91 core + 14 peripheral + 5 realtime telemetry).
The memory model on AVR
- Arena. A
static uint8_t g_mcu_arena[VYNE_MCU_ARENA_SIZE]in.bss, 1024 bytes by default.arena_allocis a pointer bump plus a bounds check. Exhaustion halts withwhile (1) ;. - Checkpoints. Sixteen fixed slots. Nested regions deeper than 16 are not supported.
- Scratch. C stack storage. Roughly 1.5 KB of stack headroom remains after frame pointers and ISR return addresses. Use scratch for small fixed buffers.
- Typed arrays.
Array<Float64>costs 4 bytes per element plus a 12-byte header; an untypedArraycosts 16 bytes per element plus the same header. Use the annotated form whenever possible. - Push grows, rewind reclaims.
pushallocates a fresh buffer (1.5×, minimum 8 elements) and copies. Repeating push without a region exhausts the arena. - Strings. String literals do not allocate;
vyne_stringcopies into the arena and can trigger the halt path if full. - No
out(). The boxed print engine is not linked. Usearduino.serial_print/serial_println.
@bounded on AVR
The MCU arena maintains the same live-allocation counter as the desktop arena. @bounded<bytes> checks it at region exit, and vyne_panic_region_bound halts the sketch on a violation. The embedded project template exercises this path directly.
What is not bound
dot,norm,argmax,argminare absent from theARDUINO_MAPtable. They would require typed-array containers inmcu_types.hplusboxAnylowering for MCU targets. Calling them from a sketch fails at compile time with "not defined".attach_interruptis counter-based, not callback-based. A Vyne function compiles to the boxed signature, which cannot be installed as an AVRvoid(void)ISR without compiler-side wrapper emission. Pollinterrupt_count,interrupt_fired, andinterrupt_reset.- Timer compare-match ISRs are not exposed.
- The MCU typed-array method surface is partial:
contains,pop,reverse,sort,place_all,delete_at,back, andpop_frontare not bound on AVR. vlin.multiplythrough theOps.vywrapper is still boxed on MCU even though the kernel is unboxed; directvlin.k_*calls from a sketch have not been hardware-tested.- No filesystem (
vfsis desktop-only), no@device, no@persistent, no@streamed.
Complete API reference
The section below is generated from the AVR runtime manual so the binding surface stays aligned with the headers. Every function is reachable through use native arduino;. C symbols are shown for reference only; call the Vyne names.
API reference
Every function below is available in Vyne source via use native arduino;. The Vyne signature is shown; the C symbol is in the code block for reference but should never be called directly from Vyne.
Core I/O — mcu_hardware.h
Configure a GPIO pin.
| Parameter | Values |
|---|---|
pin | 0–13 (digital), 0–5 (analog pins used as digital 14–19) |
mode | 0 = INPUT, 1 = OUTPUT, 2 = INPUT_PULLUP |
Returns null.
Drive a pin low or high. val is 0 for LOW and any non-zero value for HIGH. Returns null.
Read a pin. Returns 0 or 1.
Read the ADC. By default returns 0..1023 (10-bit). If arduino.analog_read_resolution(bits) has been called, the raw value is right-shifted by 10 - bits before returning, so the range becomes 0..(2^bits - 1).
Write a PWM value. By default accepts 0..255 (8-bit). If arduino.analog_write_resolution(bits) has been called with bits < 8, the input is scaled up to 0..255 before reaching the hardware. Values outside the current range are clamped. Returns null.
Busy-wait for ms milliseconds. Blocks. Returns null.
Busy-wait for us microseconds. Uses delayMicroseconds(), which is cycle-accurate at the requested resolution but does not yield to interrupts consistently below ~2 µs. Returns null.
Milliseconds since boot. Wraps at 2^32 (about 49.7 days). Returns Int64.
Microseconds since boot. Wraps at 2^32 (about 71 minutes). Returns Int64.
Configure the hardware UART. Standard rates: 9600, 19200, 38400, 57600,
- The Vyne entry point already calls this with 115200 before
vyne_setup(); a second call from Vyne source is idempotent. Returns null.
Write v to the serial port. v may be Int64, Float64, String, Bool, or null. Uses the same formatting as out(v) on desktop. No trailing newline. Returns null.
Single-precision versions of the standard library. These are also available in the extended math family below with the same signature; the duplicates here exist so that a sketch using only the base runtime does not need to include mcu_math.h.
Bytes currently in use in the MCU arena. The intended use is to measure drift = after - before around a region body to verify that the rewind fired. Returns Int64.
The following symbols are internal — emitted by the code generator, never called from Vyne source:
vyne_panic_bounds replaces fprintf(stderr, ...) + exit(1) on desktop. It prints the diagnostic over Serial and halts. This is the MCU substitute for the scratch bounds-check failure path (VNE-072).
Serial — mcu_serial.h
Bytes in the RX buffer. 0 when empty. Non-blocking.
Read one byte. Returns -1 when the RX buffer is empty. Non-blocking.
Read a line. Blocks up to 1 second waiting for \n. Returns the line without the trailing newline or carriage return. Buffer limit is 63 bytes; longer lines are truncated at 63 characters and the remainder is discarded. The result is copied into the arena, so a call from inside a region { } block is reclaimed at the closing brace.
Read the next integer from the serial stream using Serial.parseInt() with its default 1-second timeout. Blocks. Returns 0 on timeout.
Read the next float. Same blocking / timeout behaviour as serial_parse_int.
Same as serial_print(v) followed by a newline. Returns null.
Wait for the transmit buffer to drain. Returns null.
Timing — mcu_timing.h
Measure the HIGH portion of the next pulse on pin, in microseconds. Returns 0 on timeout (default 1 second, matching pulseIn). For an active-LOW sensor, call arduino.pulse_in(pin, 0, timeout_us) instead.
Read Timer1's raw 16-bit counter (TCNT1). Returns 0 until the sketch configures Timer1 via avr-libc registers (TCCR1A, TCCR1B, OCR1A, prescaler). Wraps at 65536 counts; the tick interval depends on the prescaler. This is a low-level escape hatch; most sketches should not call it.
Math — mcu_math.h
The math family exposes both a boxed form (works on any argument kind) and an unboxed _f64 form. The emitter selects the unboxed form when every call-site argument is a provably-Float64 native expression. The two forms are functionally identical.
Transcendentals
Unboxed forms: arduino_tan_f64, arduino_asin_f64, ..., arduino_fmod_f64. Prefer writing the call with Float64 arguments so the emitter picks the unboxed form.
Domain / range behaviour follows avr-libc's <math.h>:
tanandatanare defined for all inputs.asinandacosreturn NaN for arguments outside[-1, 1].logandlog10return-inffor0, NaN for negative arguments.expsaturates to+infat large positive inputs.powreturns NaN forpow(negative, non-integer).
The caller is responsible for domain clipping. arduino.constrain is usually the right tool.
Interpolation and clamping
Returns lo if x < lo, hi if x > hi, otherwise x. If lo > hi, the result is hi (matching the desktop vmath.clamp behaviour).
Linear remap. out_lo + (x - in_lo) * (out_hi - out_lo) / (in_hi - in_lo). This is the Arduino map() function for floats — the function every ADC-to-physical-unit conversion goes through. Division by zero on a degenerate input range is not guarded; NaN propagates to the use site.
a + (b - a) * t. t is not clamped; extrapolation is the caller's choice.
Hermite ramp from a to b, evaluated at x. Clamped to [0, 1] so out-of-range x produces a plateau, matching GLSL semantics. Standard for fading LEDs and soft sensor thresholds.
Angle unit conversion. VYNE_PI (defined as 3.14159265358979323846 in mcu_math.h) is used, not <math.h>'s M_PI.
Random
Thin wrappers around the Arduino core's random() and randomSeed(). Because C has no overloading, the dispatch is variadic at runtime (arduino_random_variadic(argc, argv)).
arduino.random(max)returns0..max-1.arduino.random(min, max)returnsmin..max-1.arduino.random_seed(seed)reseeds the LCG. Passing0is a no-op, matching Arduino.
The TinyML example deliberately does not use these — it implements its own LCG in Vyne source so that the trajectory is reproducible across boots and the demo depends on nothing beyond the base runtime. For a sketch that just wants "some randomness", these are the right call.
Extended pins — mcu_pins_ext.h
Convenience wrapper. Returns analogRead(pin) * 5.0 / 1023.0. This is the ADC value in volts assuming the default 5 V reference and 10-bit resolution. If the sketch has changed the reference via arduino.analog_reference() or the resolution via arduino.analog_read_resolution(), this function does not account for either — the caller must scale manually.
mode | Effect on Uno R3 |
|---|---|
0 | DEFAULT — 5 V |
1 | INTERNAL — 1.1 V (small signals, high precision) |
2 | EXTERNAL — external AREF pin |
Subsequent analog_read calls use the new reference. Returns null.
Set the ADC resolution. bits is clamped to 1..10. The value is stored as a right-shift amount in g_vyne_adc_shift; subsequent analog_read calls return raw >> g_vyne_adc_shift.
The raw ADC is always 10-bit. Asking for 8 bits does not improve hardware precision — it only reduces the reported range. It does save a few cycles per read and reduces downstream VyneValue boxing costs by keeping values inside the 0..255 window. Returns null.
Set the PWM input range. AVR's PWM hardware is 8-bit; asking for more than 8 is clamped to 8 with a VNE-090 warning. Asking for fewer scales the input up to 0..255 before writing.
arduino.analog_write_resolution(4) followed by arduino.analog_write(pin, 15) produces a 100% duty cycle; 0 produces 0%. This is the correct way to expose a coarse-grained control surface (LED brightness in 16 steps, motor throttle in 16 steps) without incurring the full 8-bit resolution cost. Returns null.
Average n consecutive reads and return the mean as Float64. SNR improves by roughly sqrt(n); on the Uno's 10-bit ADC, n = 16 recovers about 2 effective bits, n = 64 about 3.
Two caveats. First, the accumulation saturates the 24-bit mantissa of AVR's double beyond roughly n = 4096; further averaging does not help. Second, the function blocks for n * 100 µs (the ADC conversion time), so n = 64 blocks for ~6.4 ms. In a hot loop, sample in the background via analogRead and average with a rolling window instead.
Equivalent to digitalWrite(pin, !digitalRead(pin)). Saves a function call and a variable. Returns null.
Measure the duration of a pulse on pin. state selects which level to measure (0 = LOW portion, 1 = HIGH portion). Returns the pulse width in microseconds, or 0 on timeout. Uses the Arduino core's pulseIn(), which blocks.
The maximum measurable pulse width is limited by timeout_us. The default in pulseIn() is 1 second; pass a smaller value if the sketch has other work to do.
Bit-bang nbits bits out of val on data_pin, clocking on clk_pin. bit_order is 0 for LSB-first, non-zero for MSB-first.
The built-in shiftOut() only handles 8 bits; this implementation open-codes the loop so it works for any width from 1 to 32. Returns null.
Count LOW-to-HIGH transitions on pin over window_ms milliseconds. Polling-based; the achievable rate on a 16 MHz Uno is roughly 5 kHz. For higher rates, use arduino.attach_interrupt on D2 or D3 plus arduino.interrupt_count.
Returns the count as Int64. Note the transition definition: it counts rising edges, not pulses. A 50% duty cycle signal at 1 kHz produces 1000 counts per second.
Memory — mcu_memory.h
Peak arena usage (high-water mark, persists across rewinds) and remaining free bytes in the arena before the next arena_alloc halts the board. These are diagnostics; calling them in a loop is a mistake because their return values do not change until an allocation occurs.
Free SRAM between the top of the heap and the current stack pointer. These are the numbers that answer "am I about to crash?". They use the standard avr-libc __brkval / __heap_start trick: __brkval is 0 until the first heap allocation, so on a fresh boot the free-RAM computation falls back to __heap_start.
Both names are exposed because some developers prefer the explicit stack framing. On AVR without stack-painting instrumentation, there is no separate "stack watermark" — the two functions return the same value.
Calling these from inside a hot loop is a mistake. free_ram is five instructions but the value changes slowly; polling it in a loop tells you nothing new. Call it once at boot, once at exit, and once around any suspicious allocation.
Bits — mcu_bits.h
All bit-manipulation functions operate on Int64. On AVR the Int64 type is emulated; for values that fit in 32 bits, cast down before calling to save libgcc cycles.
n is not bounds-checked. n >= 64 is undefined behaviour (it happens to work on AVR because the shift amount is masked to 6 bits, but do not rely on it).
Byte extraction and assembly. Useful for 16-bit payloads over I2C/SPI, register manipulation, and EEPROM serialization.
Number of set bits. Uses Kernighan's algorithm — one loop iteration per set bit. For dense data (few zero bits) a 256-byte lookup table is faster, but it costs flash and requires a PROGMEM read; for the small bitmaps typical of a sketch, Kernighan is the right default.
Dallas/Maxim CRC-8 (polynomial 0x31, MSB-first, initial value typically 0). One byte per call so the caller can chain:
The implementation uses an 8-iteration loop rather than a 256-byte lookup table. On AVR, for a frame of a few dozen bytes, the loop is faster than table lookup because it avoids the PROGMEM read overhead.
EEPROM — mcu_eeprom.h
One kilobyte of persistent storage, byte-addressable, ~100,000 write cycles per byte. Access is via <avr/eeprom.h>'s eeprom_read_byte / eeprom_update_byte, not the bundled Arduino EEPROM library.
Read or write 8 bytes (int64_t) starting at addr. The write variant uses update_byte, which only writes when the new byte differs from the current — extending cell life. If you write the same value repeatedly, the EEPROM is not touched.
Read or write 4 bytes (double, which is 32-bit single-precision on AVR). Same update-only-if-changed semantics.
Address range is 0..1023. Bounds are not checked. A write past 1023 wraps to address 0 (the address register is 10 bits wide), so a runaway loop can clobber the entire EEPROM. The correct pattern is to reserve a small block for your sketch and hardcode the addresses.
Integer and float slots must not overlap. A sketch that stores an Int64 at address 0 and a Float64 at address 4 will work; a sketch that stores an Int64 at 0 and a Float64 at 2 will corrupt both. Plan the layout in a comment at the top of the sketch.
I2C — mcu_i2c.h
I2C/TWI master bindings backed by the bundled Arduino Wire library. On the Uno R3, SDA is A4 and SCL is A5. The build integration compiles vendor/arduino/libraries/Wire/src (including utility/twi.c) and adds it to the include path.
| Binding | Returns | Notes |
|---|---|---|
arduino.i2c_begin() | Null | Start the bus master |
arduino.i2c_end() | Null | Release the peripheral |
arduino.i2c_set_clock(hz) | Null | 0 keeps the 100 kHz default |
arduino.i2c_write(addr, value) | Int64 | endTransmission status |
arduino.i2c_read(addr) | Int64 | One byte, or -1 |
arduino.i2c_write_reg(addr, reg, value) | Int64 | Register write |
arduino.i2c_read_reg(addr, reg) | Int64 | Repeated-start read, or -1 |
arduino.i2c_available() | Int64 | Bytes in the receive buffer |
Addresses are 7-bit (0..127). The C layer casts to uint8_t; the typed vi2c wrapper validates first and returns -2 / -3 for bad arguments instead of truncating. endTransmission status values are Arduino's: 0 ACK, 1 data too long, 2 NACK address, 3 NACK data, 4 other.
See examples/arduino/i2c_imu.vy and vyne/modules/external/vi2c/README.md.
SPI — mcu_spi.h
SPI master bindings backed by the bundled Arduino SPI library. On the Uno R3, MOSI is D11, MISO D12, SCK D13, and SS D10 (drive SS yourself). The build integration compiles vendor/arduino/libraries/SPI/src and adds it to the include path.
| Binding | Returns | Notes |
|---|---|---|
arduino.spi_begin() | Null | Power the peripheral |
arduino.spi_end() | Null | Release it |
arduino.spi_set(clock_hz, mode) | Null | Begins a transaction; MSB first; mode 0..3 |
arduino.spi_end_transaction() | Null | Ends the transaction |
arduino.spi_transfer(value) | Int64 | 8-bit full-duplex |
arduino.spi_transfer16(value) | Int64 | 16-bit full-duplex |
arduino.spi_set falls back to mode 0 for an out-of-range mode and to 4 MHz for a zero clock, so a bad constant cannot hang the bus. The typed vspi wrapper validates clock, mode, and value widths and returns -2 / -3 instead.
See examples/arduino/spi_loopback.vy and vyne/modules/external/vspi/README.md.
Realtime and contracts — mcu_realtime.h, mcu_contracts.h
@realtime<ms> compiles to vyne_realtime_now_us() at region entry and vyne_realtime_check(name, line, deadline, start) on every exit. Overrun halts with VNE-109. Telemetry is exposed as arduino.*:
| Binding | Returns | Notes |
|---|---|---|
arduino.realtime_worst_ms() | Float64 | Worst observed across all regions |
arduino.realtime_overruns() | Int64 | Total overruns |
arduino.realtime_reset() | Null | Clears all counters |
arduino.realtime_worst_ms_named(name) | Float64 | One region by name |
arduino.realtime_overruns_named(name) | Int64 | One region by name |
requires / ensures / @invariant compile to vyne_contract_assert. A violation prints VNE-111 over Serial and halts. In evidence mode the pass/fail CSV goes to Serial. ruleset { contracts = "off" } emits no checks, which is the release path. See examples/test/realtime_contract_avr.vy.
Interrupts — mcu_interrupts.h
The Uno R3 has two external-interrupt pins: D2 (IRQ 0) and D3 (IRQ 1). digitalPinToInterrupt() returns -1 for every other pin. The runtime provides a counter-based interface, not a callback interface — see What is not bound and why for the reasoning.
Install an edge-counting trampoline on pin. mode selects the edge type:
mode | Trigger |
|---|---|
0 | LOW |
1 | CHANGE (both edges) |
2 | RISING |
3 | FALLING |
Returns the IRQ index (0 for D2, 1 for D3) on success, -1 if the pin has no external interrupt. The counter is reset to zero on attach.
Remove the trampoline. Subsequent edges do nothing. Returns null.
Read the current edge count. Returns 0 for non-interrupt pins. Interrupts are masked during the read so the 64-bit value is coherent.
Reset the counter to zero. Returns null.
true if the counter is greater than zero. Equivalent to interrupt_count(pin) > 0 but marginally cheaper. Interrupts are masked during the read.
The intended pattern:
Watchdog — mcu_interrupts.h
The AVR watchdog resets the board if it is not petted within the configured interval. The standard tool for autonomous firmware that must recover from a software lockup.
Enable the watchdog. The AVR hardware supports a fixed set of intervals; timeout_ms is snapped up to the nearest supported value:
| Requested | Actual |
|---|---|
| ≤ 15 | 15 ms |
| ≤ 30 | 30 ms |
| ≤ 60 | 60 ms |
| ≤ 120 | 120 ms |
| ≤ 250 | 250 ms |
| ≤ 500 | 500 ms |
| ≤ 1000 | 1 s |
| ≤ 2000 | 2 s |
| ≤ 4000 | 4 s |
| ≤ 8000 | 8 s |
The watchdog is disabled by the Arduino core before setup() runs, so a firmware must call watchdog_enable explicitly.
Pet the watchdog. Every call resets the timer. The standard pattern is to call this once per successful iteration of the main loop — if the loop locks up, the watchdog fires and the board resets.
Disable the watchdog. Useful for entering a critical section where you explicitly do not want a reset, or for a firmware that has decided its own recovery is better than a hard reset.
Do not call watchdog_disable and forget to re-enable. A watchdog enabled at boot and then disabled without reason leaves the firmware without the safety net it was designed to have.
Typed arrays — mcu_types.h
Typed-array containers are the memory-efficient representation for numerical arrays on AVR. See Memory model for the layout. The emitter uses these directly from Vyne source via:
Operations supported from Vyne source:
| Operation | Emitter lowering | Notes |
|---|---|---|
Array<Float64>() / [] | vyne_array_f64_create(0) | Empty container |
[1.0, 2.0, 3.0] | vyne_array_f64_create(3) + direct writes | Fixed-size literal |
arr.push(x) | vyne_array_f64_push(&arr, x) | Grows by 1.5× |
arr.size() | arr.size (field read) | O(1) |
arr[i] | arr.data[i] (direct load) | No bounds check |
arr[lo:hi] | vyne_array_f64_slice(&arr, lo, hi) | hi inclusive |
Internal C functions defined in mcu_types.h for the emitter's use:
The untyped VyneArray fallback exists for x := []; (which infers no element type) and for mixed-type literals. Its cost is 16 bytes per element. Annotate the binding with Array<Float64> or Array<Int64> whenever the elements are all one type.
Arena — mcu_arena.h
The arena header is not part of the Vyne-facing API. It is documented here for developers who are adding new bindings or debugging an allocation failure.
arena_alloc_aligned currently ignores align and calls arena_alloc. The default allocator already returns 8-byte-aligned pointers, so any align <= 8 is satisfied. A align > 8 request would need a real implementation if it is ever used.
arena_free_all resets g_mcu_cur, g_mcu_peak, and g_mcu_cp_top. It is called once by vyne_arduino.h before vyne_setup() and can be called from Vyne source via vmem.reset() if the binding exists on AVR (it does not currently).
See also
- Memory & Regions
- vi2c and vspi for typed bus wrappers
- Projects & Tooling for the
embeddedtemplate