From: Erik Andresen Date: Thu, 22 Oct 2026 17:15:44 +0000 (+0200) Subject: added dynamixel AVR client X-Git-Url: https://defiant.homedns.org/gitweb/?a=commitdiff_plain;h=e18b940b845b97ec96fe09bd704499ee5bc03deb;p=wt_open_manipulator.git added dynamixel AVR client --- diff --git a/.gitignore b/.gitignore index c18ae36..a19e77c 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,12 @@ COLCON_IGNORE +*.swp +.dep +*.o +*.eep +*.elf +*.hex +*.lss +*.lst +*.map +*.sym +*.lst diff --git a/avr/nano/AGENTS.md b/avr/nano/AGENTS.md new file mode 100644 index 0000000..043a7e3 --- /dev/null +++ b/avr/nano/AGENTS.md @@ -0,0 +1,34 @@ +# 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 ` if needed. diff --git a/avr/nano/Makefile b/avr/nano/Makefile new file mode 100644 index 0000000..d01e57d --- /dev/null +++ b/avr/nano/Makefile @@ -0,0 +1,453 @@ +# Hey Emacs, this is a -*- makefile -*- +# +# WinAVR makefile written by Eric B. Weddington, J�rg Wunsch, et al. +# Released to the Public Domain +# Please read the make user manual! +# +# Additional material for this makefile was submitted by: +# Tim Henigan +# Peter Fleury +# Reiner Patommel +# Sander Pool +# Frederik Rouleau +# Markus Pfaff +# +# On command line: +# +# make all = Make software. +# +# make clean = Clean out built project files. +# +# make coff = Convert ELF to AVR COFF (for use with AVR Studio 3.x or VMLAB). +# +# make extcoff = Convert ELF to AVR Extended COFF (for use with AVR Studio +# 4.07 or greater). +# +# make program = Download the hex file to the device, using avrdude. Please +# customize the avrdude settings below first! +# +# make filename.s = Just compile filename.c into the assembler code only +# +# To rebuild project do "make clean" then "make all". +# + +# mth 2004/09 +# Differences from WinAVR 20040720 sample: +# - DEPFLAGS according to Eric Weddingtion's fix (avrfreaks/gcc-forum) +# - F_OSC Define in CFLAGS and AFLAGS + + +# MCU name +MCU = atmega328p + +# Main Oscillator Frequency +# This is only used to define F_OSC in all assembler and c-sources. +#F_OSC = 3686400 + +# Output format. (can be srec, ihex, binary) +FORMAT = ihex + +# Target file name (without extension). +TARGET = main + + +# List C source files here. (C dependencies are automatically generated.) +SRC = $(TARGET).c uart.c +SRCPP = dynamixel-avr/dynamixel.cpp picoUART/src/picoUART.cpp + +# List Assembler source files here. +# Make them always end in a capital .S. Files ending in a lowercase .s +# will not be considered source files but generated files (assembler +# output from the compiler), and will be deleted upon "make clean"! +# Even though the DOS/Win* filesystem matches both .s and .S the same, +# it will preserve the spelling of the filenames, and gcc itself does +# care about how the name is spelled on its command-line. +ASRC = + + + +# Optimization level, can be [0, 1, 2, 3, s]. +# 0 = turn off optimization. s = optimize for size. +# (Note: 3 is not always the best optimization level. See avr-libc FAQ.) +OPT = s + +# Debugging format. +# Native formats for AVR-GCC's -g are stabs [default], or dwarf-2. +# AVR (extended) COFF requires stabs, plus an avr-objcopy run. +DEBUG = stabs +#DEBUG = dwarf-2 + +# List any extra directories to look for include files here. +# Each directory must be seperated by a space. +EXTRAINCDIRS = + + +# Compiler flag to set the C Standard level. +# c89 - "ANSI" C +# gnu89 - c89 plus GCC extensions +# c99 - ISO C99 standard (not yet fully implemented) +# gnu99 - c99 plus GCC extensions +CSTANDARD = -std=gnu99 + +# Place -D or -U options here +CDEFS = -DF_CPU=16000000 + +# Place -I options here +CINCS = -ILib_TWI_USI_Slave_EEProm_1v3 -IpicoUART/src + + +# Compiler flags. +# -g*: generate debugging information +# -O*: optimization level +# -f...: tuning, see GCC manual and avr-libc documentation +# -Wall...: warning level +# -Wa,...: tell GCC to pass this to the assembler. +# -adhlns...: create assembler listing +CFLAGS = -g$(DEBUG) +CFLAGS += $(CDEFS) $(CINCS) +CFLAGS += -O$(OPT) +CFLAGS += -funsigned-char -funsigned-bitfields -fpack-struct -fshort-enums -fcommon +CFLAGS += -Wall -Wstrict-prototypes +CFLAGS += -Wa,-adhlns=$(<:.c=.lst) +CFLAGS += $(patsubst %,-I%,$(EXTRAINCDIRS)) +CFLAGS += $(CSTANDARD) +CFLAGS += -DF_OSC=$(F_OSC) + +CPPFLAGS = -g$(DEBUG) +CPPFLAGS += $(CDEFS) $(CINCS) +CPPFLAGS += -O$(OPT) +CPPFLAGS += -funsigned-char -funsigned-bitfields -fpack-struct -fshort-enums -fcommon +CPPFLAGS += -Wall +CPPFLAGS += -Wa,-adhlns=$(<:.cpp=.lst) +CPPFLAGS += $(patsubst %,-I%,$(EXTRAINCDIRS)) +CPPFLAGS += -DF_OSC=$(F_OSC) + + + +# Assembler flags. +# -Wa,...: tell GCC to pass this to the assembler. +# -ahlms: create listing +# -gstabs: have the assembler create line number information; note that +# for use in COFF files, additional information about filenames +# and function names needs to be present in the assembler source +# files -- see avr-libc docs [FIXME: not yet described there] +ASFLAGS = -Wa,-adhlns=$(<:.S=.lst),-gstabs +ASFLAGS += -DF_OSC=$(F_OSC) + + +#Additional libraries. + +# Minimalistic printf version +PRINTF_LIB_MIN = -Wl,-u,vfprintf -lprintf_min + +# Floating point printf version (requires MATH_LIB = -lm below) +PRINTF_LIB_FLOAT = -Wl,-u,vfprintf -lprintf_flt -lm + +PRINTF_LIB = $(PRINTF_LIB_MIN) + +# Minimalistic scanf version +SCANF_LIB_MIN = -Wl,-u,vfscanf -lscanf_min + +# Floating point + %[ scanf version (requires MATH_LIB = -lm below) +SCANF_LIB_FLOAT = -Wl,-u,vfscanf -lscanf_flt + +SCANF_LIB = + +MATH_LIB = #-lm + +# External memory options + +# 64 KB of external RAM, starting after internal RAM (ATmega128!), +# used for variables (.data/.bss) and heap (malloc()). +#EXTMEMOPTS = -Wl,-Tdata=0x801100,--defsym=__heap_end=0x80ffff + +# 64 KB of external RAM, starting after internal RAM (ATmega128!), +# only used for heap (malloc()). +#EXTMEMOPTS = -Wl,--defsym=__heap_start=0x801100,--defsym=__heap_end=0x80ffff + +EXTMEMOPTS = + +# Linker flags. +# -Wl,...: tell GCC to pass this to linker. +# -Map: create map file +# --cref: add cross reference to map file +LDFLAGS = -Wl,-Map=$(TARGET).map,--cref +LDFLAGS += $(EXTMEMOPTS) +LDFLAGS += $(PRINTF_LIB) $(SCANF_LIB) $(MATH_LIB) + + + + +# Programming support using avrdude. Settings and variables. + +# Programming hardware: alf avr910 avrisp bascom bsd +# dt006 pavr picoweb pony-stk200 sp12 stk200 stk500 +# +# Type: avrdude -c ? +# to get a full listing. +# +#AVRDUDE_PROGRAMMER = avr911 +AVRDUDE_PROGRAMMER = avrisp2 + +# com1 = serial port. Use lpt1 to connect to parallel port. +#AVRDUDE_PORT = /dev/ttyUSB0 # programmer connected to serial device +AVRDUDE_PORT = usb # programmer connected to serial device + +AVRDUDE_WRITE_FLASH = -U flash:w:$(TARGET).hex +#AVRDUDE_WRITE_EEPROM = -U eeprom:w:$(TARGET).eep + + +# Uncomment the following if you want avrdude's erase cycle counter. +# Note that this counter needs to be initialized first using -Yn, +# see avrdude manual. +#AVRDUDE_ERASE_COUNTER = -y + +# Uncomment the following if you do /not/ wish a verification to be +# performed after programming the device. +#AVRDUDE_NO_VERIFY = -V + +# Increase verbosity level. Please use this when submitting bug +# reports about avrdude. See +# to submit bug reports. +#AVRDUDE_VERBOSE = -v -v + +AVRDUDE_FLAGS = -p $(MCU) -P $(AVRDUDE_PORT) -c $(AVRDUDE_PROGRAMMER) +AVRDUDE_FLAGS += $(AVRDUDE_NO_VERIFY) +AVRDUDE_FLAGS += $(AVRDUDE_VERBOSE) +AVRDUDE_FLAGS += $(AVRDUDE_ERASE_COUNTER) + + + +# --------------------------------------------------------------------------- + +# Define directories, if needed. +DIRAVR = c:/winavr +DIRAVRBIN = $(DIRAVR)/bin +DIRAVRUTILS = $(DIRAVR)/utils/bin +DIRINC = . +DIRLIB = $(DIRAVR)/avr/lib + + +# Define programs and commands. +SHELL = sh +CC = avr-gcc +CPP = avr-g++ +OBJCOPY = avr-objcopy +OBJDUMP = avr-objdump +SIZE = avr-size +NM = avr-nm +AVRDUDE = avrdude +REMOVE = rm -f +COPY = cp + + + + +# Define Messages +# English +MSG_ERRORS_NONE = Errors: none +MSG_BEGIN = -------- begin -------- +MSG_END = -------- end -------- +MSG_SIZE_BEFORE = Size before: +MSG_SIZE_AFTER = Size after: +MSG_COFF = Converting to AVR COFF: +MSG_EXTENDED_COFF = Converting to AVR Extended COFF: +MSG_FLASH = Creating load file for Flash: +MSG_EEPROM = Creating load file for EEPROM: +MSG_EXTENDED_LISTING = Creating Extended Listing: +MSG_SYMBOL_TABLE = Creating Symbol Table: +MSG_LINKING = Linking: +MSG_COMPILING = Compiling: +MSG_ASSEMBLING = Assembling: +MSG_CLEANING = Cleaning project: + + + + +# Define all object files. +OBJ = $(SRC:.c=.o) $(ASRC:.S=.o) $(SRCPP:.cpp=.o) + +# Define all listing files. +LST = $(ASRC:.S=.lst) $(SRC:.c=.lst) $(SRCPP:.cpp=.lst) + + +# Compiler flags to generate dependency files. +### GENDEPFLAGS = -Wp,-M,-MP,-MT,$(*F).o,-MF,.dep/$(@F).d +GENDEPFLAGS = -MD -MP -MF .dep/$(@F).d + +# Combine all necessary flags and optional flags. +# Add target processor to flags. +ALL_CFLAGS = -mmcu=$(MCU) -I. $(CFLAGS) $(GENDEPFLAGS) +ALL_ASFLAGS = -mmcu=$(MCU) -I. -x assembler-with-cpp $(ASFLAGS) +ALL_CPPFLAGS = -mmcu=$(MCU) -I. $(CPPFLAGS) $(GENDEPFLAGS) + + + + + +# Default target. +all: begin gccversion sizebefore build sizeafter finished end + +build: elf hex eep lss sym + +elf: $(TARGET).elf +hex: $(TARGET).hex +eep: $(TARGET).eep +lss: $(TARGET).lss +sym: $(TARGET).sym + + + +# Eye candy. +# AVR Studio 3.x does not check make's exit code but relies on +# the following magic strings to be generated by the compile job. +begin: + @echo + @echo $(MSG_BEGIN) + +finished: + @echo $(MSG_ERRORS_NONE) + +end: + @echo $(MSG_END) + @echo + + +# Display size of file. +HEXSIZE = $(SIZE) --target=$(FORMAT) $(TARGET).hex +ELFSIZE = $(SIZE) -A $(TARGET).elf +sizebefore: + @if [ -f $(TARGET).elf ]; then echo; echo $(MSG_SIZE_BEFORE); $(ELFSIZE); echo; fi + +sizeafter: + @if [ -f $(TARGET).elf ]; then echo; echo $(MSG_SIZE_AFTER); $(ELFSIZE); echo; fi + + + +# Display compiler version information. +gccversion : + @$(CC) --version + + + +# Program the device. +program: $(TARGET).hex $(TARGET).eep + $(AVRDUDE) $(AVRDUDE_FLAGS) $(AVRDUDE_WRITE_FLASH) $(AVRDUDE_WRITE_EEPROM) + + + + +# Convert ELF to COFF for use in debugging / simulating in AVR Studio or VMLAB. +COFFCONVERT=$(OBJCOPY) --debugging \ +--change-section-address .data-0x800000 \ +--change-section-address .bss-0x800000 \ +--change-section-address .noinit-0x800000 \ +--change-section-address .eeprom-0x810000 + + +coff: $(TARGET).elf + @echo + @echo $(MSG_COFF) $(TARGET).cof + $(COFFCONVERT) -O coff-avr $< $(TARGET).cof + + +extcoff: $(TARGET).elf + @echo + @echo $(MSG_EXTENDED_COFF) $(TARGET).cof + $(COFFCONVERT) -O coff-ext-avr $< $(TARGET).cof + + + +# Create final output files (.hex, .eep) from ELF output file. +%.hex: %.elf + @echo + @echo $(MSG_FLASH) $@ + $(OBJCOPY) -O $(FORMAT) -R .eeprom $< $@ + +%.eep: %.elf + @echo + @echo $(MSG_EEPROM) $@ + -$(OBJCOPY) -j .eeprom --set-section-flags=.eeprom="alloc,load" \ + --change-section-lma .eeprom=0 -O $(FORMAT) $< $@ + +# Create extended listing file from ELF output file. +%.lss: %.elf + @echo + @echo $(MSG_EXTENDED_LISTING) $@ + $(OBJDUMP) -h -S $< > $@ + +# Create a symbol table from ELF output file. +%.sym: %.elf + @echo + @echo $(MSG_SYMBOL_TABLE) $@ + $(NM) -n $< > $@ + + + +# Link: create ELF output file from object files. +.SECONDARY : $(TARGET).elf +.PRECIOUS : $(OBJ) +%.elf: $(OBJ) + @echo + @echo $(MSG_LINKING) $@ + $(CC) $(ALL_CFLAGS) $(OBJ) --output $@ $(LDFLAGS) + + +# Compile: create object files from C source files. +%.o : %.c + @echo + @echo $(MSG_COMPILING) $< + $(CC) -c $(ALL_CFLAGS) $< -o $@ + +%.o : %.cpp + @echo + @echo $(MSG_COMPILING) $< + $(CPP) -c $(ALL_CPPFLAGS) $< -o $@ + +# Compile: create assembler files from C source files. +%.s : %.c + $(CC) -S $(ALL_CFLAGS) $< -o $@ + + +# Assemble: create object files from assembler source files. +%.o : %.S + @echo + @echo $(MSG_ASSEMBLING) $< + $(CC) -c $(ALL_ASFLAGS) $< -o $@ + + + +# Target: clean project. +clean: begin clean_list finished end + +clean_list : + @echo + @echo $(MSG_CLEANING) + $(REMOVE) $(TARGET).hex + $(REMOVE) $(TARGET).eep + $(REMOVE) $(TARGET).obj + $(REMOVE) $(TARGET).cof + $(REMOVE) $(TARGET).elf + $(REMOVE) $(TARGET).map + $(REMOVE) $(TARGET).obj + $(REMOVE) $(TARGET).a90 + $(REMOVE) $(TARGET).sym + $(REMOVE) $(TARGET).lnk + $(REMOVE) $(TARGET).lss + $(REMOVE) $(OBJ) + $(REMOVE) $(LST) + $(REMOVE) $(SRC:.c=.s) + $(REMOVE) $(SRC:.c=.d) + $(REMOVE) .dep/* + + + +# Include the dependency files. +-include $(shell mkdir .dep 2>/dev/null) $(wildcard .dep/*) + + +# Listing of phony targets. +.PHONY : all begin finish end sizebefore sizeafter gccversion \ +build elf hex eep lss sym coff extcoff \ +clean clean_list program + diff --git a/avr/nano/dynamixel-avr b/avr/nano/dynamixel-avr new file mode 160000 index 0000000..7151f97 --- /dev/null +++ b/avr/nano/dynamixel-avr @@ -0,0 +1 @@ +Subproject commit 7151f970b4f4d7649d4ad025a099baa8769f05b2 diff --git a/avr/nano/main.c b/avr/nano/main.c new file mode 100644 index 0000000..29a5e3b --- /dev/null +++ b/avr/nano/main.c @@ -0,0 +1,76 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "uart.h" +#include "dynamixel-avr/dynamixel.h" +#include "dynamixel-avr/xm.h" + +/** + * Nano Pinout + * A0 PC0/ADC0 + * A1 PC1/ADC1 + * A2 PC2/ADC2 + * A3 PC3/ADC3 + * A4 PC4/ADC4/SDA + * A5 PC5/ADC5/SCL + * A6 ADC6 + * A7 ADC7 + * D0 PD0/RX + * D1 PD1/TX + * D2 PD2/INT0 dynamixel half-duplex UART + * D3 PD3/INT1/OC2B + * D4 PD4/T0 + * D5 PD5/OC0B/T1 + * D6 PD6/OC0A/AIN0 LED + * D7 PD7/AIN1 + * D8 PB0/ICP1 + * D9 PB1/OC1A + * D10 PB2/SS/OC1B + * D11 PB3/MOSI/OC2A + * D12 PB4/MISO + * D13 PB5/SCK + */ + + +/* + * http://emanual.robotis.com/docs/en/dxl/x/xm430-w350 + * http://emanual.robotis.com/docs/en/dxl/protocol2 + * https://nerdralph.blogspot.com/2020/02/building-better-bit-bang-uart-picouart.html + */ +int main(void) { + DDRD = (1<<6); + PORTD = (1<<6); + setup_uart(9600); + uart_setup_stdout(); + dynamixel_init(); + dynamixel_listen_init(); + + // LED + // Timer 0: Fast PWM non-inverting mode, Top=255 => ~1kHz + // Prescaler=64 + TCCR0A = (1 << COM0A1) | (1 << WGM01) | (1 << WGM00); + TCCR0B = (1 << CS01) | (1 << CS00); + OCR0A = 255; + + printf_P(PSTR("\r\nStart\r\n")); + + set_sleep_mode(SLEEP_MODE_IDLE); + sei(); + while(1) { + // a packet may have completed while the CPU was awake (its last + // byte's ISR ran outside of sleep): process it now instead of + // sleeping with it pending + if (!dynamixel_rxready) { + sleep_mode(); + } + dynamixel_slave_poll(); + } + + return 0; +} diff --git a/avr/nano/picoUART b/avr/nano/picoUART new file mode 160000 index 0000000..c536976 --- /dev/null +++ b/avr/nano/picoUART @@ -0,0 +1 @@ +Subproject commit c53697625a000fecc43040c0097dfd16bb25b2b9 diff --git a/avr/nano/ringbuffer.h b/avr/nano/ringbuffer.h new file mode 100644 index 0000000..ed8b022 --- /dev/null +++ b/avr/nano/ringbuffer.h @@ -0,0 +1,34 @@ +#ifndef RINGBUFFER_H +#define RINGBUFFER_H + +#define RINGBUFFER_LEN 100 +#define RINGBUFFER_MAX_NUM 1 + +typedef struct ringbuffer { + char read[RINGBUFFER_LEN]; + char *in_read_ptr; + char *out_read_ptr; + char write[RINGBUFFER_LEN]; + char *in_write_ptr; + char *out_write_ptr; + FILE *dev; + FILE *dev_in_as_out; + uint8_t newlines; + char block_read; +} ringbuffer_t; + +ringbuffer_t *ringbuffers[RINGBUFFER_MAX_NUM]; +uint8_t num_ringbuffers; + +void ringbuffer_setup(FILE *stream, ringbuffer_t *buffer); +void ringbuffer_setup_in_as_out(FILE *stream, ringbuffer_t *buffer); +void init_ringbuffers(void); +void stream_setup(FILE *uart_stream); +void stream_setup_out_only(FILE *stream); +void stream_setup_in_as_out(FILE *stream, int ringbuffer_putchar_sound(char, FILE*)); +uint8_t ringbuffer_busy(void); +void ringbuffer_set_read_noblock(FILE *stream); +void ringbuffer_set_read_block(FILE *stream, char c); + +#endif + diff --git a/avr/nano/tools/verify_slave.sh b/avr/nano/tools/verify_slave.sh new file mode 100644 index 0000000..8629eff --- /dev/null +++ b/avr/nano/tools/verify_slave.sh @@ -0,0 +1,116 @@ +#!/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; } diff --git a/avr/nano/uart.c b/avr/nano/uart.c new file mode 100644 index 0000000..6fb768f --- /dev/null +++ b/avr/nano/uart.c @@ -0,0 +1,97 @@ +#include +#include "uart.h" +#include + +#define UART_UBRR_CALC(BAUD_,FREQ_) ((FREQ_)/((BAUD_)*16L)-1) + +static volatile char read[RINGBUFFER_LEN]; +static volatile char *in_read_ptr; +static volatile char *out_read_ptr; + +ISR(USART_RX_vect) { + // update read from uart + if (UCSR0A & (1<> 8); + UBRR0L = (uint8_t)UART_UBRR_CALC(rate, F_CPU); + + in_read_ptr = out_read_ptr = read; +} + + +void uart_putc(char *c) { + while (!(UCSR0A & (1<out_write_ptr != buffer->in_write_ptr) { + if (UCSR0A & (1<out_write_ptr; + if (buffer->out_write_ptr < buffer->write + RINGBUFFER_LEN - 1) buffer->out_write_ptr++; + else buffer->out_write_ptr = buffer->write; + } + } + + // update read from uart + if (in_read_ptr != out_read_ptr) { + *buffer->in_read_ptr = *out_read_ptr; + + // update newline chars + if (buffer->block_read == *buffer->in_read_ptr) buffer->newlines++; + + if (buffer->in_read_ptr < buffer->read + RINGBUFFER_LEN - 1) buffer->in_read_ptr++; + else buffer->in_read_ptr = buffer->read; + + // move pointer + if (out_read_ptr < read + RINGBUFFER_LEN - 1) out_read_ptr++; + else out_read_ptr = read; + } +} + diff --git a/avr/nano/uart.h b/avr/nano/uart.h new file mode 100644 index 0000000..1225590 --- /dev/null +++ b/avr/nano/uart.h @@ -0,0 +1,18 @@ +#ifndef UART_H +#define UART_H + +#include +#include "ringbuffer.h" + +void setup_uart(unsigned int rate); +void uart_putc(char *c); +void uart_puts(char *s); +int uart_getc(void); +void uart_puti(int i); +int uart_putchar(char c, FILE *stream); +int uart_getchar(FILE *stream); +void uart_setup_stdout(void); +void uart_stream_update(ringbuffer_t *buffer); + +#endif +