--- /dev/null
+# AGENTS.md
+
+AVR firmware (ATmega328P, 16 MHz) for the "Wild Thumper" arm's **virtual servo**: a DYNAMIXEL bus slave with ID `0x21` on the half-duplex single-wire UART (PD2, picoUART, 115200 8N1). A protocol-2.0 1-byte WRITE (INS=0x03) to address 0x01 sets `OCR0A` (D6 LED PWM duty) and gets an 11-byte status reply; all other packets are silently ignored. The ROS 2 package side lives in the repo root and is documented in the root `AGENTS.md` — do not confuse the two.
+
+## Build / verify
+
+- `make` → `main.elf` / `main.hex` (WinAVR-style Makefile; sources in `SRC`/`SRCPP`: `main.c uart.c` + `dynamixel-avr/dynamixel.cpp picoUART/src/picoUART.cpp`). `make clean` removes all artifacts (`*.o *.elf *.hex *.map *.lss *.lst *.sym *.eep .dep`) — run it before committing.
+- **`picoUART/src/rxISR.cpp` is deliberately NOT in the build**: it targets the ATtiny (`GIMSK`/`PCMSK`/PCINT0, none exist on the 328P) and captures one byte only. Do not "fix" it into the build.
+- Flashing: `make program` (avrdude/avrisp2/usb). No programmer is attached in this environment; the user flashes elsewhere — do not attempt to flash here.
+- Debug console: 9600 baud on D0/D1 (`uart.c`, `printf`); prints "Start" at boot.
+- **No-hardware verification** (this environment has no python3, no host gcc, no simavr/qemu; shell is busybox ash):
+ 1. `make` must finish with `Errors: none`.
+ 2. `sh tools/verify_slave.sh` — host-side check of the slave's CRC + decision logic: loads the real CRC table from `dynamixel-avr/dynamixel.cpp` (lines 40–71, line-range sensitive), replicates `update_crc` and the `dynamixel_slave_poll` decisions, and checks known-good Soll CRCs, valid writes, and negatives.
+ 3. ISR sanity: `avr-objdump -d -C main.elf | sed -n '/<__vector_5>:/,/^$/p'` (PCINT2_vect = `__vector_5`).
+ 4. busybox ash gotcha: multi-digit positional params are broken (`$10` → `$1`+"0", also inside `$(( ))`) — use `shift`/named vars in shell scripts (see `tools/verify_slave.sh`).
+
+## Architecture (non-obvious)
+
+- `main.c`: sleep-based loop `if (!dynamixel_rxready) sleep_mode(); dynamixel_slave_poll();` — the rxready check **before** sleeping is load-bearing (a completed packet must be processed before the CPU can sleep).
+- Capture: naked `ISR(PCINT2_vect, ISR_NAKED)` in `dynamixel-avr/dynamixel.cpp` with hand-rolled SREG save/restore. PD2 = PCINT18 → `PCMSK2` (0x6D) is in memory space, so mask ops are `lds`/`andi`/`sts`, not `cbi`. Per byte: disable mask at entry, sample 8 bits using the picoUART `PURXSTART - 18`/`PURXWAIT` delays (16 MHz constants), re-arm the mask at exit so the next start bit is caught.
+- Capture state (all `volatile`): `dynamixel_rxindex` (buffer is 128 — `DYNAMIXEL_PACKET_SIZE` is 128, not 24), `dxl_expected` (=LEN+7, parsed from the LEN field at byte 7, only for a header-valid packet), `dxl_last_tick` (stale watchdog), `dynamixel_rxready`.
+- Stale watchdog: Timer1 free-running, prescaler 64 (4 µs/tick, set in `dynamixel_listen_init`); gap > 375 ticks (~1.5 ms) since the last captured byte → buffer restarts. TCNT0 (8-bit, wraps at 1.024 ms) cannot be used for this.
+- **Skip guard**: at ISR entry, if `rxindex >= dxl_expected`, skip the capture and just re-arm — a complete packet cannot have more start bits (the master waits for the reply; `poll()` resets state right after sending it). Load-bearing: `PU_DISABLE_IRQ=1` makes `putx()` run with `cli()`, so falling edges of our own 11-byte reply TX latch and one spurious ISR fires right after the last `putx()` byte. Without the guard the captured command is processed again and a **second reply** goes on the bus.
+- `dynamixel_slave_poll()`: validates header + CRC (`update_crc`, table in `dynamixel.cpp`), ID==0x21, INS==WRITE, len==13, addr==1 → `OCR0A = value`, then replies: wait for line idle, `_delay_us(50)` turnaround, 11× `putx`. Always restores idle state afterwards: PD2 pull-up (`putx` clears it, leaving the pin floating), re-arm PCMSK2, `rxindex = 0`, `dxl_expected = DYNAMIXEL_PACKET_SIZE`.
+- Timer ownership: Timer0 = LED PWM (D6, ~1 kHz; `OCR0A` doubles as the virtual servo's "value" — do not reconfigure). Timer1 = stale watchdog — do not reconfigure. picoUART timing constants assume F_CPU = 16 MHz (hardcoded in the Makefile `CDEFS`).
+- `dxl_packet_length()` is inline asm because -Os with GCC 15.2 dropped the high byte of the 16-bit result (see the comment in the source) — keep it in asm if touched.
+
+## Conventions / gotchas
+
+- C/C++ indentation: **tabs**, one tab per level — match surrounding code; do not introduce space indentation.
+- `dynamixel-avr/` is a vendored library with its own `.git` — treat it as mostly read-only; keep changes minimal and deliberate.
+- Legacy paths in `dynamixel.cpp` (`purx()` polling, `dynamixel_readpacket`/`dynamixel_txrx`, the `#ifdef TEST` printf branch) are **not** used by `main.c` — do not assume they are live.
+- Do not modify picoUART's `putx`/`purx` internals or the `PURXSTART`/`PURXWAIT`/`PUTXWAIT` constants — the bit timing is proven on real hardware.
+- Repo git (see root `AGENTS.md`): files are owned by `ubuntu`, shell runs as root → "dubious ownership" on git commands; `git config --global --add safe.directory <path>` if needed.
--- /dev/null
+# Hey Emacs, this is a -*- makefile -*-\r
+#\r
+# WinAVR makefile written by Eric B. Weddington, J�rg Wunsch, et al.\r
+# Released to the Public Domain\r
+# Please read the make user manual!\r
+#\r
+# Additional material for this makefile was submitted by:\r
+# Tim Henigan\r
+# Peter Fleury\r
+# Reiner Patommel\r
+# Sander Pool\r
+# Frederik Rouleau\r
+# Markus Pfaff\r
+#\r
+# On command line:\r
+#\r
+# make all = Make software.\r
+#\r
+# make clean = Clean out built project files.\r
+#\r
+# make coff = Convert ELF to AVR COFF (for use with AVR Studio 3.x or VMLAB).\r
+#\r
+# make extcoff = Convert ELF to AVR Extended COFF (for use with AVR Studio\r
+# 4.07 or greater).\r
+#\r
+# make program = Download the hex file to the device, using avrdude. Please\r
+# customize the avrdude settings below first!\r
+#\r
+# make filename.s = Just compile filename.c into the assembler code only\r
+#\r
+# To rebuild project do "make clean" then "make all".\r
+#\r
+\r
+# mth 2004/09 \r
+# Differences from WinAVR 20040720 sample:\r
+# - DEPFLAGS according to Eric Weddingtion's fix (avrfreaks/gcc-forum)\r
+# - F_OSC Define in CFLAGS and AFLAGS\r
+\r
+\r
+# MCU name\r
+MCU = atmega328p\r
+\r
+# Main Oscillator Frequency\r
+# This is only used to define F_OSC in all assembler and c-sources.\r
+#F_OSC = 3686400\r
+\r
+# Output format. (can be srec, ihex, binary)\r
+FORMAT = ihex\r
+\r
+# Target file name (without extension).\r
+TARGET = main\r
+\r
+\r
+# List C source files here. (C dependencies are automatically generated.)\r
+SRC = $(TARGET).c uart.c\r
+SRCPP = dynamixel-avr/dynamixel.cpp picoUART/src/picoUART.cpp\r
+\r
+# List Assembler source files here.\r
+# Make them always end in a capital .S. Files ending in a lowercase .s\r
+# will not be considered source files but generated files (assembler\r
+# output from the compiler), and will be deleted upon "make clean"!\r
+# Even though the DOS/Win* filesystem matches both .s and .S the same,\r
+# it will preserve the spelling of the filenames, and gcc itself does\r
+# care about how the name is spelled on its command-line.\r
+ASRC = \r
+\r
+\r
+\r
+# Optimization level, can be [0, 1, 2, 3, s]. \r
+# 0 = turn off optimization. s = optimize for size.\r
+# (Note: 3 is not always the best optimization level. See avr-libc FAQ.)\r
+OPT = s\r
+\r
+# Debugging format.\r
+# Native formats for AVR-GCC's -g are stabs [default], or dwarf-2.\r
+# AVR (extended) COFF requires stabs, plus an avr-objcopy run.\r
+DEBUG = stabs\r
+#DEBUG = dwarf-2\r
+\r
+# List any extra directories to look for include files here.\r
+# Each directory must be seperated by a space.\r
+EXTRAINCDIRS = \r
+\r
+\r
+# Compiler flag to set the C Standard level.\r
+# c89 - "ANSI" C\r
+# gnu89 - c89 plus GCC extensions\r
+# c99 - ISO C99 standard (not yet fully implemented)\r
+# gnu99 - c99 plus GCC extensions\r
+CSTANDARD = -std=gnu99\r
+\r
+# Place -D or -U options here\r
+CDEFS = -DF_CPU=16000000\r
+\r
+# Place -I options here\r
+CINCS = -ILib_TWI_USI_Slave_EEProm_1v3 -IpicoUART/src\r
+\r
+\r
+# Compiler flags.\r
+# -g*: generate debugging information\r
+# -O*: optimization level\r
+# -f...: tuning, see GCC manual and avr-libc documentation\r
+# -Wall...: warning level\r
+# -Wa,...: tell GCC to pass this to the assembler.\r
+# -adhlns...: create assembler listing\r
+CFLAGS = -g$(DEBUG)\r
+CFLAGS += $(CDEFS) $(CINCS)\r
+CFLAGS += -O$(OPT)\r
+CFLAGS += -funsigned-char -funsigned-bitfields -fpack-struct -fshort-enums -fcommon\r
+CFLAGS += -Wall -Wstrict-prototypes\r
+CFLAGS += -Wa,-adhlns=$(<:.c=.lst)\r
+CFLAGS += $(patsubst %,-I%,$(EXTRAINCDIRS))\r
+CFLAGS += $(CSTANDARD)\r
+CFLAGS += -DF_OSC=$(F_OSC)\r
+\r
+CPPFLAGS = -g$(DEBUG)\r
+CPPFLAGS += $(CDEFS) $(CINCS)\r
+CPPFLAGS += -O$(OPT)\r
+CPPFLAGS += -funsigned-char -funsigned-bitfields -fpack-struct -fshort-enums -fcommon\r
+CPPFLAGS += -Wall\r
+CPPFLAGS += -Wa,-adhlns=$(<:.cpp=.lst)\r
+CPPFLAGS += $(patsubst %,-I%,$(EXTRAINCDIRS))\r
+CPPFLAGS += -DF_OSC=$(F_OSC)\r
+\r
+\r
+\r
+# Assembler flags.\r
+# -Wa,...: tell GCC to pass this to the assembler.\r
+# -ahlms: create listing\r
+# -gstabs: have the assembler create line number information; note that\r
+# for use in COFF files, additional information about filenames\r
+# and function names needs to be present in the assembler source\r
+# files -- see avr-libc docs [FIXME: not yet described there]\r
+ASFLAGS = -Wa,-adhlns=$(<:.S=.lst),-gstabs \r
+ASFLAGS += -DF_OSC=$(F_OSC)\r
+\r
+\r
+#Additional libraries.\r
+\r
+# Minimalistic printf version\r
+PRINTF_LIB_MIN = -Wl,-u,vfprintf -lprintf_min\r
+\r
+# Floating point printf version (requires MATH_LIB = -lm below)\r
+PRINTF_LIB_FLOAT = -Wl,-u,vfprintf -lprintf_flt -lm\r
+\r
+PRINTF_LIB = $(PRINTF_LIB_MIN)\r
+\r
+# Minimalistic scanf version\r
+SCANF_LIB_MIN = -Wl,-u,vfscanf -lscanf_min\r
+\r
+# Floating point + %[ scanf version (requires MATH_LIB = -lm below)\r
+SCANF_LIB_FLOAT = -Wl,-u,vfscanf -lscanf_flt\r
+\r
+SCANF_LIB = \r
+\r
+MATH_LIB = #-lm\r
+\r
+# External memory options\r
+\r
+# 64 KB of external RAM, starting after internal RAM (ATmega128!),\r
+# used for variables (.data/.bss) and heap (malloc()).\r
+#EXTMEMOPTS = -Wl,-Tdata=0x801100,--defsym=__heap_end=0x80ffff\r
+\r
+# 64 KB of external RAM, starting after internal RAM (ATmega128!),\r
+# only used for heap (malloc()).\r
+#EXTMEMOPTS = -Wl,--defsym=__heap_start=0x801100,--defsym=__heap_end=0x80ffff\r
+\r
+EXTMEMOPTS =\r
+\r
+# Linker flags.\r
+# -Wl,...: tell GCC to pass this to linker.\r
+# -Map: create map file\r
+# --cref: add cross reference to map file\r
+LDFLAGS = -Wl,-Map=$(TARGET).map,--cref\r
+LDFLAGS += $(EXTMEMOPTS)\r
+LDFLAGS += $(PRINTF_LIB) $(SCANF_LIB) $(MATH_LIB)\r
+\r
+\r
+\r
+\r
+# Programming support using avrdude. Settings and variables.\r
+\r
+# Programming hardware: alf avr910 avrisp bascom bsd \r
+# dt006 pavr picoweb pony-stk200 sp12 stk200 stk500\r
+#\r
+# Type: avrdude -c ?\r
+# to get a full listing.\r
+#\r
+#AVRDUDE_PROGRAMMER = avr911\r
+AVRDUDE_PROGRAMMER = avrisp2\r
+\r
+# com1 = serial port. Use lpt1 to connect to parallel port.\r
+#AVRDUDE_PORT = /dev/ttyUSB0 # programmer connected to serial device\r
+AVRDUDE_PORT = usb # programmer connected to serial device\r
+\r
+AVRDUDE_WRITE_FLASH = -U flash:w:$(TARGET).hex\r
+#AVRDUDE_WRITE_EEPROM = -U eeprom:w:$(TARGET).eep\r
+\r
+\r
+# Uncomment the following if you want avrdude's erase cycle counter.\r
+# Note that this counter needs to be initialized first using -Yn,\r
+# see avrdude manual.\r
+#AVRDUDE_ERASE_COUNTER = -y\r
+\r
+# Uncomment the following if you do /not/ wish a verification to be\r
+# performed after programming the device.\r
+#AVRDUDE_NO_VERIFY = -V\r
+\r
+# Increase verbosity level. Please use this when submitting bug\r
+# reports about avrdude. See <http://savannah.nongnu.org/projects/avrdude> \r
+# to submit bug reports.\r
+#AVRDUDE_VERBOSE = -v -v\r
+\r
+AVRDUDE_FLAGS = -p $(MCU) -P $(AVRDUDE_PORT) -c $(AVRDUDE_PROGRAMMER)\r
+AVRDUDE_FLAGS += $(AVRDUDE_NO_VERIFY)\r
+AVRDUDE_FLAGS += $(AVRDUDE_VERBOSE)\r
+AVRDUDE_FLAGS += $(AVRDUDE_ERASE_COUNTER)\r
+\r
+\r
+\r
+# ---------------------------------------------------------------------------\r
+\r
+# Define directories, if needed.\r
+DIRAVR = c:/winavr\r
+DIRAVRBIN = $(DIRAVR)/bin\r
+DIRAVRUTILS = $(DIRAVR)/utils/bin\r
+DIRINC = .\r
+DIRLIB = $(DIRAVR)/avr/lib\r
+\r
+\r
+# Define programs and commands.\r
+SHELL = sh\r
+CC = avr-gcc\r
+CPP = avr-g++\r
+OBJCOPY = avr-objcopy\r
+OBJDUMP = avr-objdump\r
+SIZE = avr-size\r
+NM = avr-nm\r
+AVRDUDE = avrdude\r
+REMOVE = rm -f\r
+COPY = cp\r
+\r
+\r
+\r
+\r
+# Define Messages\r
+# English\r
+MSG_ERRORS_NONE = Errors: none\r
+MSG_BEGIN = -------- begin --------\r
+MSG_END = -------- end --------\r
+MSG_SIZE_BEFORE = Size before: \r
+MSG_SIZE_AFTER = Size after:\r
+MSG_COFF = Converting to AVR COFF:\r
+MSG_EXTENDED_COFF = Converting to AVR Extended COFF:\r
+MSG_FLASH = Creating load file for Flash:\r
+MSG_EEPROM = Creating load file for EEPROM:\r
+MSG_EXTENDED_LISTING = Creating Extended Listing:\r
+MSG_SYMBOL_TABLE = Creating Symbol Table:\r
+MSG_LINKING = Linking:\r
+MSG_COMPILING = Compiling:\r
+MSG_ASSEMBLING = Assembling:\r
+MSG_CLEANING = Cleaning project:\r
+\r
+\r
+\r
+\r
+# Define all object files.\r
+OBJ = $(SRC:.c=.o) $(ASRC:.S=.o) $(SRCPP:.cpp=.o)\r
+\r
+# Define all listing files.\r
+LST = $(ASRC:.S=.lst) $(SRC:.c=.lst) $(SRCPP:.cpp=.lst)\r
+\r
+\r
+# Compiler flags to generate dependency files.\r
+### GENDEPFLAGS = -Wp,-M,-MP,-MT,$(*F).o,-MF,.dep/$(@F).d\r
+GENDEPFLAGS = -MD -MP -MF .dep/$(@F).d\r
+\r
+# Combine all necessary flags and optional flags.\r
+# Add target processor to flags.\r
+ALL_CFLAGS = -mmcu=$(MCU) -I. $(CFLAGS) $(GENDEPFLAGS)\r
+ALL_ASFLAGS = -mmcu=$(MCU) -I. -x assembler-with-cpp $(ASFLAGS)\r
+ALL_CPPFLAGS = -mmcu=$(MCU) -I. $(CPPFLAGS) $(GENDEPFLAGS)\r
+\r
+\r
+\r
+\r
+\r
+# Default target.\r
+all: begin gccversion sizebefore build sizeafter finished end\r
+\r
+build: elf hex eep lss sym\r
+\r
+elf: $(TARGET).elf\r
+hex: $(TARGET).hex\r
+eep: $(TARGET).eep\r
+lss: $(TARGET).lss \r
+sym: $(TARGET).sym\r
+\r
+\r
+\r
+# Eye candy.\r
+# AVR Studio 3.x does not check make's exit code but relies on\r
+# the following magic strings to be generated by the compile job.\r
+begin:\r
+ @echo\r
+ @echo $(MSG_BEGIN)\r
+\r
+finished:\r
+ @echo $(MSG_ERRORS_NONE)\r
+\r
+end:\r
+ @echo $(MSG_END)\r
+ @echo\r
+\r
+\r
+# Display size of file.\r
+HEXSIZE = $(SIZE) --target=$(FORMAT) $(TARGET).hex\r
+ELFSIZE = $(SIZE) -A $(TARGET).elf\r
+sizebefore:\r
+ @if [ -f $(TARGET).elf ]; then echo; echo $(MSG_SIZE_BEFORE); $(ELFSIZE); echo; fi\r
+\r
+sizeafter:\r
+ @if [ -f $(TARGET).elf ]; then echo; echo $(MSG_SIZE_AFTER); $(ELFSIZE); echo; fi\r
+\r
+\r
+\r
+# Display compiler version information.\r
+gccversion : \r
+ @$(CC) --version\r
+\r
+\r
+\r
+# Program the device. \r
+program: $(TARGET).hex $(TARGET).eep\r
+ $(AVRDUDE) $(AVRDUDE_FLAGS) $(AVRDUDE_WRITE_FLASH) $(AVRDUDE_WRITE_EEPROM)\r
+\r
+\r
+\r
+\r
+# Convert ELF to COFF for use in debugging / simulating in AVR Studio or VMLAB.\r
+COFFCONVERT=$(OBJCOPY) --debugging \\r
+--change-section-address .data-0x800000 \\r
+--change-section-address .bss-0x800000 \\r
+--change-section-address .noinit-0x800000 \\r
+--change-section-address .eeprom-0x810000 \r
+\r
+\r
+coff: $(TARGET).elf\r
+ @echo\r
+ @echo $(MSG_COFF) $(TARGET).cof\r
+ $(COFFCONVERT) -O coff-avr $< $(TARGET).cof\r
+\r
+\r
+extcoff: $(TARGET).elf\r
+ @echo\r
+ @echo $(MSG_EXTENDED_COFF) $(TARGET).cof\r
+ $(COFFCONVERT) -O coff-ext-avr $< $(TARGET).cof\r
+\r
+\r
+\r
+# Create final output files (.hex, .eep) from ELF output file.\r
+%.hex: %.elf\r
+ @echo\r
+ @echo $(MSG_FLASH) $@\r
+ $(OBJCOPY) -O $(FORMAT) -R .eeprom $< $@\r
+\r
+%.eep: %.elf\r
+ @echo\r
+ @echo $(MSG_EEPROM) $@\r
+ -$(OBJCOPY) -j .eeprom --set-section-flags=.eeprom="alloc,load" \\r
+ --change-section-lma .eeprom=0 -O $(FORMAT) $< $@\r
+\r
+# Create extended listing file from ELF output file.\r
+%.lss: %.elf\r
+ @echo\r
+ @echo $(MSG_EXTENDED_LISTING) $@\r
+ $(OBJDUMP) -h -S $< > $@\r
+\r
+# Create a symbol table from ELF output file.\r
+%.sym: %.elf\r
+ @echo\r
+ @echo $(MSG_SYMBOL_TABLE) $@\r
+ $(NM) -n $< > $@\r
+\r
+\r
+\r
+# Link: create ELF output file from object files.\r
+.SECONDARY : $(TARGET).elf\r
+.PRECIOUS : $(OBJ)\r
+%.elf: $(OBJ)\r
+ @echo\r
+ @echo $(MSG_LINKING) $@\r
+ $(CC) $(ALL_CFLAGS) $(OBJ) --output $@ $(LDFLAGS)\r
+\r
+\r
+# Compile: create object files from C source files.\r
+%.o : %.c\r
+ @echo\r
+ @echo $(MSG_COMPILING) $<\r
+ $(CC) -c $(ALL_CFLAGS) $< -o $@ \r
+\r
+%.o : %.cpp\r
+ @echo\r
+ @echo $(MSG_COMPILING) $<\r
+ $(CPP) -c $(ALL_CPPFLAGS) $< -o $@ \r
+\r
+# Compile: create assembler files from C source files.\r
+%.s : %.c\r
+ $(CC) -S $(ALL_CFLAGS) $< -o $@\r
+\r
+\r
+# Assemble: create object files from assembler source files.\r
+%.o : %.S\r
+ @echo\r
+ @echo $(MSG_ASSEMBLING) $<\r
+ $(CC) -c $(ALL_ASFLAGS) $< -o $@\r
+\r
+\r
+\r
+# Target: clean project.\r
+clean: begin clean_list finished end\r
+\r
+clean_list :\r
+ @echo\r
+ @echo $(MSG_CLEANING)\r
+ $(REMOVE) $(TARGET).hex\r
+ $(REMOVE) $(TARGET).eep\r
+ $(REMOVE) $(TARGET).obj\r
+ $(REMOVE) $(TARGET).cof\r
+ $(REMOVE) $(TARGET).elf\r
+ $(REMOVE) $(TARGET).map\r
+ $(REMOVE) $(TARGET).obj\r
+ $(REMOVE) $(TARGET).a90\r
+ $(REMOVE) $(TARGET).sym\r
+ $(REMOVE) $(TARGET).lnk\r
+ $(REMOVE) $(TARGET).lss\r
+ $(REMOVE) $(OBJ)\r
+ $(REMOVE) $(LST)\r
+ $(REMOVE) $(SRC:.c=.s)\r
+ $(REMOVE) $(SRC:.c=.d)\r
+ $(REMOVE) .dep/*\r
+\r
+\r
+\r
+# Include the dependency files.\r
+-include $(shell mkdir .dep 2>/dev/null) $(wildcard .dep/*)\r
+\r
+\r
+# Listing of phony targets.\r
+.PHONY : all begin finish end sizebefore sizeafter gccversion \\r
+build elf hex eep lss sym coff extcoff \\r
+clean clean_list program\r
+\r
--- /dev/null
+#!/bin/sh
+# Verifies the DYNAMIXEL slave logic in avr/nano, using the CRC
+# implementation from dynamixel-avr/dynamixel.cpp itself:
+# - the table (lines 40-71) is loaded verbatim from the source
+# - update_crc() algorithm is replicated exactly (same table, same steps)
+# - fidelity proven against the known-good "Soll" CRCs in the source
+# - the slave decision sequence (mirrors dynamixel_slave_poll) is checked
+# for a 1 byte write to address 0x01 at ID 0x21, and for negatives
+# NOTE: busybox ash mangles multi-digit positional params, so packet
+# fields are captured into single-letter vars via shift (see fields()).
+set -e
+cd "$(dirname "$0")/.."
+
+# --- load the real table (dynamixel.cpp lines 40..71) into T0..T255 ---
+i=0
+for v in $(sed -n '40,71p' dynamixel-avr/dynamixel.cpp | tr -d ',' | tr -s ' \t' '\n' | grep '^0x'); do
+ eval "T$i=\$v"
+ i=$((i+1))
+done
+if [ $i -ne 256 ]; then echo "TABLE COUNT ERROR: $i" >&2; exit 2; fi
+
+# same algorithm as update_crc() in dynamixel.cpp
+crc() {
+ crc=0
+ for b in "$@"; do
+ idx=$(( ( ( (crc >> 8) & 0xff ) ^ b ) & 0xff ))
+ eval "t=\$T$idx"
+ crc=$(( ( (crc << 8) & 0xffff ) ^ t ))
+ done
+ printf '0x%04X' $(( crc & 0xffff ))
+}
+
+# capture a 13-byte packet's fields into single-letter vars.
+# packet layout: 1=FF 2=FF 3=FD 4=00 5=ID 6=LEN_L 7=LEN_H 8=INS
+# 9=ADDR_L 10=ADDR_H 11=VAL 12=CRC_L 13=CRC_H
+# sets: F_ID F_LEN F_INS F_ADDR F_VAL (F_LEN/F_ADDR already 16-bit int)
+fields() {
+ pkt=$1
+ set -- $pkt
+ F_ID=$5
+ F_LEN=$(( $6 + 7 + ( $7 << 8 ) ))
+ F_INS=$8
+ F_ADDR=$(( $9 + 0 ))
+ shift 9
+ F_ADDR=$(( F_ADDR + $1 * 256 ))
+ F_VAL=$2
+}
+
+fail=0
+check() {
+ if [ "$1" = "$2" ]; then echo "PASS $3"; else echo "FAIL $3 (got $1 want $2)"; fail=1; fi
+}
+
+echo "== fidelity: known-good Soll CRCs from the source =="
+check "$(crc 0xFF 0xFF 0xFD 0x00 0x01 0x09 0x00 0x03 0x74 0x00 0x00 0x02 0x00 0x00)" "0x89CA" "Soll write 16B (0xCA 0x89)"
+check "$(crc 0xFF 0xFF 0xFD 0x00 0x01 0x04 0x00 0x55 0x00)" "0x0CA1" "Soll reply 11B (0xA1 0x0C)"
+check "$(crc 0xFF 0xFF 0xFD 0x00 0x15 0x04 0x00 0x55 0x00 0x0B)" "0x4105" "Soll reply 12B (0x05 0x41)"
+check "$(crc 0xFF 0xFF 0xFD 0x00 0x0C 0x08 0x00 0x55 0x00 0xC1 0x02 0x00 0x00)" "0x0056" "Soll reply 15B (0x56 0x00)"
+
+echo "== valid 1 byte write, ID 0x21, addr 0x0001 =="
+r_crc=$(crc 0xFF 0xFF 0xFD 0x00 0x21 0x04 0x00 0x55 0x00)
+reply="0xFF 0xFF 0xFD 0x00 0x21 0x04 0x00 0x55 0x00 0x$(printf '%02x' $(( r_crc & 0xff ))) 0x$(printf '%02x' $(( r_crc >> 8 )))"
+echo " reply: $reply"
+
+for val in 0x00 0x7F 0x80 0xFF; do
+ pre="0xFF 0xFF 0xFD 0x00 0x21 0x06 0x00 0x03 0x01 0x00 $val"
+ c=$(crc $pre)
+ cmd="$pre 0x$(printf '%02x' $(( c & 0xff ))) 0x$(printf '%02x' $(( c >> 8 )))"
+ fields "$cmd"
+ # recompute CRC over the first 11 bytes the way the slave does
+ crc11=$(crc $(echo "$cmd" | cut -d' ' -f1-11))
+ check "$F_LEN" "13" "VAL=$val len from LEN field == 13"
+ check "$crc11" "$c" "VAL=$val slave CRC check passes (crc=$c)"
+ check "$F_ID" "0x21" "VAL=$val ID == 0x21"
+ check "$F_INS" "0x03" "VAL=$val INS == WRITE"
+ check "$F_ADDR" "1" "VAL=$val addr == 0x0001"
+ check "$F_VAL" "$val" "VAL=$val OCR0A set to $val"
+ echo " cmd : $cmd"
+done
+
+echo "== negatives =="
+mk() { # $1 = 13/14 byte packet with CRC appended; echoes it
+ local pre=$1 c
+ c=$(crc $pre)
+ echo "$pre 0x$(printf '%02x' $(( c & 0xff ))) 0x$(printf '%02x' $(( c >> 8 )))"
+}
+
+# bad CRC (stored value corrupted)
+pre="0xFF 0xFF 0xFD 0x00 0x21 0x06 0x00 0x03 0x01 0x00 0x10"
+c=$(crc $pre); c=$(( c ^ 0x01 ))
+bad="$pre 0x$(printf '%02x' $(( c & 0xff ))) 0x$(printf '%02x' $(( c >> 8 )))"
+c2=$(crc $(echo "$bad" | cut -d' ' -f1-11))
+check "$(( c2 == c ))" "0" "bad CRC: recompute($c2) != stored(0x$(printf '%04x' $c)) -> rejected"
+
+# wrong ID (0x22), valid CRC
+cmd=$(mk "0xFF 0xFF 0xFD 0x00 0x22 0x06 0x00 0x03 0x01 0x00 0x10")
+fields "$cmd"
+check "$F_ID" "0x22" "ID 0x22 != 0x21 -> silently ignored"
+
+# wrong INS (READ), valid CRC
+cmd=$(mk "0xFF 0xFF 0xFD 0x00 0x21 0x06 0x00 0x02 0x01 0x00 0x01")
+fields "$cmd"
+check "$F_INS" "0x02" "INS READ != WRITE -> silently ignored"
+
+# wrong address (0x0002), valid CRC
+cmd=$(mk "0xFF 0xFF 0xFD 0x00 0x21 0x06 0x00 0x03 0x02 0x00 0x10")
+fields "$cmd"
+check "$F_ADDR" "2" "addr 0x0002 != 1 -> silently ignored"
+
+# 2 byte write (LEN=7 -> total 14), valid CRC
+cmd=$(mk "0xFF 0xFF 0xFD 0x00 0x21 0x07 0x00 0x03 0x01 0x00 0x10 0x20")
+fields "$cmd"
+check "$F_LEN" "14" "word write: len=14 != 13 -> silently ignored"
+
+echo
+[ $fail -eq 0 ] && echo "ALL PASS" || { echo "FAILURES: $fail"; exit 1; }