Language Reference

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:

 shell snippetshell
vynec --arduino uno sketch.vy vynec --arduino uno --flash --monitor --port COM3 sketch.vy

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:

 shell snippetshell
vynec init blink --name blink --kind embedded --board arduino-uno --port COM5 cd blink vynec hardware setup vynec build vynec run

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.

 blink.vyvyne
use native arduino; arduino.serial_begin(115200); through i :: 0..9 -> loop { arduino.digital_write(13, 1); arduino.delay(100); arduino.digital_write(13, 0); arduino.delay(100); }; @bounded<512> region probe { scratch buf :: Float64[16]; through i :: 0..15 -> loop { buf[i] = arduino.sin(0.1 * i); }; arduino.serial_println(buf.mean()); };

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

HeaderFunctionsSurface
mcu_hardware.h14Pin mode, digital/analog I/O, delays, base trig, arena_used
mcu_serial.h7Available, read, read_line, parse, println, flush
mcu_timing.h2Pulse width, Timer1 read
mcu_math.h34Transcendentals (boxed + unboxed _f64), constrain, map, lerp, smoothstep, random
mcu_pins_ext.h9ADC voltage/reference/resolution, oversampling, toggle, pulse, shift, count
mcu_memory.h4Arena peak/free, free RAM, stack free
mcu_bits.h9Bit set/clear/toggle/read, byte split/merge, popcount, CRC-8
mcu_eeprom.h4Read/write Int64 and Float64 across resets
mcu_i2c.h8I2C master via Wire: byte/register read-write, clock
mcu_spi.h6SPI master via SPI: settings, byte/word transfer
mcu_realtime.h5@realtime watchdog and telemetry (opt-in)
mcu_interrupts.h8Counter-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_alloc is a pointer bump plus a bounds check. Exhaustion halts with while (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 untyped Array costs 16 bytes per element plus the same header. Use the annotated form whenever possible.
  • Push grows, rewind reclaims. push allocates 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_string copies into the arena and can trigger the halt path if full.
  • No out(). The boxed print engine is not linked. Use arduino.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.

 vyne snippetvyne
@bounded<512> region sensor_frame { scratch samples :: Float64[32]; through i :: 0..31 -> loop { samples[i] = arduino.analog_read(0); }; arduino.serial_println(samples.mean()); };

What is not bound

  • dot, norm, argmax, argmin are absent from the ARDUINO_MAP table. They would require typed-array containers in mcu_types.h plus boxAny lowering for MCU targets. Calling them from a sketch fails at compile time with "not defined".
  • attach_interrupt is counter-based, not callback-based. A Vyne function compiles to the boxed signature, which cannot be installed as an AVR void(void) ISR without compiler-side wrapper emission. Poll interrupt_count, interrupt_fired, and interrupt_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, and pop_front are not bound on AVR.
  • vlin.multiply through the Ops.vy wrapper is still boxed on MCU even though the kernel is unboxed; direct vlin.k_* calls from a sketch have not been hardware-tested.
  • No filesystem (vfs is 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

 vyne snippetvyne
arduino.pin_mode(pin :: Int64, mode :: Int64)

Configure a GPIO pin.

ParameterValues
pin0–13 (digital), 0–5 (analog pins used as digital 14–19)
mode0 = INPUT, 1 = OUTPUT, 2 = INPUT_PULLUP

Returns null.

 vyne snippetvyne
arduino.digital_write(pin :: Int64, val :: Int64)

Drive a pin low or high. val is 0 for LOW and any non-zero value for HIGH. Returns null.

 vyne snippetvyne
arduino.digital_read(pin :: Int64) -> Int64

Read a pin. Returns 0 or 1.

 vyne snippetvyne
arduino.analog_read(pin :: Int64) -> Int64

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).

 vyne snippetvyne
arduino.analog_write(pin :: Int64, val :: Int64)

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.

 vyne snippetvyne
arduino.delay(ms :: Int64)

Busy-wait for ms milliseconds. Blocks. Returns null.

 vyne snippetvyne
arduino.delay_microseconds(us :: Int64)

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.

 vyne snippetvyne
arduino.millis() -> Int64

Milliseconds since boot. Wraps at 2^32 (about 49.7 days). Returns Int64.

 vyne snippetvyne
arduino.micros() -> Int64

Microseconds since boot. Wraps at 2^32 (about 71 minutes). Returns Int64.

 vyne snippetvyne
arduino.serial_begin(baud :: Int64)

Configure the hardware UART. Standard rates: 9600, 19200, 38400, 57600,

  1. The Vyne entry point already calls this with 115200 before

vyne_setup(); a second call from Vyne source is idempotent. Returns null.

 vyne snippetvyne
arduino.serial_print(v)

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.

 vyne snippetvyne
arduino.sin(x :: Float64) -> Float64 arduino.cos(x :: Float64) -> Float64 arduino.sqrt(x :: Float64) -> Float64

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.

 vyne snippetvyne
arduino.arena_used() -> Int64

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:

 c snippetc
VyneValue vmem_runtime_checkpoint(void); void vmem_runtime_rewind(VyneValue cp); void vyne_panic_bounds(const char* dimLabel, int shapeBound, int line, int64_t got);

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

 vyne snippetvyne
arduino.serial_available() -> Int64

Bytes in the RX buffer. 0 when empty. Non-blocking.

 vyne snippetvyne
arduino.serial_read() -> Int64

Read one byte. Returns -1 when the RX buffer is empty. Non-blocking.

 vyne snippetvyne
arduino.serial_read_line() -> String

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.

 vyne snippetvyne
arduino.serial_parse_int() -> Int64

Read the next integer from the serial stream using Serial.parseInt() with its default 1-second timeout. Blocks. Returns 0 on timeout.

 vyne snippetvyne
arduino.serial_parse_float() -> Float64

Read the next float. Same blocking / timeout behaviour as serial_parse_int.

 vyne snippetvyne
arduino.serial_println(v)

Same as serial_print(v) followed by a newline. Returns null.

 vyne snippetvyne
arduino.serial_flush() -> null

Wait for the transmit buffer to drain. Returns null.


Timing — mcu_timing.h

 vyne snippetvyne
arduino.pulse_width(pin :: Int64) -> Int64

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.

 vyne snippetvyne
arduino.timer_read() -> Int64

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

 vyne snippetvyne
arduino.tan(x) -> Float64 arduino.asin(x) -> Float64 arduino.acos(x) -> Float64 arduino.atan(x) -> Float64 arduino.atan2(y, x) -> Float64 arduino.log(x) -> Float64 arduino.log10(x) -> Float64 arduino.exp(x) -> Float64 arduino.pow(x, y) -> Float64 arduino.fmod(x, y) -> Float64

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>:

  • tan and atan are defined for all inputs.
  • asin and acos return NaN for arguments outside [-1, 1].
  • log and log10 return -inf for 0, NaN for negative arguments.
  • exp saturates to +inf at large positive inputs.
  • pow returns NaN for pow(negative, non-integer).

The caller is responsible for domain clipping. arduino.constrain is usually the right tool.

Interpolation and clamping

 vyne snippetvyne
arduino.constrain(x, lo, hi) -> Float64

Returns lo if x < lo, hi if x > hi, otherwise x. If lo > hi, the result is hi (matching the desktop vmath.clamp behaviour).

 vyne snippetvyne
arduino.fmap(x, in_lo, in_hi, out_lo, out_hi) -> Float64

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.

 vyne snippetvyne
arduino.lerp(a, b, t) -> Float64

a + (b - a) * t. t is not clamped; extrapolation is the caller's choice.

 vyne snippetvyne
arduino.smoothstep(a, b, x) -> Float64

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.

 vyne snippetvyne
arduino.radians(deg) -> Float64 arduino.degrees(rad) -> Float64

Angle unit conversion. VYNE_PI (defined as 3.14159265358979323846 in mcu_math.h) is used, not <math.h>'s M_PI.

Random

 vyne snippetvyne
arduino.random(max) -> Int64 arduino.random(min, max) -> Int64 arduino.random_seed(seed)

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) returns 0..max-1.
  • arduino.random(min, max) returns min..max-1.
  • arduino.random_seed(seed) reseeds the LCG. Passing 0 is 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

 vyne snippetvyne
arduino.analog_read_voltage(pin :: Int64) -> Float64

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.

 vyne snippetvyne
arduino.analog_reference(mode :: Int64)
modeEffect on Uno R3
0DEFAULT — 5 V
1INTERNAL — 1.1 V (small signals, high precision)
2EXTERNAL — external AREF pin

Subsequent analog_read calls use the new reference. Returns null.

 vyne snippetvyne
arduino.analog_read_resolution(bits :: Int64)

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.

 vyne snippetvyne
arduino.analog_write_resolution(bits :: Int64)

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.

 vyne snippetvyne
arduino.analog_read_oversampled(pin :: Int64, n :: Int64) -> Float64

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.

 vyne snippetvyne
arduino.pin_toggle(pin :: Int64)

Equivalent to digitalWrite(pin, !digitalRead(pin)). Saves a function call and a variable. Returns null.

 vyne snippetvyne
arduino.pulse_in(pin :: Int64, state :: Int64, timeout_us :: Int64) -> Int64

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.

 vyne snippetvyne
arduino.shift_out(data_pin :: Int64, clk_pin :: Int64, bit_order :: Int64, val :: Int64, nbits :: Int64)

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.

 vyne snippetvyne
arduino.pulse_count(pin :: Int64, window_ms :: Int64) -> Int64

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

 vyne snippetvyne
arduino.arena_peak() -> Int64 arduino.arena_free() -> Int64

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.

 vyne snippetvyne
arduino.free_ram() -> Int64 arduino.stack_free() -> Int64

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.

 vyne snippetvyne
arduino.bit_set(x, n) -> Int64 # x | (1 << n) arduino.bit_clear(x, n) -> Int64 # x & ~(1 << n) arduino.bit_toggle(x, n) -> Int64 # x ^ (1 << n) arduino.bit_read(x, n) -> Int64 # (x >> n) & 1

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).

 vyne snippetvyne
arduino.low_byte(x) -> Int64 # x & 0xFF arduino.high_byte(x) -> Int64 # (x >> 8) & 0xFF arduino.make_word(hi, lo)-> Int64 # ((hi & 0xFF) << 8) | (lo & 0xFF)

Byte extraction and assembly. Useful for 16-bit payloads over I2C/SPI, register manipulation, and EEPROM serialization.

 vyne snippetvyne
arduino.popcount(x) -> Int64

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.

 vyne snippetvyne
arduino.crc8(data, seed) -> Int64

Dallas/Maxim CRC-8 (polynomial 0x31, MSB-first, initial value typically 0). One byte per call so the caller can chain:

 vyne snippetvyne
crc :: Int64 := 0; through i :: 0..n-1 -> loop { crc = arduino.crc8(frame[i], crc); };

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.

 vyne snippetvyne
arduino.eeprom_read_int(addr :: Int64) -> Int64 arduino.eeprom_write_int(addr :: Int64, val :: Int64)

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.

 vyne snippetvyne
arduino.eeprom_read_float(addr :: Int64) -> Float64 arduino.eeprom_write_float(addr :: Int64, val :: Float64)

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.

BindingReturnsNotes
arduino.i2c_begin()NullStart the bus master
arduino.i2c_end()NullRelease the peripheral
arduino.i2c_set_clock(hz)Null0 keeps the 100 kHz default
arduino.i2c_write(addr, value)Int64endTransmission status
arduino.i2c_read(addr)Int64One byte, or -1
arduino.i2c_write_reg(addr, reg, value)Int64Register write
arduino.i2c_read_reg(addr, reg)Int64Repeated-start read, or -1
arduino.i2c_available()Int64Bytes 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.

 vyne snippetvyne
use native arduino; use external "vi2c/vi2c.vy"; vi2c.begin(); id :: Int64 := vi2c.read_reg(0x68, 0x75); # MPU-6050 WHO_AM_I vi2c.end();

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.

BindingReturnsNotes
arduino.spi_begin()NullPower the peripheral
arduino.spi_end()NullRelease it
arduino.spi_set(clock_hz, mode)NullBegins a transaction; MSB first; mode 0..3
arduino.spi_end_transaction()NullEnds the transaction
arduino.spi_transfer(value)Int648-bit full-duplex
arduino.spi_transfer16(value)Int6416-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.

 vyne snippetvyne
use native arduino; use external "vspi/vspi.vy"; vspi.begin(); vspi.set(1000000, 0); id :: Int64 := vspi.transfer(0x9F); # JEDEC ID vspi.end_transaction(); vspi.end();

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.*:

BindingReturnsNotes
arduino.realtime_worst_ms()Float64Worst observed across all regions
arduino.realtime_overruns()Int64Total overruns
arduino.realtime_reset()NullClears all counters
arduino.realtime_worst_ms_named(name)Float64One region by name
arduino.realtime_overruns_named(name)Int64One 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.

 vyne snippetvyne
arduino.attach_interrupt(pin :: Int64, mode :: Int64) -> Int64

Install an edge-counting trampoline on pin. mode selects the edge type:

modeTrigger
0LOW
1CHANGE (both edges)
2RISING
3FALLING

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.

 vyne snippetvyne
arduino.detach_interrupt(pin :: Int64)

Remove the trampoline. Subsequent edges do nothing. Returns null.

 vyne snippetvyne
arduino.interrupt_count(pin :: Int64) -> Int64

Read the current edge count. Returns 0 for non-interrupt pins. Interrupts are masked during the read so the 64-bit value is coherent.

 vyne snippetvyne
arduino.interrupt_reset(pin :: Int64)

Reset the counter to zero. Returns null.

 vyne snippetvyne
arduino.interrupt_fired(pin :: Int64) -> Bool

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:

 vyne snippetvyne
arduino.attach_interrupt(2, 2); # D2, RISING through tick :: 0..1000000-1 -> loop { if arduino.interrupt_fired(2) { arduino.interrupt_reset(2); arduino.digital_write(13, 1); arduino.delay(50); arduino.digital_write(13, 0); } };

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.

 vyne snippetvyne
arduino.watchdog_enable(timeout_ms :: Int64)

Enable the watchdog. The AVR hardware supports a fixed set of intervals; timeout_ms is snapped up to the nearest supported value:

RequestedActual
≤ 1515 ms
≤ 3030 ms
≤ 6060 ms
≤ 120120 ms
≤ 250250 ms
≤ 500500 ms
≤ 10001 s
≤ 20002 s
≤ 40004 s
≤ 80008 s

The watchdog is disabled by the Arduino core before setup() runs, so a firmware must call watchdog_enable explicitly.

 vyne snippetvyne
arduino.watchdog_reset() -> null

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.

 vyne snippetvyne
arduino.watchdog_disable() -> null

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:

 vyne snippetvyne
region buffer { a :: Array<Float64> := []; a.push(1.0); a.push(2.0); # a.size() == 2 # a[0] == 1.0 };

Operations supported from Vyne source:

OperationEmitter loweringNotes
Array<Float64>() / []vyne_array_f64_create(0)Empty container
[1.0, 2.0, 3.0]vyne_array_f64_create(3) + direct writesFixed-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:

 c snippetc
VyneArray_f64 vyne_array_f64_create(int64_t n); VyneArray_i64 vyne_array_i64_create(int64_t n); void vyne_array_f64_push(VyneArray_f64* arr, double v); void vyne_array_i64_push(VyneArray_i64* arr, int64_t v); VyneValue vyne_array_f64_to_value(VyneArray_f64* arr); VyneValue vyne_array_i64_to_value(VyneArray_i64* arr); VyneArray_f64 vyne_value_to_array_f64(VyneValue v); VyneArray_i64 vyne_value_to_array_i64(VyneValue v); VyneArray_f64 vyne_array_f64_slice(VyneArray_f64* src, int64_t lo, int64_t hi); VyneArray_i64 vyne_array_i64_slice(VyneArray_i64* src, int64_t lo, int64_t hi);

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.

 c snippetc
void* arena_alloc(size_t size); void* arena_alloc_aligned(size_t size, size_t align); void arena_free_all(void); size_t arena_used(void); ArenaCheckpoint arena_checkpoint(void); void arena_rewind(ArenaCheckpoint cp);

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