SpindelController
RP2040 + W5500: A LinuxCNC Spindle Closed-Loop Controller
요약
SpindelController는 Raspberry Pi RP2040과 WIZnet W5500 Ethernet 컨트롤러를 기반으로 구축한 CNC 스핀들 전용 실시간 제어기입니다. LinuxCNC와 Remora 프로토콜 over UDP로 통신하며, **21-bit 절대 자기 인코더(MT6835)**를 사용해 속도 제어(M3)와 위치 제어(M19 리지드 태핑)를 단일 펌웨어에서 구현합니다. W5500이 TCP/IP 스택 전체를 하드웨어로 처리하기 때문에, RP2040은 10kHz PID 루프와 160kHz 인코더 샘플링을 소프트웨어 네트워크 스택 충돌 없이 실행할 수 있습니다. 수만 원 부품으로 산업용 컨트롤러에서만 지원되던 스핀들 오리엔테이션을 DIY 환경에서 구현했다는 점이 주목할 만합니다.
개요
LinuxCNC 기반 DIY CNC 머신에서 스핀들 제어는 오랫동안 약점으로 꼽혀왔습니다. 일반적인 Remora 보드(EC300, EC500 등)는 축 스텝 제너레이터를 중심으로 설계되어 있고, 스핀들은 단순 PWM 출력 수준으로만 처리합니다. 이 구조로는 G-code M19 커맨드가 요구하는 스핀들 오리엔테이션과 리지드 태핑이 불가능합니다. 클로즈드루프 스핀들 위치 제어는 Siemens Sinumerik, FANUC 시리즈처럼 수백~수천만 원대 산업용 컨트롤러에서만 지원되던 기능입니다.
SpindelController는 이 공백을 정면으로 겨냥합니다. Waveshare RP2040 Zero 또는 RP2040 Plus에 W5500 Ethernet 컨트롤러와 MT6835 21-bit 자기 인코더를 조합해, LinuxCNC의 Remora 프로토콜 명령을 Ethernet으로 수신하고 스핀들을 속도·위치 이중 모드로 제어합니다. 빌드 환경은 Raspberry Pi Pico SDK + CMake + Ninja이며, 주된 대상 독자는 DIY 선반·밀링머신을 운용하면서 리지드 태핑 기능을 추가하려는 메이커와 LinuxCNC 기반 CNC 통합 개발자입니다.
아키텍처
전체 데이터 흐름은 다음과 같습니다.
**Remora 패킷 구조(64바이트)**는 다음 필드로 구성됩니다.
[0..3]헤더 (REMORA_PRU_WRITE/REMORA_PRU_READ)[4..7]floatspeed_setpoint_rpm[8]uint8direction(0=CW, 1=CCW)[9]uint8brake_cmd[10]uint8enable[11]uint8control_mode(0=속도, 1=위치)[12..15]floatposition_setpoint_deg
피드백 패킷에는 speed_measured_rpm과 E-Stop·과전류·워치독 등 6개 상태 비트(status_bits)가 담겨 LinuxCNC로 반환됩니다.
기술 배경
Remora over Ethernet: LinuxCNC 실시간 분산 제어 프로토콜
LinuxCNC는 PC에서 실행되는 오픈소스 CNC 제어 소프트웨어로, G-code 경로 계획과 HAL(Hardware Abstraction Layer) 기반 하드웨어 추상화를 담당합니다. 전통적으로 PC가 직접 스텝 펄스를 생성했지만, 고속·다축 환경에서는 PC의 실시간 부담이 커져 제어 품질이 저하됩니다. Remora는 이 문제를 해결하기 위해 STM32 등 외부 MCU에 실시간 처리를 위임하는 오픈소스 펌웨어 프레임워크입니다. MCU는 LinuxCNC로부터 Remora 포맷의 커맨드 패킷을 수신해 모터·인코더·IO를 직접 제어하고, 피드백 패킷을 반환합니다.
원래 Remora는 SPI 또는 RS485 기반이었으나, W5500 Ethernet 버전은 LAN 케이블로 호스트와 컨트롤러를 분리해 배선 자유도와 노이즈 내성을 동시에 확보합니다. SpindelController는 이 Ethernet 변형을 RP2040으로 구현한 사례입니다. LinuxCNC M3 명령은 speed_setpoint_rpm으로, M19는 position_setpoint_deg와 control_mode=1로 변환되어 64바이트 UDP 패킷으로 전송됩니다.
→ Remora 공식 저장소: https://github.com/scottalford75/Remora
W5500 하드웨어 TCP/IP 오프로딩
W5500은 WIZnet이 개발한 하드웨어 TCP/IP 컨트롤러로, MAC·PHY·TCP/IP 소켓 엔진을 단일 칩에 통합합니다. MCU는 SPI를 통해 W5500과 통신하며, 소프트웨어 TCP/IP 스택을 구현할 필요가 없습니다. CNC 실시간 제어 환경에서 이 구조가 결정적인 이유는 지터(jitter) 억제 때문입니다. 소프트웨어 스택은 MCU 인터럽트와 경합하며 패킷 처리 타이밍이 불규칙해지지만, W5500은 네트워크 처리를 하드웨어에서 독립적으로 처리해 제어 루프에 간섭하지 않습니다.
SpindelController에서 W5500은 SPI 62.5MHz로 RP2040에 연결되며, RP2040의 DMA 채널 2개(TX/RX)를 활용한 버스트 전송으로 8바이트 이상 패킷에서 CPU 개입 없이 데이터를 처리합니다. DHCP 클라이언트를 내장해 자동 IP 할당을 지원하며, 2초 타임아웃 후 정적 IP로 자동 전환합니다. PHY 링크 단절 시 200ms 주기로 재연결을 시도해 전원 투입 순서에 관계없이 안정적으로 복구됩니다.
→ W5500 데이터시트: https://docs.wiznet.io/Product/iEthernet/W5500/overview
AMR 절대 자기 인코더: MT6835
MT6835는 MagnTek의 4세대 자기 각도 인코더 IC로, 이방성 자기저항(AMR, Anisotropic Magnetoresistive) 기술 기반입니다. 칩 표면에 형성된 두 쌍의 AMR 휘트스톤 브리지가 회전 자기장의 방향을 감지하여 0°~360° 절대 각도를 출력합니다. 광학 인코더와 달리 먼지·절삭유·진동에 강하며, 비접촉 방식이므로 마모가 없습니다. 21-bit 해상도는 1회전당 2,097,152 스텝으로, 스핀들 1°를 약 5,825 카운트로 분해합니다. 최대 동작 속도는 120,000 RPM으로, CNC 고속 가공 스핀들에서도 정밀 피드백이 가능합니다.
SpindelController에서 MT6835는 **SPI 인터페이스(최대 16MHz)**로 RP2040에 연결되어 160kHz 샘플링 주기로 절대 각도를 읽습니다. 이 절대 각도값이 PID 제어 루프의 피드백 입력이 되어 M19 스핀들 오리엔테이션 시 목표 각도 ±0.5° 이내 정지(deadband 설정)를 구현합니다. 5,000 RPM 이상에서는 자동으로 위치 모드가 비활성화되고 4,500 RPM 이하로 복귀 시 재활성화되는 히스테리시스 로직이 firmware에 구현되어 있어, 고속 회전 중 의도치 않은 위치 제어 진입을 방지합니다.
→ MT6835 제품 페이지: https://www.avnet.com/apac/products/new-products/npi/aac-202509-novosense/
기술 특징
이중 제어 모드 전환이 핵심 차별점입니다. 속도 모드(CONTROL_MODE_SPEED)는 LinuxCNC M3 S명령을 RPM 목표값으로 받아 PID로 추종하고, 위치 모드(CONTROL_MODE_POSITION)는 M19 P명령의 목표 각도(deg)로 최단 경로 이동을 수행합니다. 두 모드는 런타임에 Remora 패킷 한 필드 변경만으로 전환되며, 스레딩·탭핑 같은 복합 작업에서 LinuxCNC가 필요에 따라 모드를 전환할 수 있습니다.
- PID 제어 루프: 기본값 Kp=1.0, Ki=0.25, Kd=0.005, 10kHz 실행
- 모터 PWM: 20kHz 캐리어 주파수, H-Bridge 방향·브레이크 제어 포함
- 램프 가속: 최대 3,000 RPM/s 설정으로 급가속에 의한 기계적 충격 방지
- RPM 범위: 0~12,000 RPM (config.h에서 조정 가능)
안전 아키텍처는 다층으로 구성됩니다. 하드웨어 워치독이 런타임 중 예외 상황을 감지하면 PWM 출력을 차단하고, **E-Stop 핀(GPIO 3)**은 즉시 모터를 중단시킵니다. ACS712 전류 센서는 선택 사항이지만, 과전류 감지 시 STATUS_BIT_OVERCURRENT를 Remora 피드백으로 LinuxCNC에 전달해 상위 레벨 인터록을 구성할 수 있습니다. 6개 상태 비트(E-Stop, 과전류, 과온, 워치독, 폴트, 인코더 결함)가 표준화된 비트맵으로 피드백되어 LinuxCNC HAL 스크립트에서 직접 조건 처리가 가능합니다.
모듈식 설계도 주목할 만합니다. config.h 단일 파일에서 W5500·인코더·디스플레이·ADC·WS2812 모듈을 플래그 하나(0/1)로 활성화·비활성화할 수 있으며, 빌드 단계 0~5로 나뉜 HARDWARETEST_BRINGUP_STAGE로 단계적 하드웨어 검증이 가능합니다.
W5500 적용 구조
SpindelController는 W5500을 실제 사용하며, 역할이 명확하게 정의되어 있습니다.
기존 소프트웨어 Ethernet 구조의 한계
RP2040이 소프트웨어 TCP/IP 스택을 직접 처리할 경우, 네트워크 패킷 처리와 10kHz PID 루프가 동일한 CPU 사이클을 두고 경합합니다. 패킷 수신 타이밍이 제어 루프 주기에 간섭하면 LinuxCNC 측에서 joint following error가 발생하고, CNC 동작이 중단됩니다.
W5500 적용 구조
- 하드웨어 TCP/IP 오프로딩: W5500이 DHCP·UDP 소켓·PHY 링크를 독립적으로 처리
- SPI + DMA 버스트: RP2040 DMA 채널 2개 전용 할당, 8바이트 이상 전송에서 CPU 개입 없이 처리
- 폴링 기반 비블로킹 수신:
Remora_iface_poll()이 최대 4패킷/호출로 수신 버스트를 처리하며, 수신 없으면 즉시 반환해 제어 루프에 지연을 주지 않음 - 자동 복구 루프: W5500 초기화 실패 또는 PHY 링크 단절 시 200ms 주기로 재초기화 시도
기대 효과
- RP2040 코어가 네트워크 처리 부담 없이 PID·인코더·PWM에만 집중 가능
- 유선 Ethernet 특성상 Wi-Fi 대비 지터가 결정론적으로 낮아 제어 품질 향상
- LinuxCNC와의 통신 거리 제한 없음 (LAN 케이블 범위 내)
WIZnet Makers 유사 사례
LinuxCNC + Ethernet + WIZnet 조합은 이미 maker.wiznet.io 생태계에서 여러 선행 사례로 검증된 패턴입니다.
Remora RPi/W5500 LinuxCNC Adapter Board: STM32 Blackpill + W5500을 사용한 LinuxCNC 전축 모션 제어 보드. Remora 프로토콜과 W5500 UDP 조합이 동일하며, 스핀들 PWM 1채널을 지원합니다. 본 프로젝트는 그 스핀들 채널을 전용 클로즈드루프 컨트롤러로 특화·심화한 형태입니다.
→ Remora RPi/W5500 LinuxCNC Adapter Board: https://maker.wiznet.io/louis_m/projects/remora-rpi-w5500-linuxcnc-adapter-board/
Real-Time CNC Control with Remora-Core: STM32 기반 Remora Core 펌웨어로 구성된 범용 CNC 플랫폼. W5500 Ethernet 확장이 분산 CNC 제어의 방향성으로 명시되어 있으며, 본 프로젝트는 그 방향성을 RP2040 + 스핀들 특화로 구현한 병렬 사례입니다.
→ Real-Time CNC Control with Remora-Core: https://maker.wiznet.io/josephsr/projects/real-time-cnc-control-with-remora-core-remora-cnc/
ESP32UDP: ESP32 + W5500으로 LinuxCNC에 최대 200kHz 다축 스텝 제너레이터를 제공하는 프로젝트. "MCU + W5500 + UDP + LinuxCNC" 패턴이 동일하며, 축 스텝 제너레이터와 스핀들 전용 PID 컨트롤러라는 역할 분리가 두 프로젝트를 상호 보완 관계로 만듭니다.
세 사례 모두 LinuxCNC 실시간 제어와 W5500 하드웨어 Ethernet의 조합을 채택한 것은, 소프트웨어 스택의 지터 문제를 W5500의 하드웨어 오프로딩으로 해소하는 것이 이 생태계에서 실질적 선택임을 보여줍니다.
비즈니스 가치
시장 배경: DIY CNC와 오픈소스의 교차점
데스크탑 CNC 시장은 2025년 기준 약 26억 달러 규모로, 2035년까지 CAGR 8%의 성장이 전망됩니다. 성장 동력으로 오픈소스 펌웨어(GRBL, LinuxCNC) 확산과 저가 하드웨어 조합이 명시적으로 언급됩니다. 이 흐름 속에서 SpindelController가 채운 공백은 구체적입니다. Siemens·FANUC 수준의 스핀들 위치 제어 기능을 수만 원 부품으로 DIY 선반에 이식하는 것이 가능해진다는 점에서, 기술적 가격 격차를 직접 공략합니다.
활용 시나리오
DIY 선반 리지드 태핑 추가: 리지드 태핑 기능이 없는 구형 수동 선반을 LinuxCNC로 레트로핏할 때, 이 컨트롤러를 스핀들 모듈로 추가하면 M19 오리엔테이션과 G84 탭 사이클을 활성화할 수 있습니다.
소형 CNC 밀링 스핀들 오리엔테이션: 공구 교환 시 스핀들을 특정 각도에 정지시켜야 하는 자동 공구 교환(ATC) 구성에서, M19를 처리할 수 있는 저비용 스핀들 컨트롤러 모듈로 활용 가능합니다.
교육·연구 환경: 산업용 CNC 시스템의 스핀들 클로즈드루프 제어 원리를 저비용으로 실습할 수 있는 교육용 플랫폼으로 적합합니다. RP2040의 낮은 진입 장벽과 Pico SDK의 풍부한 문서가 학습 곡선을 낮춥니다.
소규모 공방 레트로핏 모듈화: 복수의 구형 CNC 장비에 이 컨트롤러를 탑재해 LinuxCNC 네트워크로 통합하는 분산 제어 구성이 가능합니다. Ethernet 기반이기 때문에 배선 복잡도 없이 LAN 스위치 하나로 여러 축과 스핀들을 동일 네트워크에 연결할 수 있습니다.
WIZnet 관점에서의 인사이트
Remora 생태계에서 W5500 기반 Ethernet이 사실상 표준 통신 경로로 자리 잡고 있으며, 이 프로젝트는 그 패턴을 스핀들 전용 클로즈드루프 제어로 확장한 첫 번째 RP2040 기반 사례입니다. Remora + EC300/EC500 계열이 DIY 커뮤니티에서 상용 보드로 발전한 전례를 고려하면, 전용 스핀들 컨트롤러 모듈이 유사한 상용화 경로를 밟을 가능성이 있습니다. RP2040 + W5500 조합이 단순 IoT 센서 노드를 넘어 산업 수준 실시간 제어에서도 검증된 레퍼런스가 된다는 점이 WIZnet 생태계 관점의 핵심 인사이트입니다.
한계 및 개선 방향
현재 한계
Remora 인터페이스 미완성: remora_iface.c 소스 내에 "Platzhalter(플레이스홀더)" 주석이 명시되어 있어, 공식 Remora 프로토콜의 부분 구현 상태입니다. 전체 Remora 기능(예: 다축 피드백, 확장 상태 보고)과의 완전한 호환성은 추가 개발이 필요합니다.
UDP 패킷 유실 무방비: Remora 프로토콜은 UDP 기반이므로 패킷 유실 시 재전송 메커니즘이 없습니다. LinuxCNC 포럼에서는 네트워크 지터로 인한 joint following error가 빈번히 보고됩니다. 현재 구현은 수신 타임아웃 감지만 있고, 시퀀스 번호 기반 유실 추적은 없습니다.
단일 회전 절대 인코더: MT6835는 0°~360° 단일 회전 절대값만 제공합니다. 스핀들이 수 바퀴 이상 회전하는 나사 이송 구간에서 누적 위치 추적은 소프트웨어 카운터로 보완해야 하며, 전원 차단 시 다회전 정보는 소실됩니다.
디스플레이·ADC 기본 비활성화: UI 및 전류 모니터링 모듈이 기본 OFF 상태이므로, 현장 투입 전 별도 활성화와 검증이 필요합니다.
개선 방향
이 프로젝트가 기여한 클로즈드루프 스핀들 제어 구조는 탄탄합니다. 여기서 한 단계 더 나아가면 실전 투입 가능성이 높아집니다.
UDP 유실 대응으로는 Remora 패킷에 시퀀스 번호와 재전송 요청 플래그를 추가하거나, 단방향 커맨드 패킷 수신 타임아웃 시 안전 정지를 즉시 실행하는 폴백 로직을 강화하는 방향이 현실적입니다. 다회전 추적은 소프트웨어 카운터에 플래시 저장소(RP2040의 QSPI 플래시 2MB)를 활용한 전원 유지 위치 복원으로 개선할 수 있습니다. 장기적으로 디스플레이 모듈을 활성화해 스핀들 RPM·각도·상태를 현장에서 직접 확인하는 독립 운전 모드로 발전시키면, LinuxCNC 없이도 단독 스핀들 드라이버로 사용할 수 있는 제품성을 확보할 수 있습니다.
FAQ
Q. M19 스핀들 오리엔테이션을 사용하려면 어떤 조건이 필요한가요?
LinuxCNC 측에서 HAL 파일에 remora.spindle.control_mode를 위치 모드(1)로 설정하는 구성이 필요합니다. 펌웨어 측에서는 MT6835 인코더가 정상 동작 중이어야 하며, 스핀들 RPM이 POSITION_ENABLE_RPM_THRESHOLD(기본 4,500 RPM) 이하일 때만 위치 제어가 활성화됩니다. 고속 회전 중 M19를 요청하면 펌웨어가 자동으로 해당 요청을 무시하고 STATUS_BIT_POSITION_DISABLED 플래그로 상태를 LinuxCNC에 알립니다.
Q. W5500 없이 Wi-Fi 모듈로 대체할 수 있나요?
구조적으로 불가능하진 않지만 권장하지 않습니다. LinuxCNC의 실시간 서보 루프(통상 1ms 주기)는 패킷 지터가 수백 μs 이상 발생하면 joint following error로 중단됩니다. Wi-Fi는 채널 경합·재전송으로 인해 지터가 수 ms에 달할 수 있어, 실시간 CNC 제어에 적합하지 않습니다. W5500의 하드웨어 UDP 처리가 이 지터를 결정론적으로 낮추는 핵심 역할을 합니다.
Q. AS5600과 MT6835 중 어떤 인코더를 선택해야 하나요?
| 항목 | AS5600 | MT6835 |
|---|---|---|
| 해상도 | 12-bit (4,096 스텝/회전) | 21-bit (2,097,152 스텝/회전) |
| 인터페이스 | I2C | SPI (최대 16MHz) |
| 최대 RPM | ~3,000 RPM 권장 | 120,000 RPM |
| 위치 제어 정밀도 | 낮음 | 높음 (M19 필수) |
| 가격 | 저가 | 중가 |
스핀들 위치 제어(M19)나 리지드 태핑이 목적이라면 MT6835를 선택해야 합니다. AS5600은 단순 RPM 모니터링이나 저속 스핀들의 속도 제어 용도로는 충분합니다.
Q. LinuxCNC 없이 독립 운전(standalone)도 가능한가요?
현재 펌웨어는 LinuxCNC에서 Remora 커맨드 패킷을 수신하는 것을 전제로 설계되어 있습니다. W5500 연결이 없거나 HARDWARETEST_MODE=1로 설정하면 네트워크 없이도 부팅은 가능하지만, 속도·위치 설정점을 외부에서 받아야 하므로 실질적인 독립 운전은 별도 UI 개발이 필요합니다. config.h에 디스플레이·터치 모듈이 이미 설계되어 있어, 이를 활성화하면 독립 운전 가능한 구조로 발전시킬 수 있습니다.
Q. 리지드 태핑이란 무엇이고, 왜 스핀들 위치 제어가 필요한가요?
리지드 태핑(Rigid Tapping)은 밀링머신이나 선반에서 나사 탭을 가공할 때, 스핀들 회전과 Z축 이송을 완전히 동기화해 끊어지지 않고 나사산을 만드는 가공 방법입니다. 이 과정에서 탭이 구멍 바닥에 닿는 순간 스핀들이 정확히 역회전으로 전환되어야 하며, 이를 위해 스핀들의 실시간 각도 위치 피드백이 필수입니다. 위치 피드백 없이 단순 PWM 속도 제어만 가능한 스핀들로는 구현할 수 없으며, 산업용 CNC 컨트롤러가 고가인 이유 중 하나입니다.
Summary
SpindelController is a dedicated CNC spindle controller built on the Raspberry Pi RP2040 and the WIZnet W5500 Ethernet controller. It communicates with LinuxCNC over the Remora protocol via UDP and uses a 21-bit absolute magnetic encoder (MT6835) to implement speed control (M3) and position control (M19 rigid tapping) within a single firmware. Because W5500 handles the entire TCP/IP stack in hardware, the RP2040 can run a 10 kHz PID loop and 160 kHz encoder sampling without interference from a software network stack. The project is notable for bringing spindle orientation — a feature traditionally reserved for expensive industrial controllers — into the DIY domain with a handful of low-cost components.
Overview
Spindle control has long been the weak point in LinuxCNC-based DIY CNC builds. Typical Remora boards (EC300, EC500, etc.) are designed around axis step generators and handle the spindle with nothing more than a simple PWM output. That approach makes G-code M19 — spindle orientation — and rigid tapping impossible. Closed-loop spindle position control has historically been the domain of Siemens Sinumerik or FANUC series industrial controllers, costing tens of thousands of dollars.
SpindelController addresses this gap directly. It combines a Waveshare RP2040 Zero (or RP2040 Plus), a W5500 Ethernet controller, and an MT6835 21-bit magnetic encoder to receive Remora protocol commands over Ethernet from LinuxCNC and control the spindle in dual speed/position modes. The build environment is the Raspberry Pi Pico SDK with CMake and Ninja. The primary audience is makers running DIY lathes or milling machines who want to add rigid tapping, and LinuxCNC integration developers building modular CNC systems.
Architecture
The full data flow is as follows.
The Remora packet structure (64 bytes) carries the following fields.
[0..3]Header (REMORA_PRU_WRITE/REMORA_PRU_READ)[4..7]floatspeed_setpoint_rpm[8]uint8direction(0=CW, 1=CCW)[9]uint8brake_cmd[10]uint8enable[11]uint8control_mode(0=speed, 1=position)[12..15]floatposition_setpoint_deg
The feedback packet returns speed_measured_rpm and six status bits (status_bits) — covering E-Stop, overcurrent, overtemperature, watchdog, latched fault, and encoder fault — to LinuxCNC on every cycle.
Technology Background
Remora over Ethernet: LinuxCNC Real-Time Distributed Control
LinuxCNC is an open-source CNC control system that runs on Linux and handles G-code path planning through its HAL (Hardware Abstraction Layer). Traditionally, the host PC generated step pulses directly, but at high speeds or across many axes, real-time load on the PC degrades control quality. Remora is an open-source firmware framework that offloads real-time processing to an external MCU. The MCU receives Remora-format command packets from LinuxCNC, drives motors, encoders, and I/O directly, and returns feedback packets on every servo cycle.
Originally SPI or RS-485 based, the W5500 Ethernet variant separates host and controller over a LAN cable, simultaneously improving wiring flexibility and noise immunity. SpindelController implements this Ethernet variant on the RP2040. An M3 command becomes speed_setpoint_rpm; an M19 command becomes position_setpoint_deg with control_mode=1 — both serialized into a 64-byte UDP packet and sent to the controller.
→ Remora GitHub: https://github.com/scottalford75/Remora
W5500 Hardware TCP/IP Offloading
The W5500 is a hardwired TCP/IP controller developed by WIZnet, integrating MAC, PHY, and a TCP/IP socket engine on a single chip. The MCU communicates with W5500 over SPI and requires no software TCP/IP stack. In a CNC real-time control environment, this matters for one reason above all: jitter suppression. A software stack competes with the MCU's control loop for CPU cycles, making packet processing timing irregular. W5500 handles networking independently in hardware, leaving the control loop undisturbed.
In SpindelController, W5500 connects to the RP2040 via SPI at 62.5 MHz. Two RP2040 DMA channels (TX and RX) handle burst transfers, processing packets of 8 bytes or more without CPU intervention. The built-in DHCP client assigns an IP automatically, falling back to a static address after a 2-second timeout. If the PHY link drops, the driver retries initialization every 200 ms, ensuring reliable recovery regardless of power-on sequence.
→ W5500 overview: https://docs.wiznet.io/Product/iEthernet/W5500/overview
AMR Absolute Magnetic Encoder: MT6835
The MT6835 is MagnTek's fourth-generation magnetic angle encoder IC, based on Anisotropic Magnetoresistive (AMR) technology. Two pairs of AMR Wheatstone bridges on the chip surface detect the direction of a rotating magnetic field and output an absolute angle from 0° to 360°. Unlike optical encoders, it is resistant to dust, cutting fluid, and vibration, and its contactless design eliminates wear. At 21-bit resolution, the encoder delivers 2,097,152 steps per revolution — resolving 1° of spindle rotation to approximately 5,825 counts. Its maximum operating speed is 120,000 RPM, providing precise feedback even on high-speed machining spindles.
In SpindelController, the MT6835 connects to the RP2040 over a SPI interface (up to 16 MHz) and is sampled at 160 kHz. The absolute angle value feeds directly into the PID control loop, enabling M19 spindle orientation to stop within ±0.5° of the target angle (configurable deadband). Above 5,000 RPM, position mode is automatically disabled; below 4,500 RPM, it re-enables. This hysteresis logic, built into the firmware, prevents accidental entry into position control during high-speed operation.
→ MT6835 product page: https://www.avnet.com/apac/products/new-products/npi/aac-202509-novosense/
Technical Highlights
Dual control mode switching is the project's core differentiator. Speed mode (CONTROL_MODE_SPEED) receives an RPM target from LinuxCNC M3 and tracks it with PID. Position mode (CONTROL_MODE_POSITION) moves to a target angle in degrees via the shortest path, triggered by M19. Switching between modes requires only a single field change in the Remora packet, so LinuxCNC can alternate between them within a single machining cycle — exactly what threading and tapping require.
- PID control loop: default Kp=1.0, Ki=0.25, Kd=0.005, running at 10 kHz
- Motor PWM: 20 kHz carrier frequency with direction and brake control
- Ramp acceleration: up to 3,000 RPM/s to prevent mechanical shock on rapid speed changes
- RPM range: 0–12,000 RPM (adjustable in config.h)
The safety architecture operates in layers. A hardware watchdog cuts PWM output on any runtime exception. The E-Stop pin (GPIO 3) halts the motor immediately. The ACS712 current sensor is optional, but when active, it sends STATUS_BIT_OVERCURRENT to LinuxCNC via the Remora feedback frame, enabling upper-level interlocks in the HAL script. All six status bits — E-Stop, overcurrent, overtemperature, watchdog, latched fault, and encoder fault — are reported in a standardized bitmap, allowing direct condition handling in LinuxCNC HAL.
Modular design is also a strength. A single config.h file activates or deactivates the W5500, encoder, display, ADC, and WS2812 modules with a single flag (0 or 1). A five-stage HARDWARETEST_BRINGUP_STAGE variable supports incremental hardware bring-up, reducing debugging time during initial assembly.
Where WIZnet Fits
SpindelController actively uses the W5500, with a clearly defined role.
The problem with software Ethernet
If the RP2040 handled TCP/IP in software, network packet processing would compete with the 10 kHz PID loop for CPU cycles. Irregular packet timing interferes with the control loop period, causing joint following error on the LinuxCNC side and halting machine motion.
The W5500 integration
- Hardware TCP/IP offloading: W5500 independently manages DHCP, UDP sockets, and PHY link state
- SPI + DMA burst: two dedicated RP2040 DMA channels handle transfers of 8 bytes or more without CPU involvement
- Non-blocking polling receive:
remora_iface_poll()processes up to 4 packets per call and returns immediately when no data is available, adding zero latency to the control loop - Automatic recovery: if W5500 initialization fails or the PHY link drops, the driver retries every 200 ms
Expected benefits
- RP2040 cores dedicate full capacity to PID, encoder sampling, and PWM with no networking overhead
- Wired Ethernet delivers deterministically low jitter compared to Wi-Fi, directly improving control quality
- No cable-length restriction between LinuxCNC host and the spindle controller beyond standard LAN limits
Similar Projects on WIZnet Makers
The LinuxCNC + Ethernet + WIZnet combination is already a validated pattern across multiple projects in the maker.wiznet.io ecosystem.
Remora RPi/W5500 LinuxCNC Adapter Board: a LinuxCNC full-axis motion control board using STM32 Blackpill and W5500. It shares the identical Remora protocol and W5500 UDP combination and supports one spindle PWM channel. SpindelController takes that spindle channel and deepens it into a dedicated closed-loop controller.
→ Remora RPi/W5500 LinuxCNC Adapter Board: https://maker.wiznet.io/louis_m/projects/remora-rpi-w5500-linuxcnc-adapter-board/
Real-Time CNC Control with Remora-Core: a general-purpose CNC platform built on STM32 and the Remora Core firmware abstraction layer. Its documentation explicitly points to W5500 Ethernet extension as the direction for distributed CNC control — a direction SpindelController realizes on the RP2040 with spindle specialization.
→ Real-Time CNC Control with Remora-Core: https://maker.wiznet.io/josephsr/projects/real-time-cnc-control-with-remora-core-remora-cnc/
ESP32UDP: a project delivering up to 200 kHz multi-axis step generation for LinuxCNC via ESP32 and W5500. It shares the same "MCU + W5500 + UDP + LinuxCNC" pattern. The two projects are naturally complementary: ESP32UDP handles axis step generation while SpindelController manages spindle closed-loop control.
All three projects chose W5500-based Ethernet as their communication path. The consistent reasoning across the ecosystem — offloading TCP/IP to hardware to suppress jitter in real-time CNC loops — confirms that this is a practical, proven choice rather than an architectural preference.
Business Value
Market Context: Where DIY CNC and Open Source Converge
The desktop CNC machine market stood at approximately $2.56 billion in 2025 and is forecast to grow at a CAGR of 8% through 2035. Market research explicitly identifies open-source firmware ecosystems — GRBL, LinuxCNC — as a primary growth driver, alongside declining hardware costs. Within that context, SpindelController addresses a specific and tangible gap: it delivers spindle position control that previously required Siemens- or FANUC-class hardware, using components that cost a fraction of the price. That price-capability gap is the market opportunity.
Use Cases
Rigid tapping on a DIY lathe: when retrofitting an old manual lathe with LinuxCNC, adding this controller as a spindle module activates M19 orientation and G84 tapping cycles — features the original machine never had.
Spindle orientation for automatic tool change (ATC): machining centers that stop the spindle at a defined angle before a tool change need exactly this kind of closed-loop position control. SpindelController provides that capability at low cost.
Education and research: the project is well suited as a teaching platform for industrial spindle closed-loop control principles. The RP2040's low barrier to entry and the extensive Pico SDK documentation keep the learning curve manageable.
Multi-machine workshop integration: because the controller uses Ethernet, multiple spindle controllers can sit on the same LAN switch alongside other Remora-based axis boards, building a distributed CNC network without additional wiring complexity.
Insight for WIZnet
The Remora ecosystem is converging on W5500-based Ethernet as its de facto communication path. SpindelController is the first known RP2040-based implementation of that pattern applied to dedicated spindle closed-loop control. The Remora community has already seen DIY boards evolve into commercial products — the EC300 and EC500 are direct examples. A dedicated spindle controller module could follow the same trajectory. More broadly, this project demonstrates that the RP2040 + W5500 combination is viable not just for IoT sensor nodes but for industrial-grade real-time motion control — a meaningful reference point for the WIZnet ecosystem.
Limitations and Future Improvements
Current Limitations
Partial Remora implementation: the remora_iface.c source contains explicit "Platzhalter (placeholder)" comments, indicating that the Remora protocol support is not yet complete. Full compatibility with the upstream Remora feature set — multi-axis feedback, extended status reporting — requires additional development.
No UDP packet loss recovery: the Remora protocol runs over UDP with no retransmission mechanism. On the LinuxCNC forum, joint following error caused by network jitter is a frequently reported issue. The current implementation detects receive timeouts but has no sequence-number-based loss tracking.
Single-turn absolute encoder: the MT6835 provides absolute position within a single revolution (0°–360°). Multi-turn tracking during extended threading passes requires a software counter, and accumulated position is lost on power cycle.
Display and ADC disabled by default: the UI and current monitoring modules are off by default. Enabling them requires deliberate configuration and verification before field deployment.
Future Improvements
The closed-loop spindle control architecture this project establishes is solid. A few targeted additions would bring it closer to production readiness.
For UDP loss resilience, adding sequence numbers and a missed-packet counter to the Remora packet, combined with an immediate safe-stop fallback on receive timeout, would significantly reduce the risk of undetected communication failures. Multi-turn tracking can be improved by persisting the software revolution counter to the RP2040's onboard QSPI flash (2 MB), allowing position to survive a power cycle. Activating the display module to show spindle RPM, angle, and status locally would enable a standalone operating mode — letting the controller function as an independent spindle drive without a LinuxCNC host, which meaningfully expands the range of deployable scenarios.
FAQ
Q. What conditions are required to use M19 spindle orientation?
On the LinuxCNC side, the HAL file must configure remora.spindle.control_mode to position mode (1). On the firmware side, the MT6835 encoder must be operating correctly, and the spindle RPM must be below POSITION_ENABLE_RPM_THRESHOLD (default 4,500 RPM). If M19 is requested at high speed, the firmware silently ignores it and sets STATUS_BIT_POSITION_DISABLED in the feedback packet, informing LinuxCNC of the current state.
Q. Can a Wi-Fi module replace the W5500?
Structurally possible, but not recommended. LinuxCNC's real-time servo loop (typically 1 ms period) halts with a joint following error when packet jitter exceeds a few hundred microseconds. Wi-Fi jitter can reach several milliseconds due to channel contention and retransmission. W5500's hardware UDP processing keeps jitter deterministically low — which is precisely why it is the right choice for this application.
Q. Which encoder should I choose — AS5600 or MT6835?
| Item | AS5600 | MT6835 |
|---|---|---|
| Resolution | 12-bit (4,096 steps/rev) | 21-bit (2,097,152 steps/rev) |
| Interface | I2C | SPI (up to 16 MHz) |
| Max RPM | ~3,000 RPM recommended | 120,000 RPM |
| Position control accuracy | Low | High (required for M19) |
| Price | Lower | Moderate |
If spindle position control (M19) or rigid tapping is the goal, MT6835 is required. The AS5600 is adequate for simple RPM monitoring or speed control on low-speed spindles.
Q. Is standalone operation possible without LinuxCNC?
The current firmware assumes it will receive Remora command packets from a LinuxCNC host. Without a W5500 connection, or with HARDWARETEST_MODE=1, the firmware boots, but speed and position setpoints still need to come from an external source. True standalone operation requires a separate UI layer. The display and touch modules are already architected into config.h, so activating them provides a clear path to a self-contained spindle drive.
Q. What is rigid tapping, and why does it require spindle position control?
Rigid tapping is a machining operation that cuts internal threads by synchronizing spindle rotation and Z-axis feed precisely so the tap advances exactly one thread pitch per revolution. When the tap reaches the bottom of the hole, the spindle must reverse instantly and accurately. That reversal requires real-time angular position feedback from the spindle. Without closed-loop position control — relying only on PWM speed control — the spindle cannot reverse at the right moment, and the tap breaks. This is one of the primary reasons industrial CNC controllers carry a high price premium.
