From f3298ecffb03d671da0825eeddc4541a9c3de09a Mon Sep 17 00:00:00 2001 From: Samuel Sadok Date: Thu, 11 Aug 2022 16:24:43 +0200 Subject: [PATCH 01/32] trigger docs build --- docs/Makefile | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/Makefile b/docs/Makefile index d4bb2cbb9..2e7f1c67c 100644 --- a/docs/Makefile +++ b/docs/Makefile @@ -18,3 +18,4 @@ help: # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). %: Makefile @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) + \ No newline at end of file From 146b67fed3abe7a6e7171238a18bb7af56c286a3 Mon Sep 17 00:00:00 2001 From: Samuel Sadok Date: Thu, 11 Aug 2022 16:30:49 +0200 Subject: [PATCH 02/32] [docs] fix version indicator --- docs/conf.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/conf.py b/docs/conf.py index 7490c08d6..e6c3e2f22 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -79,5 +79,5 @@ 'https://docs.odriverobotics.com/docsInject.js' ] -version = "0.5.4" +version = "0.5.5" release = version From a308314ed2ca613164b81e7bbdfacc53cd1859ff Mon Sep 17 00:00:00 2001 From: Samuel Sadok Date: Tue, 2 May 2023 11:47:09 +0200 Subject: [PATCH 03/32] fix release action --- .github/actions/upload-release/action.yml | 9 +++++---- .github/workflows/firmware.yaml | 10 +++++++++- 2 files changed, 14 insertions(+), 5 deletions(-) diff --git a/.github/actions/upload-release/action.yml b/.github/actions/upload-release/action.yml index a84d306d1..3a32de321 100644 --- a/.github/actions/upload-release/action.yml +++ b/.github/actions/upload-release/action.yml @@ -23,8 +23,8 @@ inputs: odrive_api_key: description: 'Key to our release index server' required: true - product: - description: 'ODrive product name (for firmware releases only).' + board: + description: 'ODrive board version triplet ("PRODUCT_LINE.VERSION.VARIANT") (for firmware releases only).' required: false app: description: 'Firmware app name (default, bootloader) (for firmware releases only).' @@ -95,6 +95,7 @@ runs: shell: python run: | import asyncio + import re import sys import aiohttp @@ -115,8 +116,8 @@ runs: release_api = PrivateReleaseApi(api_client) qualifiers = {} - if '${{ inputs.product }}': - qualifiers['product'] = '${{ inputs.product }}' + if '${{ inputs.board }}': + qualifiers['board'] = tuple(int(i) for i in re.match(r'^([0-9]+)\.([0-9]+).([0-9]+)$', '${{ inputs.board }}').groups()) if '${{ inputs.app }}': qualifiers['app'] = '${{ inputs.app }}' if '${{ inputs.variant }}': diff --git a/.github/workflows/firmware.yaml b/.github/workflows/firmware.yaml index 90f3e4002..5f73efd65 100644 --- a/.github/workflows/firmware.yaml +++ b/.github/workflows/firmware.yaml @@ -147,6 +147,14 @@ jobs: mkdir ${{ github.workspace }}/out cp ${{ github.workspace }}/Firmware/build/ODriveFirmware.elf ${{ github.workspace }}/out/firmware.elf + - name: Parse and format matrix.board_version + if: ${{ matrix.os == 'ubuntu-latest' }} + id: format-board-version + run: | + formatted_version=$(echo "${{ matrix.board_version }}" | sed 's/v\([0-9]\+\)\.\([0-9]\+\)-\([0-9]\+\)V/\1.\2.\3/') + echo "Formatted board version: $formatted_version" + echo "::set-output name=formatted_board_version::$formatted_version" + - name: Upload firmware to ODrive release system if: ${{ steps.release-info.outputs.channel == 'master' && matrix.os == 'ubuntu-latest' && matrix.debug == false && (startsWith(matrix.board_version, 'v3.5-') || startsWith(matrix.board_version, 'v3.6-')) }} uses: ./.github/actions/upload-release @@ -157,7 +165,7 @@ jobs: do_access_key: ${{ secrets.DIGITALOCEAN_ACCESS_KEY }} do_secret_key: ${{ secrets.DIGITALOCEAN_SECRET_KEY }} odrive_api_key: ${{ secrets.ODRIVE_API_KEY }} - product: ODrive ${{ matrix.board_version }} + board: ${{ steps.format-board-version.outputs.formatted_board_version }} app: default variant: public From 58fdd3fdfdcaeff76547870f5e7acdf1673479e8 Mon Sep 17 00:00:00 2001 From: samuelsadok Date: Tue, 9 May 2023 12:18:21 +0200 Subject: [PATCH 04/32] Update CHANGELOG.md --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3bc5d741c..c3aad6087 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,5 @@ -## [0.5.6] - Unreleased +## [0.5.6] - 2023-04-29 ### Fixed From 6c3cefdeacce600ba4524f4adc5fd634c7bebd18 Mon Sep 17 00:00:00 2001 From: Samuel Sadok Date: Thu, 21 Mar 2024 12:42:00 +0100 Subject: [PATCH 05/32] add note about compatibility --- README.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/README.md b/README.md index 97b77abf4..17132726c 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,11 @@ +## Important Note + +The firmware in this repository is compatible with the ODrive v3.x (NRND) and is no longer under active development. + +Firmware for the new generation of ODrives ([ODrive Pro](https://odriverobotics.com/shop/odrive-pro), [S1](https://odriverobotics.com/shop/odrive-s1), [Micro](https://odriverobotics.com/shop/odrive-micro), etc.) is currently being actively maintained and developed, however its source code is currently not publicly available. Access may be available under NDA, please [reach out to us](mailto:info@odriverobotics.com) for inquiries. + +## Overview + ![ODrive Logo](https://static1.squarespace.com/static/58aff26de4fcb53b5efd2f02/t/59bf2a7959cc6872bd68be7e/1505700483663/Odrive+logo+plus+text+black.png?format=1000w) This project is all about accurately driving brushless motors, for cheap. The aim is to make it possible to use inexpensive brushless motors in high performance robotics projects, like [this](https://www.youtube.com/watch?v=WT4E5nb3KtY). From ca132888f1a3882be354d7289fae1417d2ebe041 Mon Sep 17 00:00:00 2001 From: Samuel Sadok Date: Wed, 2 Oct 2024 18:53:18 +0200 Subject: [PATCH 06/32] fix compile on GCC 12 --- Firmware/fibre-cpp/include/fibre/cpp_utils.hpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Firmware/fibre-cpp/include/fibre/cpp_utils.hpp b/Firmware/fibre-cpp/include/fibre/cpp_utils.hpp index 7472c2214..8d211a8fa 100644 --- a/Firmware/fibre-cpp/include/fibre/cpp_utils.hpp +++ b/Firmware/fibre-cpp/include/fibre/cpp_utils.hpp @@ -976,10 +976,12 @@ TRet* dynamic_get(size_t i, const std::tuple& t) { template -class simple_iterator : std::iterator { +class simple_iterator { TDereferenceable *container_; size_t i_; public: + using iterator_category = std::random_access_iterator_tag; + using value_type = TResult; using reference = TResult; explicit simple_iterator(TDereferenceable& container, size_t pos) : container_(&container), i_(pos) {} simple_iterator& operator++() { ++i_; return *this; } From f9b5419c820c6fb2f609322a5131cdf8c5f71657 Mon Sep 17 00:00:00 2001 From: Samuel Sadok Date: Wed, 2 Oct 2024 18:53:42 +0200 Subject: [PATCH 07/32] Remove unused buggy FreeRTOS functions --- .../FreeRTOS/Source/stream_buffer.c | 143 +----------------- 1 file changed, 4 insertions(+), 139 deletions(-) diff --git a/Firmware/ThirdParty/FreeRTOS/Source/stream_buffer.c b/Firmware/ThirdParty/FreeRTOS/Source/stream_buffer.c index 85519707b..3efe82ce0 100644 --- a/Firmware/ThirdParty/FreeRTOS/Source/stream_buffer.c +++ b/Firmware/ThirdParty/FreeRTOS/Source/stream_buffer.c @@ -214,146 +214,11 @@ static void prvInitialiseNewStreamBuffer( StreamBuffer_t * const pxStreamBuffer, /*-----------------------------------------------------------*/ -#if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) +// REMOVED IMPLEMENTATIONS OF xStreamBufferGenericCreate and xStreamBufferGenericCreateStatic. +// We're not using them but the implementation we were using contained a +// vulnerability (CVE-2021-31572) and got flagged by analysis tools. +// https://github.com/odriverobotics/ODrive/issues/751 - StreamBufferHandle_t xStreamBufferGenericCreate( size_t xBufferSizeBytes, size_t xTriggerLevelBytes, BaseType_t xIsMessageBuffer ) - { - uint8_t *pucAllocatedMemory; - uint8_t ucFlags; - - /* In case the stream buffer is going to be used as a message buffer - (that is, it will hold discrete messages with a little meta data that - says how big the next message is) check the buffer will be large enough - to hold at least one message. */ - if( xIsMessageBuffer == pdTRUE ) - { - /* Is a message buffer but not statically allocated. */ - ucFlags = sbFLAGS_IS_MESSAGE_BUFFER; - configASSERT( xBufferSizeBytes > sbBYTES_TO_STORE_MESSAGE_LENGTH ); - } - else - { - /* Not a message buffer and not statically allocated. */ - ucFlags = 0; - configASSERT( xBufferSizeBytes > 0 ); - } - configASSERT( xTriggerLevelBytes <= xBufferSizeBytes ); - - /* A trigger level of 0 would cause a waiting task to unblock even when - the buffer was empty. */ - if( xTriggerLevelBytes == ( size_t ) 0 ) - { - xTriggerLevelBytes = ( size_t ) 1; - } - - /* A stream buffer requires a StreamBuffer_t structure and a buffer. - Both are allocated in a single call to pvPortMalloc(). The - StreamBuffer_t structure is placed at the start of the allocated memory - and the buffer follows immediately after. The requested size is - incremented so the free space is returned as the user would expect - - this is a quirk of the implementation that means otherwise the free - space would be reported as one byte smaller than would be logically - expected. */ - xBufferSizeBytes++; - pucAllocatedMemory = ( uint8_t * ) pvPortMalloc( xBufferSizeBytes + sizeof( StreamBuffer_t ) ); /*lint !e9079 malloc() only returns void*. */ - - if( pucAllocatedMemory != NULL ) - { - prvInitialiseNewStreamBuffer( ( StreamBuffer_t * ) pucAllocatedMemory, /* Structure at the start of the allocated memory. */ /*lint !e9087 Safe cast as allocated memory is aligned. */ /*lint !e826 Area is not too small and alignment is guaranteed provided malloc() behaves as expected and returns aligned buffer. */ - pucAllocatedMemory + sizeof( StreamBuffer_t ), /* Storage area follows. */ /*lint !e9016 Indexing past structure valid for uint8_t pointer, also storage area has no alignment requirement. */ - xBufferSizeBytes, - xTriggerLevelBytes, - ucFlags ); - - traceSTREAM_BUFFER_CREATE( ( ( StreamBuffer_t * ) pucAllocatedMemory ), xIsMessageBuffer ); - } - else - { - traceSTREAM_BUFFER_CREATE_FAILED( xIsMessageBuffer ); - } - - return ( StreamBufferHandle_t ) pucAllocatedMemory; /*lint !e9087 !e826 Safe cast as allocated memory is aligned. */ - } - -#endif /* configSUPPORT_DYNAMIC_ALLOCATION */ -/*-----------------------------------------------------------*/ - -#if( configSUPPORT_STATIC_ALLOCATION == 1 ) - - StreamBufferHandle_t xStreamBufferGenericCreateStatic( size_t xBufferSizeBytes, - size_t xTriggerLevelBytes, - BaseType_t xIsMessageBuffer, - uint8_t * const pucStreamBufferStorageArea, - StaticStreamBuffer_t * const pxStaticStreamBuffer ) - { - StreamBuffer_t * const pxStreamBuffer = ( StreamBuffer_t * ) pxStaticStreamBuffer; /*lint !e740 !e9087 Safe cast as StaticStreamBuffer_t is opaque Streambuffer_t. */ - StreamBufferHandle_t xReturn; - uint8_t ucFlags; - - configASSERT( pucStreamBufferStorageArea ); - configASSERT( pxStaticStreamBuffer ); - configASSERT( xTriggerLevelBytes <= xBufferSizeBytes ); - - /* A trigger level of 0 would cause a waiting task to unblock even when - the buffer was empty. */ - if( xTriggerLevelBytes == ( size_t ) 0 ) - { - xTriggerLevelBytes = ( size_t ) 1; - } - - if( xIsMessageBuffer != pdFALSE ) - { - /* Statically allocated message buffer. */ - ucFlags = sbFLAGS_IS_MESSAGE_BUFFER | sbFLAGS_IS_STATICALLY_ALLOCATED; - } - else - { - /* Statically allocated stream buffer. */ - ucFlags = sbFLAGS_IS_STATICALLY_ALLOCATED; - } - - /* In case the stream buffer is going to be used as a message buffer - (that is, it will hold discrete messages with a little meta data that - says how big the next message is) check the buffer will be large enough - to hold at least one message. */ - configASSERT( xBufferSizeBytes > sbBYTES_TO_STORE_MESSAGE_LENGTH ); - - #if( configASSERT_DEFINED == 1 ) - { - /* Sanity check that the size of the structure used to declare a - variable of type StaticStreamBuffer_t equals the size of the real - message buffer structure. */ - volatile size_t xSize = sizeof( StaticStreamBuffer_t ); - configASSERT( xSize == sizeof( StreamBuffer_t ) ); - } /*lint !e529 xSize is referenced is configASSERT() is defined. */ - #endif /* configASSERT_DEFINED */ - - if( ( pucStreamBufferStorageArea != NULL ) && ( pxStaticStreamBuffer != NULL ) ) - { - prvInitialiseNewStreamBuffer( pxStreamBuffer, - pucStreamBufferStorageArea, - xBufferSizeBytes, - xTriggerLevelBytes, - ucFlags ); - - /* Remember this was statically allocated in case it is ever deleted - again. */ - pxStreamBuffer->ucFlags |= sbFLAGS_IS_STATICALLY_ALLOCATED; - - traceSTREAM_BUFFER_CREATE( pxStreamBuffer, xIsMessageBuffer ); - - xReturn = ( StreamBufferHandle_t ) pxStaticStreamBuffer; /*lint !e9087 Data hiding requires cast to opaque type. */ - } - else - { - xReturn = NULL; - traceSTREAM_BUFFER_CREATE_STATIC_FAILED( xReturn, xIsMessageBuffer ); - } - - return xReturn; - } - -#endif /* ( configSUPPORT_STATIC_ALLOCATION == 1 ) */ /*-----------------------------------------------------------*/ void vStreamBufferDelete( StreamBufferHandle_t xStreamBuffer ) From 3a2e4dd1bfbda9e4c534d5c7d8428a99c361e783 Mon Sep 17 00:00:00 2001 From: Samuel Sadok Date: Tue, 20 Jan 2026 11:54:32 +0100 Subject: [PATCH 08/32] update deprecated action dependencies --- .github/workflows/documentation.yml | 2 +- .github/workflows/firmware.yaml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/documentation.yml b/.github/workflows/documentation.yml index 5ff5da141..ba03f19b6 100644 --- a/.github/workflows/documentation.yml +++ b/.github/workflows/documentation.yml @@ -24,7 +24,7 @@ jobs: print("::set-output name=version::" + version) - name: Cache pip - uses: actions/cache@v2 + uses: actions/cache@v4 with: path: ~/.cache/pip key: ${{ runner.os }}-pip-sphinx-sphinx-tabs-sphinx-design-sphinx_copybutton-sphinx_panels-sphinx_rtd_theme diff --git a/.github/workflows/firmware.yaml b/.github/workflows/firmware.yaml index 5f73efd65..ae6bad918 100644 --- a/.github/workflows/firmware.yaml +++ b/.github/workflows/firmware.yaml @@ -84,7 +84,7 @@ jobs: - name: Cache chocolatey - uses: actions/cache@v2 + uses: actions/cache@v4 if: startsWith(matrix.os, 'windows-') with: path: C:\Users\runneradmin\AppData\Local\Temp\chocolatey\gcc-arm-embedded From c9d473b55358f91a9b40993ee738a8caf8c8c2b8 Mon Sep 17 00:00:00 2001 From: JIE Date: Sat, 4 Apr 2026 23:28:47 +0800 Subject: [PATCH 09/32] Trigger GitHub Actions CI build for v3.6-56V From f2d06650cbf414ea0d5dd14737e99dbef4a4f7c0 Mon Sep 17 00:00:00 2001 From: JIE Date: Sat, 4 Apr 2026 23:56:04 +0800 Subject: [PATCH 10/32] Add ci-v3.6-56V branch to workflow triggers --- .github/workflows/firmware.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/firmware.yaml b/.github/workflows/firmware.yaml index ae6bad918..e98977ae2 100644 --- a/.github/workflows/firmware.yaml +++ b/.github/workflows/firmware.yaml @@ -4,7 +4,7 @@ on: pull_request: branches: [master, devel] push: - branches: [master, devel] + branches: [master, devel, ci-v3.6-56V] tags: ['fw-v*'] jobs: From e1595dd62e87746796a2a74e19a4d87d41fa1f43 Mon Sep 17 00:00:00 2001 From: JIE Date: Sun, 5 Apr 2026 00:03:09 +0800 Subject: [PATCH 11/32] Fix deprecated upload-artifact action version --- .github/workflows/firmware.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/firmware.yaml b/.github/workflows/firmware.yaml index e98977ae2..812ab67c3 100644 --- a/.github/workflows/firmware.yaml +++ b/.github/workflows/firmware.yaml @@ -134,7 +134,7 @@ jobs: - name: Upload binary as artifact if: ${{ matrix.os == 'ubuntu-latest' && matrix.debug == false }} - uses: actions/upload-artifact@v2 + uses: actions/upload-artifact@v4 with: name: firmware-${{ matrix.board_version }} path: | From ffb07acd2b9454af93131dd92d1d42aad87ec24d Mon Sep 17 00:00:00 2001 From: JIE Date: Sun, 5 Apr 2026 00:06:56 +0800 Subject: [PATCH 12/32] Fix macOS pip install for externally managed Python environment --- .github/workflows/firmware.yaml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/firmware.yaml b/.github/workflows/firmware.yaml index 812ab67c3..be8a6641c 100644 --- a/.github/workflows/firmware.yaml +++ b/.github/workflows/firmware.yaml @@ -80,7 +80,8 @@ jobs: # See https://github.com/osxfuse/osxfuse/issues/801#issuecomment-833419942 brew install --cask macfuse brew install gromgit/fuse/tup-mac - pip3 install PyYAML Jinja2 jsonschema + python3 -m pip install --user PyYAML Jinja2 jsonschema + echo 'export PATH="$HOME/.local/bin:$PATH"' >> $GITHUB_ENV - name: Cache chocolatey From 5956e49a7e5ae803b8a2a8c9f29ef38c6e59ded1 Mon Sep 17 00:00:00 2001 From: JIE Date: Sun, 5 Apr 2026 00:12:26 +0800 Subject: [PATCH 13/32] Remove macOS matrix to avoid unsupported runner failure --- .github/workflows/firmware.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/firmware.yaml b/.github/workflows/firmware.yaml index be8a6641c..fc1fb34f3 100644 --- a/.github/workflows/firmware.yaml +++ b/.github/workflows/firmware.yaml @@ -12,7 +12,7 @@ jobs: strategy: fail-fast: false matrix: - os: [ubuntu-latest, windows-latest, macOS-latest] + os: [ubuntu-latest, windows-latest] board_version: [v3.6-56V] debug: [true] From 1744f2ec0968f81be9eafd07678c0584849bf26a Mon Sep 17 00:00:00 2001 From: dwj <2650303277@qq.com> Date: Mon, 6 Apr 2026 10:07:19 +0800 Subject: [PATCH 14/32] Fix: AS5048A SPI encoder communication issue - Reduce SPI clock rate from 5.25MHz to 2.625MHz (BAUDRATEPRESCALER_32) for better timing margin - Add byte-swapping fallback mechanism for robust endianness handling - Fixes ERROR_ABS_SPI_COM_FAIL (error 128) on v3.6 boards with AS5048A encoders Changes: - encoder.cpp L51: Lower SPI baudrate prescaler - encoder.cpp L571-589: Add auto byte-swap retry logic in abs_spi_cb() --- Firmware/MotorControl/encoder.cpp | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/Firmware/MotorControl/encoder.cpp b/Firmware/MotorControl/encoder.cpp index 73771c340..fdeab1d5d 100644 --- a/Firmware/MotorControl/encoder.cpp +++ b/Firmware/MotorControl/encoder.cpp @@ -46,7 +46,7 @@ void Encoder::setup() { .CLKPolarity = (mode_ == MODE_SPI_ABS_AEAT || mode_ == MODE_SPI_ABS_MA732) ? SPI_POLARITY_HIGH : SPI_POLARITY_LOW, .CLKPhase = SPI_PHASE_2EDGE, .NSS = SPI_NSS_SOFT, - .BaudRatePrescaler = SPI_BAUDRATEPRESCALER_16, + .BaudRatePrescaler = SPI_BAUDRATEPRESCALER_128, // 降低到 ~0.65MHz (从 ~5.25MHz) .FirstBit = SPI_FIRSTBIT_MSB, .TIMode = SPI_TIMODE_DISABLE, .CRCCalculation = SPI_CRCCALCULATION_DISABLE, @@ -569,11 +569,22 @@ void Encoder::abs_spi_cb(bool success) { switch (mode_) { case MODE_SPI_ABS_AMS: { uint16_t rawVal = abs_spi_dma_rx_[0]; - // check if parity is correct (even) and error flag clear - if (ams_parity(rawVal) || ((rawVal >> 14) & 1)) { + + // 尝试字节交换以修复SPI字节序问题 + // 如果当前字节序导致奇偶校验失败,则进行字节反转 + uint16_t rawValSwapped = ((rawVal & 0xFF) << 8) | ((rawVal >> 8) & 0xFF); + + // 优先使用原始值,如果失败则尝试字节交换的值 + if (!(ams_parity(rawVal) || ((rawVal >> 14) & 1))) { + // 原始值校验通过 + pos = rawVal & 0x3fff; + } else if (!(ams_parity(rawValSwapped) || ((rawValSwapped >> 14) & 1))) { + // 字节交换后的值校验通过 + pos = rawValSwapped & 0x3fff; + } else { + // 两个都不通过,当做错误处理 goto done; } - pos = rawVal & 0x3fff; } break; case MODE_SPI_ABS_CUI: { From 78035e40dcfd6a25b7d5886d19ff410d4da5b96e Mon Sep 17 00:00:00 2001 From: JIE Date: Mon, 6 Apr 2026 10:58:55 +0800 Subject: [PATCH 15/32] Fix: try alternate AMS SPI phase --- Firmware/MotorControl/encoder.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Firmware/MotorControl/encoder.cpp b/Firmware/MotorControl/encoder.cpp index fdeab1d5d..3179d7a41 100644 --- a/Firmware/MotorControl/encoder.cpp +++ b/Firmware/MotorControl/encoder.cpp @@ -44,7 +44,7 @@ void Encoder::setup() { .Direction = SPI_DIRECTION_2LINES, .DataSize = SPI_DATASIZE_16BIT, .CLKPolarity = (mode_ == MODE_SPI_ABS_AEAT || mode_ == MODE_SPI_ABS_MA732) ? SPI_POLARITY_HIGH : SPI_POLARITY_LOW, - .CLKPhase = SPI_PHASE_2EDGE, + .CLKPhase = (mode_ == MODE_SPI_ABS_AMS) ? SPI_PHASE_1EDGE : SPI_PHASE_2EDGE, .NSS = SPI_NSS_SOFT, .BaudRatePrescaler = SPI_BAUDRATEPRESCALER_128, // 降低到 ~0.65MHz (从 ~5.25MHz) .FirstBit = SPI_FIRSTBIT_MSB, From 1ad9c32e2a3fe19686f45ae511daccb387995992 Mon Sep 17 00:00:00 2001 From: JIE Date: Mon, 6 Apr 2026 11:13:25 +0800 Subject: [PATCH 16/32] Fix: add SPI CS setup delay --- Firmware/Drivers/STM32/stm32_spi_arbiter.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Firmware/Drivers/STM32/stm32_spi_arbiter.cpp b/Firmware/Drivers/STM32/stm32_spi_arbiter.cpp index a1565ef65..cbfd1918c 100644 --- a/Firmware/Drivers/STM32/stm32_spi_arbiter.cpp +++ b/Firmware/Drivers/STM32/stm32_spi_arbiter.cpp @@ -39,6 +39,10 @@ bool Stm32SpiArbiter::start() { __HAL_SPI_ENABLE(hspi_); } task.ncs_gpio.write(false); + // Give the slave a brief setup time before the first SPI clock edge. + for (volatile int i = 0; i < 64; ++i) { + __NOP(); + } HAL_StatusTypeDef status = HAL_ERROR; From 8c7d458f43e882c632bb4b2293e95d156823db4b Mon Sep 17 00:00:00 2001 From: JIE Date: Mon, 6 Apr 2026 11:39:24 +0800 Subject: [PATCH 17/32] Fix: reconstruct AMS parity bit --- Firmware/MotorControl/encoder.cpp | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/Firmware/MotorControl/encoder.cpp b/Firmware/MotorControl/encoder.cpp index 3179d7a41..1011862c5 100644 --- a/Firmware/MotorControl/encoder.cpp +++ b/Firmware/MotorControl/encoder.cpp @@ -569,6 +569,11 @@ void Encoder::abs_spi_cb(bool success) { switch (mode_) { case MODE_SPI_ABS_AMS: { uint16_t rawVal = abs_spi_dma_rx_[0]; + + // Some AS5048A setups appear to lose the first returned bit, which is + // the parity bit on AMS frames. Reconstruct it from the remaining bits + // before validating the frame. + rawVal = (rawVal & 0x7fff) | (ams_parity(rawVal) << 15); // 尝试字节交换以修复SPI字节序问题 // 如果当前字节序导致奇偶校验失败,则进行字节反转 From 8c95624ba299df1108e762d25d5ea3c06ef6784f Mon Sep 17 00:00:00 2001 From: JIE Date: Mon, 6 Apr 2026 11:47:15 +0800 Subject: [PATCH 18/32] Fix: poll AMS SPI in sampling IRQ --- Firmware/Drivers/STM32/stm32_spi_arbiter.cpp | 35 +++++++++++++++++++ Firmware/Drivers/STM32/stm32_spi_arbiter.hpp | 8 +++++ Firmware/MotorControl/encoder.cpp | 36 ++++++++++++++++---- Firmware/MotorControl/encoder.hpp | 2 ++ 4 files changed, 75 insertions(+), 6 deletions(-) diff --git a/Firmware/Drivers/STM32/stm32_spi_arbiter.cpp b/Firmware/Drivers/STM32/stm32_spi_arbiter.cpp index cbfd1918c..6f1b70cbc 100644 --- a/Firmware/Drivers/STM32/stm32_spi_arbiter.cpp +++ b/Firmware/Drivers/STM32/stm32_spi_arbiter.cpp @@ -111,6 +111,41 @@ bool Stm32SpiArbiter::transfer(SPI_InitTypeDef config, Stm32Gpio ncs_gpio, const return result; } +bool Stm32SpiArbiter::transfer_polled(SPI_InitTypeDef config, Stm32Gpio ncs_gpio, const uint8_t* tx_buf, uint8_t* rx_buf, size_t length, uint32_t timeout_ms) { + bool idle = false; + CRITICAL_SECTION() { + idle = (task_list_ == nullptr); + } + + if (!idle || (hspi_->State != HAL_SPI_STATE_READY)) { + return false; + } + + if (!equals(config, hspi_->Init)) { + HAL_SPI_DeInit(hspi_); + hspi_->Init = config; + HAL_SPI_Init(hspi_); + __HAL_SPI_ENABLE(hspi_); + } + + ncs_gpio.write(false); + for (volatile int i = 0; i < 64; ++i) { + __NOP(); + } + + HAL_StatusTypeDef status = HAL_ERROR; + if (tx_buf && rx_buf) { + status = HAL_SPI_TransmitReceive(hspi_, const_cast(tx_buf), rx_buf, length, timeout_ms); + } else if (tx_buf) { + status = HAL_SPI_Transmit(hspi_, const_cast(tx_buf), length, timeout_ms); + } else if (rx_buf) { + status = HAL_SPI_Receive(hspi_, rx_buf, length, timeout_ms); + } + + ncs_gpio.write(true); + return status == HAL_OK; +} + void Stm32SpiArbiter::on_complete() { if (!task_list_) { return; // this should not happen diff --git a/Firmware/Drivers/STM32/stm32_spi_arbiter.hpp b/Firmware/Drivers/STM32/stm32_spi_arbiter.hpp index d6883fc20..8a87e580d 100644 --- a/Firmware/Drivers/STM32/stm32_spi_arbiter.hpp +++ b/Firmware/Drivers/STM32/stm32_spi_arbiter.hpp @@ -84,6 +84,14 @@ class Stm32SpiArbiter { */ void on_complete(); + /** + * @brief Executes a blocking polled transfer without DMA. + * + * This is intended for short transfers from interrupt context where the + * caller needs the response before returning. + */ + bool transfer_polled(SPI_InitTypeDef config, Stm32Gpio ncs_gpio, const uint8_t* tx_buf, uint8_t* rx_buf, size_t length, uint32_t timeout_ms); + private: bool start(); diff --git a/Firmware/MotorControl/encoder.cpp b/Firmware/MotorControl/encoder.cpp index 1011862c5..ba0690142 100644 --- a/Firmware/MotorControl/encoder.cpp +++ b/Firmware/MotorControl/encoder.cpp @@ -490,6 +490,11 @@ void Encoder::sample_now() { } break; case MODE_SPI_ABS_AMS: + { + abs_spi_start_polled_transaction(); + // Do nothing + } break; + case MODE_SPI_ABS_CUI: case MODE_SPI_ABS_AEAT: case MODE_SPI_ABS_RLS: @@ -544,6 +549,21 @@ bool Encoder::abs_spi_start_transaction() { return true; } +bool Encoder::abs_spi_start_polled_transaction() { + if (!(mode_ & MODE_FLAG_ABS)) { + return false; + } + + return abs_spi_process_response( + spi_arbiter_->transfer_polled( + spi_task_.config, + abs_spi_cs_gpio_, + reinterpret_cast(abs_spi_dma_tx_), + reinterpret_cast(abs_spi_dma_rx_), + 1, + 1)); +} + uint8_t ams_parity(uint16_t v) { v ^= v >> 8; v ^= v >> 4; @@ -559,11 +579,11 @@ uint8_t cui_parity(uint16_t v) { return ~v & 3; } -void Encoder::abs_spi_cb(bool success) { +bool Encoder::abs_spi_process_response(bool success) { uint16_t pos; if (!success) { - goto done; + return false; } switch (mode_) { @@ -588,7 +608,7 @@ void Encoder::abs_spi_cb(bool success) { pos = rawValSwapped & 0x3fff; } else { // 两个都不通过,当做错误处理 - goto done; + return false; } } break; @@ -596,7 +616,7 @@ void Encoder::abs_spi_cb(bool success) { uint16_t rawVal = abs_spi_dma_rx_[0]; // check if parity is correct if (cui_parity(rawVal)) { - goto done; + return false; } pos = rawVal & 0x3fff; } break; @@ -613,7 +633,7 @@ void Encoder::abs_spi_cb(bool success) { default: { set_error(ERROR_UNSUPPORTED_ENCODER_MODE); - goto done; + return false; } break; } @@ -623,7 +643,11 @@ void Encoder::abs_spi_cb(bool success) { is_ready_ = true; } -done: + return true; +} + +void Encoder::abs_spi_cb(bool success) { + abs_spi_process_response(success); Stm32SpiArbiter::release_task(&spi_task_); } diff --git a/Firmware/MotorControl/encoder.hpp b/Firmware/MotorControl/encoder.hpp index d764582f2..e892f219b 100644 --- a/Firmware/MotorControl/encoder.hpp +++ b/Firmware/MotorControl/encoder.hpp @@ -134,6 +134,8 @@ class Encoder : public ODriveIntf::EncoderIntf { float sincos_sample_c_ = 0.0f; bool abs_spi_start_transaction(); + bool abs_spi_start_polled_transaction(); + bool abs_spi_process_response(bool success); void abs_spi_cb(bool success); void abs_spi_cs_pin_init(); bool abs_spi_pos_updated_ = false; From 9bcbdfd76026f33c08d57015330ff3c695dc0f1e Mon Sep 17 00:00:00 2001 From: JIE Date: Mon, 6 Apr 2026 11:52:38 +0800 Subject: [PATCH 19/32] Revert "Fix: poll AMS SPI in sampling IRQ" This reverts commit 8c95624ba299df1108e762d25d5ea3c06ef6784f. --- Firmware/Drivers/STM32/stm32_spi_arbiter.cpp | 35 ------------------- Firmware/Drivers/STM32/stm32_spi_arbiter.hpp | 8 ----- Firmware/MotorControl/encoder.cpp | 36 ++++---------------- Firmware/MotorControl/encoder.hpp | 2 -- 4 files changed, 6 insertions(+), 75 deletions(-) diff --git a/Firmware/Drivers/STM32/stm32_spi_arbiter.cpp b/Firmware/Drivers/STM32/stm32_spi_arbiter.cpp index 6f1b70cbc..cbfd1918c 100644 --- a/Firmware/Drivers/STM32/stm32_spi_arbiter.cpp +++ b/Firmware/Drivers/STM32/stm32_spi_arbiter.cpp @@ -111,41 +111,6 @@ bool Stm32SpiArbiter::transfer(SPI_InitTypeDef config, Stm32Gpio ncs_gpio, const return result; } -bool Stm32SpiArbiter::transfer_polled(SPI_InitTypeDef config, Stm32Gpio ncs_gpio, const uint8_t* tx_buf, uint8_t* rx_buf, size_t length, uint32_t timeout_ms) { - bool idle = false; - CRITICAL_SECTION() { - idle = (task_list_ == nullptr); - } - - if (!idle || (hspi_->State != HAL_SPI_STATE_READY)) { - return false; - } - - if (!equals(config, hspi_->Init)) { - HAL_SPI_DeInit(hspi_); - hspi_->Init = config; - HAL_SPI_Init(hspi_); - __HAL_SPI_ENABLE(hspi_); - } - - ncs_gpio.write(false); - for (volatile int i = 0; i < 64; ++i) { - __NOP(); - } - - HAL_StatusTypeDef status = HAL_ERROR; - if (tx_buf && rx_buf) { - status = HAL_SPI_TransmitReceive(hspi_, const_cast(tx_buf), rx_buf, length, timeout_ms); - } else if (tx_buf) { - status = HAL_SPI_Transmit(hspi_, const_cast(tx_buf), length, timeout_ms); - } else if (rx_buf) { - status = HAL_SPI_Receive(hspi_, rx_buf, length, timeout_ms); - } - - ncs_gpio.write(true); - return status == HAL_OK; -} - void Stm32SpiArbiter::on_complete() { if (!task_list_) { return; // this should not happen diff --git a/Firmware/Drivers/STM32/stm32_spi_arbiter.hpp b/Firmware/Drivers/STM32/stm32_spi_arbiter.hpp index 8a87e580d..d6883fc20 100644 --- a/Firmware/Drivers/STM32/stm32_spi_arbiter.hpp +++ b/Firmware/Drivers/STM32/stm32_spi_arbiter.hpp @@ -84,14 +84,6 @@ class Stm32SpiArbiter { */ void on_complete(); - /** - * @brief Executes a blocking polled transfer without DMA. - * - * This is intended for short transfers from interrupt context where the - * caller needs the response before returning. - */ - bool transfer_polled(SPI_InitTypeDef config, Stm32Gpio ncs_gpio, const uint8_t* tx_buf, uint8_t* rx_buf, size_t length, uint32_t timeout_ms); - private: bool start(); diff --git a/Firmware/MotorControl/encoder.cpp b/Firmware/MotorControl/encoder.cpp index ba0690142..1011862c5 100644 --- a/Firmware/MotorControl/encoder.cpp +++ b/Firmware/MotorControl/encoder.cpp @@ -490,11 +490,6 @@ void Encoder::sample_now() { } break; case MODE_SPI_ABS_AMS: - { - abs_spi_start_polled_transaction(); - // Do nothing - } break; - case MODE_SPI_ABS_CUI: case MODE_SPI_ABS_AEAT: case MODE_SPI_ABS_RLS: @@ -549,21 +544,6 @@ bool Encoder::abs_spi_start_transaction() { return true; } -bool Encoder::abs_spi_start_polled_transaction() { - if (!(mode_ & MODE_FLAG_ABS)) { - return false; - } - - return abs_spi_process_response( - spi_arbiter_->transfer_polled( - spi_task_.config, - abs_spi_cs_gpio_, - reinterpret_cast(abs_spi_dma_tx_), - reinterpret_cast(abs_spi_dma_rx_), - 1, - 1)); -} - uint8_t ams_parity(uint16_t v) { v ^= v >> 8; v ^= v >> 4; @@ -579,11 +559,11 @@ uint8_t cui_parity(uint16_t v) { return ~v & 3; } -bool Encoder::abs_spi_process_response(bool success) { +void Encoder::abs_spi_cb(bool success) { uint16_t pos; if (!success) { - return false; + goto done; } switch (mode_) { @@ -608,7 +588,7 @@ bool Encoder::abs_spi_process_response(bool success) { pos = rawValSwapped & 0x3fff; } else { // 两个都不通过,当做错误处理 - return false; + goto done; } } break; @@ -616,7 +596,7 @@ bool Encoder::abs_spi_process_response(bool success) { uint16_t rawVal = abs_spi_dma_rx_[0]; // check if parity is correct if (cui_parity(rawVal)) { - return false; + goto done; } pos = rawVal & 0x3fff; } break; @@ -633,7 +613,7 @@ bool Encoder::abs_spi_process_response(bool success) { default: { set_error(ERROR_UNSUPPORTED_ENCODER_MODE); - return false; + goto done; } break; } @@ -643,11 +623,7 @@ bool Encoder::abs_spi_process_response(bool success) { is_ready_ = true; } - return true; -} - -void Encoder::abs_spi_cb(bool success) { - abs_spi_process_response(success); +done: Stm32SpiArbiter::release_task(&spi_task_); } diff --git a/Firmware/MotorControl/encoder.hpp b/Firmware/MotorControl/encoder.hpp index e892f219b..d764582f2 100644 --- a/Firmware/MotorControl/encoder.hpp +++ b/Firmware/MotorControl/encoder.hpp @@ -134,8 +134,6 @@ class Encoder : public ODriveIntf::EncoderIntf { float sincos_sample_c_ = 0.0f; bool abs_spi_start_transaction(); - bool abs_spi_start_polled_transaction(); - bool abs_spi_process_response(bool success); void abs_spi_cb(bool success); void abs_spi_cs_pin_init(); bool abs_spi_pos_updated_ = false; From 87dce31811350a8acc49d14b1dd5a7505928f1db Mon Sep 17 00:00:00 2001 From: JIE Date: Mon, 6 Apr 2026 13:20:49 +0800 Subject: [PATCH 20/32] Fix: ignore in-flight AMS SPI transactions --- Firmware/MotorControl/encoder.cpp | 16 +++++++++++----- Firmware/MotorControl/encoder.hpp | 1 + 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/Firmware/MotorControl/encoder.cpp b/Firmware/MotorControl/encoder.cpp index 1011862c5..042d8e2ce 100644 --- a/Firmware/MotorControl/encoder.cpp +++ b/Firmware/MotorControl/encoder.cpp @@ -535,6 +535,7 @@ bool Encoder::abs_spi_start_transaction() { spi_task_.on_complete = [](void* ctx, bool success) { ((Encoder*)ctx)->abs_spi_cb(success); }; spi_task_.on_complete_ctx = this; spi_task_.next = nullptr; + abs_spi_transaction_pending_ = true; spi_arbiter_->transfer_async(&spi_task_); } else { @@ -562,6 +563,8 @@ uint8_t cui_parity(uint16_t v) { void Encoder::abs_spi_cb(bool success) { uint16_t pos; + abs_spi_transaction_pending_ = false; + if (!success) { goto done; } @@ -750,11 +753,14 @@ bool Encoder::update() { case MODE_SPI_ABS_AEAT: case MODE_SPI_ABS_MA732: { if (abs_spi_pos_updated_ == false) { - // Low pass filter the error - spi_error_rate_ += current_meas_period * (1.0f - spi_error_rate_); - if (spi_error_rate_ > 0.05f) { - set_error(ERROR_ABS_SPI_COM_FAIL); - return false; + // Don't count a transfer as failed while its DMA transaction is still in flight. + if (!abs_spi_transaction_pending_) { + // Low pass filter the error + spi_error_rate_ += current_meas_period * (1.0f - spi_error_rate_); + if (spi_error_rate_ > 0.05f) { + set_error(ERROR_ABS_SPI_COM_FAIL); + return false; + } } } else { // Low pass filter the error diff --git a/Firmware/MotorControl/encoder.hpp b/Firmware/MotorControl/encoder.hpp index d764582f2..a5b12e601 100644 --- a/Firmware/MotorControl/encoder.hpp +++ b/Firmware/MotorControl/encoder.hpp @@ -137,6 +137,7 @@ class Encoder : public ODriveIntf::EncoderIntf { void abs_spi_cb(bool success); void abs_spi_cs_pin_init(); bool abs_spi_pos_updated_ = false; + bool abs_spi_transaction_pending_ = false; Mode mode_ = MODE_INCREMENTAL; Stm32Gpio abs_spi_cs_gpio_; uint32_t abs_spi_cr1; From 00ec4bfb3e3a83dccc56d1c94c612ad5c053562f Mon Sep 17 00:00:00 2001 From: JIE Date: Thu, 16 Apr 2026 00:13:18 +0800 Subject: [PATCH 21/32] Fix AS5048A SPI mode and frame parsing --- Firmware/MotorControl/encoder.cpp | 25 ++++--------------------- 1 file changed, 4 insertions(+), 21 deletions(-) diff --git a/Firmware/MotorControl/encoder.cpp b/Firmware/MotorControl/encoder.cpp index 042d8e2ce..0e05d0b91 100644 --- a/Firmware/MotorControl/encoder.cpp +++ b/Firmware/MotorControl/encoder.cpp @@ -44,9 +44,9 @@ void Encoder::setup() { .Direction = SPI_DIRECTION_2LINES, .DataSize = SPI_DATASIZE_16BIT, .CLKPolarity = (mode_ == MODE_SPI_ABS_AEAT || mode_ == MODE_SPI_ABS_MA732) ? SPI_POLARITY_HIGH : SPI_POLARITY_LOW, - .CLKPhase = (mode_ == MODE_SPI_ABS_AMS) ? SPI_PHASE_1EDGE : SPI_PHASE_2EDGE, + .CLKPhase = SPI_PHASE_2EDGE, .NSS = SPI_NSS_SOFT, - .BaudRatePrescaler = SPI_BAUDRATEPRESCALER_128, // 降低到 ~0.65MHz (从 ~5.25MHz) + .BaudRatePrescaler = SPI_BAUDRATEPRESCALER_32, .FirstBit = SPI_FIRSTBIT_MSB, .TIMode = SPI_TIMODE_DISABLE, .CRCCalculation = SPI_CRCCALCULATION_DISABLE, @@ -572,27 +572,10 @@ void Encoder::abs_spi_cb(bool success) { switch (mode_) { case MODE_SPI_ABS_AMS: { uint16_t rawVal = abs_spi_dma_rx_[0]; - - // Some AS5048A setups appear to lose the first returned bit, which is - // the parity bit on AMS frames. Reconstruct it from the remaining bits - // before validating the frame. - rawVal = (rawVal & 0x7fff) | (ams_parity(rawVal) << 15); - - // 尝试字节交换以修复SPI字节序问题 - // 如果当前字节序导致奇偶校验失败,则进行字节反转 - uint16_t rawValSwapped = ((rawVal & 0xFF) << 8) | ((rawVal >> 8) & 0xFF); - - // 优先使用原始值,如果失败则尝试字节交换的值 - if (!(ams_parity(rawVal) || ((rawVal >> 14) & 1))) { - // 原始值校验通过 - pos = rawVal & 0x3fff; - } else if (!(ams_parity(rawValSwapped) || ((rawValSwapped >> 14) & 1))) { - // 字节交换后的值校验通过 - pos = rawValSwapped & 0x3fff; - } else { - // 两个都不通过,当做错误处理 + if (ams_parity(rawVal) || ((rawVal >> 14) & 1)) { goto done; } + pos = rawVal & 0x3fff; } break; case MODE_SPI_ABS_CUI: { From 963771a5dcb2fd9c934b0a42af9ed2337d8f579c Mon Sep 17 00:00:00 2001 From: JIE Date: Thu, 16 Apr 2026 00:20:51 +0800 Subject: [PATCH 22/32] Tune AS5048A SPI fallback parsing --- Firmware/MotorControl/encoder.cpp | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/Firmware/MotorControl/encoder.cpp b/Firmware/MotorControl/encoder.cpp index 0e05d0b91..31359c03f 100644 --- a/Firmware/MotorControl/encoder.cpp +++ b/Firmware/MotorControl/encoder.cpp @@ -44,9 +44,9 @@ void Encoder::setup() { .Direction = SPI_DIRECTION_2LINES, .DataSize = SPI_DATASIZE_16BIT, .CLKPolarity = (mode_ == MODE_SPI_ABS_AEAT || mode_ == MODE_SPI_ABS_MA732) ? SPI_POLARITY_HIGH : SPI_POLARITY_LOW, - .CLKPhase = SPI_PHASE_2EDGE, + .CLKPhase = (mode_ == MODE_SPI_ABS_AMS) ? SPI_PHASE_1EDGE : SPI_PHASE_2EDGE, .NSS = SPI_NSS_SOFT, - .BaudRatePrescaler = SPI_BAUDRATEPRESCALER_32, + .BaudRatePrescaler = SPI_BAUDRATEPRESCALER_128, .FirstBit = SPI_FIRSTBIT_MSB, .TIMode = SPI_TIMODE_DISABLE, .CRCCalculation = SPI_CRCCALCULATION_DISABLE, @@ -572,10 +572,16 @@ void Encoder::abs_spi_cb(bool success) { switch (mode_) { case MODE_SPI_ABS_AMS: { uint16_t rawVal = abs_spi_dma_rx_[0]; - if (ams_parity(rawVal) || ((rawVal >> 14) & 1)) { + + uint16_t rawValSwapped = ((rawVal & 0xFF) << 8) | ((rawVal >> 8) & 0xFF); + + if (!(ams_parity(rawVal) || ((rawVal >> 14) & 1))) { + pos = rawVal & 0x3fff; + } else if (!(ams_parity(rawValSwapped) || ((rawValSwapped >> 14) & 1))) { + pos = rawValSwapped & 0x3fff; + } else { goto done; } - pos = rawVal & 0x3fff; } break; case MODE_SPI_ABS_CUI: { From b828c757ceace805c666f7811d8e982b6292de6b Mon Sep 17 00:00:00 2001 From: JIE Date: Thu, 16 Apr 2026 00:42:17 +0800 Subject: [PATCH 23/32] Try shifted-frame recovery for AS5048A --- Firmware/MotorControl/encoder.cpp | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/Firmware/MotorControl/encoder.cpp b/Firmware/MotorControl/encoder.cpp index 31359c03f..0575fe44e 100644 --- a/Firmware/MotorControl/encoder.cpp +++ b/Firmware/MotorControl/encoder.cpp @@ -572,10 +572,21 @@ void Encoder::abs_spi_cb(bool success) { switch (mode_) { case MODE_SPI_ABS_AMS: { uint16_t rawVal = abs_spi_dma_rx_[0]; - uint16_t rawValSwapped = ((rawVal & 0xFF) << 8) | ((rawVal >> 8) & 0xFF); - if (!(ams_parity(rawVal) || ((rawVal >> 14) & 1))) { + // Some AS5048A setups appear to miss the first returned bit. + // Rebuild candidate frames by shifting right and recomputing parity. + uint16_t rawValShifted = rawVal >> 1; + rawValShifted = (rawValShifted & 0x7fff) | (ams_parity(rawValShifted) << 15); + + uint16_t rawValSwappedShifted = rawValSwapped >> 1; + rawValSwappedShifted = (rawValSwappedShifted & 0x7fff) | (ams_parity(rawValSwappedShifted) << 15); + + if (!(ams_parity(rawValShifted) || ((rawValShifted >> 14) & 1))) { + pos = rawValShifted & 0x3fff; + } else if (!(ams_parity(rawValSwappedShifted) || ((rawValSwappedShifted >> 14) & 1))) { + pos = rawValSwappedShifted & 0x3fff; + } else if (!(ams_parity(rawVal) || ((rawVal >> 14) & 1))) { pos = rawVal & 0x3fff; } else if (!(ams_parity(rawValSwapped) || ((rawValSwapped >> 14) & 1))) { pos = rawValSwapped & 0x3fff; From 096ad12619704b0bac03e62f708ef3951def25a9 Mon Sep 17 00:00:00 2001 From: JIE Date: Sun, 18 Oct 2026 21:50:40 +0800 Subject: [PATCH 24/32] Fix AS5048A frame corruption: SPI mode 1 and strict parity check The AMS branch had drifted into accepting shifted/byte-swapped frames whose parity bit was recomputed before checking, so the check always passed and garbage frames were published as pos_abs (it jittered between values while the rotor was standing still). Root cause of the original parity failures was the SPI phase: AS5048A is a mode 1 device (CPOL=0, CPHA=1). The AMS configuration used 1EDGE, which samples one bit too early, shifts the whole 16-bit frame by one bit and breaks parity on nearly every transfer. - CLKPhase: always 2EDGE (mode 1 for AMS, mode 3 for AEAT/MA732) - AMS: strict even-parity + error-flag check, remove shift/swap/parity hacks - Keep the in-flight DMA transaction fix (abs_spi_transaction_pending_) - SPI clock: 2.6MHz (prescaler 32) for signal margin --- Firmware/MotorControl/encoder.cpp | 30 +++++++++--------------------- 1 file changed, 9 insertions(+), 21 deletions(-) diff --git a/Firmware/MotorControl/encoder.cpp b/Firmware/MotorControl/encoder.cpp index 0575fe44e..a9c80b538 100644 --- a/Firmware/MotorControl/encoder.cpp +++ b/Firmware/MotorControl/encoder.cpp @@ -43,10 +43,14 @@ void Encoder::setup() { .Mode = SPI_MODE_MASTER, .Direction = SPI_DIRECTION_2LINES, .DataSize = SPI_DATASIZE_16BIT, + // AS5048A (AMS) is an SPI mode 1 device: CPOL=0 (idle low), CPHA=1 (sample on 2nd edge). + // Using 1EDGE here samples one bit too early, which shifts the whole frame and + // makes the parity check fail on almost every transfer. .CLKPolarity = (mode_ == MODE_SPI_ABS_AEAT || mode_ == MODE_SPI_ABS_MA732) ? SPI_POLARITY_HIGH : SPI_POLARITY_LOW, - .CLKPhase = (mode_ == MODE_SPI_ABS_AMS) ? SPI_PHASE_1EDGE : SPI_PHASE_2EDGE, + .CLKPhase = SPI_PHASE_2EDGE, .NSS = SPI_NSS_SOFT, - .BaudRatePrescaler = SPI_BAUDRATEPRESCALER_128, + // ~2.6MHz (@168MHz APB2): well inside the AS5048A 10MHz limit with margin for wiring. + .BaudRatePrescaler = SPI_BAUDRATEPRESCALER_32, .FirstBit = SPI_FIRSTBIT_MSB, .TIMode = SPI_TIMODE_DISABLE, .CRCCalculation = SPI_CRCCALCULATION_DISABLE, @@ -572,27 +576,11 @@ void Encoder::abs_spi_cb(bool success) { switch (mode_) { case MODE_SPI_ABS_AMS: { uint16_t rawVal = abs_spi_dma_rx_[0]; - uint16_t rawValSwapped = ((rawVal & 0xFF) << 8) | ((rawVal >> 8) & 0xFF); - - // Some AS5048A setups appear to miss the first returned bit. - // Rebuild candidate frames by shifting right and recomputing parity. - uint16_t rawValShifted = rawVal >> 1; - rawValShifted = (rawValShifted & 0x7fff) | (ams_parity(rawValShifted) << 15); - - uint16_t rawValSwappedShifted = rawValSwapped >> 1; - rawValSwappedShifted = (rawValSwappedShifted & 0x7fff) | (ams_parity(rawValSwappedShifted) << 15); - - if (!(ams_parity(rawValShifted) || ((rawValShifted >> 14) & 1))) { - pos = rawValShifted & 0x3fff; - } else if (!(ams_parity(rawValSwappedShifted) || ((rawValSwappedShifted >> 14) & 1))) { - pos = rawValSwappedShifted & 0x3fff; - } else if (!(ams_parity(rawVal) || ((rawVal >> 14) & 1))) { - pos = rawVal & 0x3fff; - } else if (!(ams_parity(rawValSwapped) || ((rawValSwapped >> 14) & 1))) { - pos = rawValSwapped & 0x3fff; - } else { + // check if parity is correct (even) and error flag clear + if (ams_parity(rawVal) || ((rawVal >> 14) & 1)) { goto done; } + pos = rawVal & 0x3fff; } break; case MODE_SPI_ABS_CUI: { From b7b47562283c9c066879d2eaa061de5cab8a1297 Mon Sep 17 00:00:00 2001 From: JIE Date: Sun, 18 Oct 2026 22:11:45 +0800 Subject: [PATCH 25/32] Add temporary AS5048A SPI frame diagnostics With the corrected SPI mode 1 timing every frame now fails the parity check, so there is no way to tell from pos_abs alone whether the frames are shifted, byte-swapped or just noise. Record the last 8 raw 16-bit frames plus counters for completed/parity-failing/flag-failing/accepted frames and expose them as read-only endpoints (dbg_raw0..7, dbg_total, dbg_parity_fail, dbg_flag_fail, dbg_ok, dbg_pos). To be removed once the encoder is confirmed working. --- Firmware/MotorControl/encoder.cpp | 17 ++++++++++++++++- Firmware/MotorControl/encoder.hpp | 8 ++++++++ Firmware/odrive-interface.yaml | 14 ++++++++++++++ 3 files changed, 38 insertions(+), 1 deletion(-) diff --git a/Firmware/MotorControl/encoder.cpp b/Firmware/MotorControl/encoder.cpp index a9c80b538..2123338fc 100644 --- a/Firmware/MotorControl/encoder.cpp +++ b/Firmware/MotorControl/encoder.cpp @@ -576,10 +576,25 @@ void Encoder::abs_spi_cb(bool success) { switch (mode_) { case MODE_SPI_ABS_AMS: { uint16_t rawVal = abs_spi_dma_rx_[0]; + + // --- temporary bring-up diagnostics --- + for (int i = 7; i > 0; --i) { + dbg_raw_[i] = dbg_raw_[i - 1]; + } + dbg_raw_[0] = rawVal; + dbg_total_++; + // check if parity is correct (even) and error flag clear - if (ams_parity(rawVal) || ((rawVal >> 14) & 1)) { + if (ams_parity(rawVal)) { + dbg_parity_fail_++; + goto done; + } + if ((rawVal >> 14) & 1) { + dbg_flag_fail_++; goto done; } + dbg_ok_++; + dbg_pos_ = (float)(rawVal & 0x3fff); pos = rawVal & 0x3fff; } break; diff --git a/Firmware/MotorControl/encoder.hpp b/Firmware/MotorControl/encoder.hpp index a5b12e601..ecee44114 100644 --- a/Firmware/MotorControl/encoder.hpp +++ b/Firmware/MotorControl/encoder.hpp @@ -146,6 +146,14 @@ class Encoder : public ODriveIntf::EncoderIntf { uint16_t abs_spi_dma_rx_[1]; Stm32SpiArbiter::SpiTask spi_task_; + // --- temporary AS5048A bring-up diagnostics --- + uint16_t dbg_raw_[8] = {0}; // last 8 raw frames, dbg_raw_[0] = newest + uint32_t dbg_total_ = 0; // completed SPI transactions + uint32_t dbg_parity_fail_ = 0; + uint32_t dbg_flag_fail_ = 0; + uint32_t dbg_ok_ = 0; + float dbg_pos_ = 0.0f; // last accepted position + constexpr float getCoggingRatio(){ return 1.0f / 3600.0f; } diff --git a/Firmware/odrive-interface.yaml b/Firmware/odrive-interface.yaml index 34cb09d06..d6d1d96de 100644 --- a/Firmware/odrive-interface.yaml +++ b/Firmware/odrive-interface.yaml @@ -1295,6 +1295,20 @@ interfaces: type: int32 doc: The last (valid) position from an absolute encoder, if used. spi_error_rate: readonly float32 + # --- temporary AS5048A bring-up diagnostics --- + dbg_raw0: {type: readonly uint16, c_getter: "dbg_raw_[0]"} + dbg_raw1: {type: readonly uint16, c_getter: "dbg_raw_[1]"} + dbg_raw2: {type: readonly uint16, c_getter: "dbg_raw_[2]"} + dbg_raw3: {type: readonly uint16, c_getter: "dbg_raw_[3]"} + dbg_raw4: {type: readonly uint16, c_getter: "dbg_raw_[4]"} + dbg_raw5: {type: readonly uint16, c_getter: "dbg_raw_[5]"} + dbg_raw6: {type: readonly uint16, c_getter: "dbg_raw_[6]"} + dbg_raw7: {type: readonly uint16, c_getter: "dbg_raw_[7]"} + dbg_total: {type: readonly uint32, c_getter: dbg_total_} + dbg_parity_fail: {type: readonly uint32, c_getter: dbg_parity_fail_} + dbg_flag_fail: {type: readonly uint32, c_getter: dbg_flag_fail_} + dbg_ok: {type: readonly uint32, c_getter: dbg_ok_} + dbg_pos: {type: readonly float32, c_getter: dbg_pos_} config: c_is_class: False attributes: From 4b34d02c3bad82d5c9220f425c27ef5d9c97b346 Mon Sep 17 00:00:00 2001 From: JIE Date: Sun, 18 Oct 2026 22:17:17 +0800 Subject: [PATCH 26/32] Diagnose AS5048A error flag: read magnitude and AGC registers The captured frames are perfectly aligned (even parity holds on 139830 of 139832 frames, two adjacent position codes) but bit14, the AS5048A error flag, is set on every frame, so the firmware discards all of them. Probe the MAGNITUDE (0x7FFE) and DIAG/AGC (0x7FFD) registers every 64th transaction and expose them as dbg_mag/dbg_diag, plus dbg_pos_raw which is the angle bits with the error flag ignored, so the angle can be watched while the shaft is turned by hand. --- Firmware/MotorControl/encoder.cpp | 23 +++++++++++++++++++++++ Firmware/MotorControl/encoder.hpp | 4 ++++ Firmware/odrive-interface.yaml | 4 ++++ 3 files changed, 31 insertions(+) diff --git a/Firmware/MotorControl/encoder.cpp b/Firmware/MotorControl/encoder.cpp index 2123338fc..5fc593c33 100644 --- a/Firmware/MotorControl/encoder.cpp +++ b/Firmware/MotorControl/encoder.cpp @@ -532,6 +532,19 @@ void Encoder::decode_hall_samples() { bool Encoder::abs_spi_start_transaction() { if (mode_ & MODE_FLAG_ABS){ if (Stm32SpiArbiter::acquire_task(&spi_task_)) { + // --- temporary diagnostics: probe AS5048A registers every 64th frame --- + if (mode_ == MODE_SPI_ABS_AMS) { + static uint32_t dbg_seq = 0; + dbg_seq++; + if ((dbg_seq & 0x3f) == 0) { + abs_spi_dma_tx_[0] = 0x7FFE; // MAGNITUDE + } else if ((dbg_seq & 0x3f) == 0x20) { + abs_spi_dma_tx_[0] = 0x7FFD; // DIAG / AGC + } else { + abs_spi_dma_tx_[0] = 0xFFFF; // ANGLE + } + dbg_tx_last_ = abs_spi_dma_tx_[0]; + } spi_task_.ncs_gpio = abs_spi_cs_gpio_; spi_task_.tx_buf = (uint8_t*)abs_spi_dma_tx_; spi_task_.rx_buf = (uint8_t*)abs_spi_dma_rx_; @@ -584,6 +597,16 @@ void Encoder::abs_spi_cb(bool success) { dbg_raw_[0] = rawVal; dbg_total_++; + if (dbg_tx_last_ == 0x7FFE) { // MAGNITUDE response + dbg_mag_ = (float)(rawVal & 0x3fff); + goto done; + } + if (dbg_tx_last_ == 0x7FFD) { // DIAG / AGC response + dbg_diag_ = (float)(rawVal & 0x3fff); + goto done; + } + dbg_pos_raw_ = (float)(rawVal & 0x3fff); + // check if parity is correct (even) and error flag clear if (ams_parity(rawVal)) { dbg_parity_fail_++; diff --git a/Firmware/MotorControl/encoder.hpp b/Firmware/MotorControl/encoder.hpp index ecee44114..931bf15ff 100644 --- a/Firmware/MotorControl/encoder.hpp +++ b/Firmware/MotorControl/encoder.hpp @@ -153,6 +153,10 @@ class Encoder : public ODriveIntf::EncoderIntf { uint32_t dbg_flag_fail_ = 0; uint32_t dbg_ok_ = 0; float dbg_pos_ = 0.0f; // last accepted position + float dbg_pos_raw_ = 0.0f; // last angle bits, error flag ignored + float dbg_mag_ = -1.0f; // AS5048A MAGNITUDE register (0x7FFE) + float dbg_diag_ = -1.0f; // AS5048A DIAG/AGC register (0x7FFD) + uint16_t dbg_tx_last_ = 0xFFFF; constexpr float getCoggingRatio(){ return 1.0f / 3600.0f; diff --git a/Firmware/odrive-interface.yaml b/Firmware/odrive-interface.yaml index d6d1d96de..9def0a003 100644 --- a/Firmware/odrive-interface.yaml +++ b/Firmware/odrive-interface.yaml @@ -1309,6 +1309,10 @@ interfaces: dbg_flag_fail: {type: readonly uint32, c_getter: dbg_flag_fail_} dbg_ok: {type: readonly uint32, c_getter: dbg_ok_} dbg_pos: {type: readonly float32, c_getter: dbg_pos_} + dbg_pos_raw: {type: readonly float32, c_getter: dbg_pos_raw_} + dbg_mag: {type: readonly float32, c_getter: dbg_mag_} + dbg_diag: {type: readonly float32, c_getter: dbg_diag_} + dbg_tx: {type: readonly uint16, c_getter: dbg_tx_last_} config: c_is_class: False attributes: From 87fde1ae0db728ec347dd113fe4ce9bf97e90101 Mon Sep 17 00:00:00 2001 From: JIE Date: Sun, 18 Oct 2026 22:29:13 +0800 Subject: [PATCH 27/32] Add temporary switch to accept AS5048A frames with the error flag set The captured angle is smooth and covers the full range while the shaft is turned by hand (static noise band ~9 counts), yet the encoder keeps EF=1, so the only thing blocking commissioning is the flag itself. dbg_ignore_ef is a non-persistent runtime switch to accept those frames for bring-up; it resets to false on reboot. --- Firmware/MotorControl/encoder.cpp | 2 +- Firmware/MotorControl/encoder.hpp | 2 ++ Firmware/odrive-interface.yaml | 8 ++++++++ 3 files changed, 11 insertions(+), 1 deletion(-) diff --git a/Firmware/MotorControl/encoder.cpp b/Firmware/MotorControl/encoder.cpp index 5fc593c33..704b1be7b 100644 --- a/Firmware/MotorControl/encoder.cpp +++ b/Firmware/MotorControl/encoder.cpp @@ -614,7 +614,7 @@ void Encoder::abs_spi_cb(bool success) { } if ((rawVal >> 14) & 1) { dbg_flag_fail_++; - goto done; + if (!dbg_ignore_ef_) goto done; } dbg_ok_++; dbg_pos_ = (float)(rawVal & 0x3fff); diff --git a/Firmware/MotorControl/encoder.hpp b/Firmware/MotorControl/encoder.hpp index 931bf15ff..074525ead 100644 --- a/Firmware/MotorControl/encoder.hpp +++ b/Firmware/MotorControl/encoder.hpp @@ -157,6 +157,8 @@ class Encoder : public ODriveIntf::EncoderIntf { float dbg_mag_ = -1.0f; // AS5048A MAGNITUDE register (0x7FFE) float dbg_diag_ = -1.0f; // AS5048A DIAG/AGC register (0x7FFD) uint16_t dbg_tx_last_ = 0xFFFF; + bool dbg_ignore_ef_ = false; // temporary: accept AS5048A frames with EF set + void set_dbg_ignore_ef(bool value) { dbg_ignore_ef_ = value; } constexpr float getCoggingRatio(){ return 1.0f / 3600.0f; diff --git a/Firmware/odrive-interface.yaml b/Firmware/odrive-interface.yaml index 9def0a003..a0180b52e 100644 --- a/Firmware/odrive-interface.yaml +++ b/Firmware/odrive-interface.yaml @@ -1313,6 +1313,14 @@ interfaces: dbg_mag: {type: readonly float32, c_getter: dbg_mag_} dbg_diag: {type: readonly float32, c_getter: dbg_diag_} dbg_tx: {type: readonly uint16, c_getter: dbg_tx_last_} + dbg_ignore_ef: + type: bool + c_getter: dbg_ignore_ef_ + c_setter: set_dbg_ignore_ef + doc: | + TEMPORARY bring-up switch. Accept AS5048A frames even if the encoder + sets its error flag (bit 14). The flag is not persisted and resets on + reboot. Only use it when the angle is known to read correctly. config: c_is_class: False attributes: From 4390a76703eb0680b24d07353010de96328a91e9 Mon Sep 17 00:00:00 2001 From: JIE Date: Sun, 18 Oct 2026 22:40:38 +0800 Subject: [PATCH 28/32] Remove AS5048A register probes, keep read-only frame diagnostics The 0x7FFE/0x7FFD probes raced with the completion callback: when a probe frame's callback ran after the next transaction had already started, the garbage register value was published as an angle and the real angle was dropped. That showed up as ~3% of frames jumping to a fixed wrong value and kept spi_error_rate pinned at 3.1%. Keep only the passive raw-frame history and counters, which do not alter behaviour, and the opt-in ignore_abs_spi_error_flag switch. --- Firmware/MotorControl/encoder.cpp | 30 ++++-------------------------- Firmware/MotorControl/encoder.hpp | 13 +++++-------- Firmware/odrive-interface.yaml | 19 +++++++------------ 3 files changed, 16 insertions(+), 46 deletions(-) diff --git a/Firmware/MotorControl/encoder.cpp b/Firmware/MotorControl/encoder.cpp index 704b1be7b..d1561b434 100644 --- a/Firmware/MotorControl/encoder.cpp +++ b/Firmware/MotorControl/encoder.cpp @@ -532,19 +532,6 @@ void Encoder::decode_hall_samples() { bool Encoder::abs_spi_start_transaction() { if (mode_ & MODE_FLAG_ABS){ if (Stm32SpiArbiter::acquire_task(&spi_task_)) { - // --- temporary diagnostics: probe AS5048A registers every 64th frame --- - if (mode_ == MODE_SPI_ABS_AMS) { - static uint32_t dbg_seq = 0; - dbg_seq++; - if ((dbg_seq & 0x3f) == 0) { - abs_spi_dma_tx_[0] = 0x7FFE; // MAGNITUDE - } else if ((dbg_seq & 0x3f) == 0x20) { - abs_spi_dma_tx_[0] = 0x7FFD; // DIAG / AGC - } else { - abs_spi_dma_tx_[0] = 0xFFFF; // ANGLE - } - dbg_tx_last_ = abs_spi_dma_tx_[0]; - } spi_task_.ncs_gpio = abs_spi_cs_gpio_; spi_task_.tx_buf = (uint8_t*)abs_spi_dma_tx_; spi_task_.rx_buf = (uint8_t*)abs_spi_dma_rx_; @@ -597,27 +584,18 @@ void Encoder::abs_spi_cb(bool success) { dbg_raw_[0] = rawVal; dbg_total_++; - if (dbg_tx_last_ == 0x7FFE) { // MAGNITUDE response - dbg_mag_ = (float)(rawVal & 0x3fff); - goto done; - } - if (dbg_tx_last_ == 0x7FFD) { // DIAG / AGC response - dbg_diag_ = (float)(rawVal & 0x3fff); - goto done; - } - dbg_pos_raw_ = (float)(rawVal & 0x3fff); - - // check if parity is correct (even) and error flag clear if (ams_parity(rawVal)) { dbg_parity_fail_++; goto done; } + // bit 14: AS5048A magnetic field error flag if ((rawVal >> 14) & 1) { dbg_flag_fail_++; - if (!dbg_ignore_ef_) goto done; + if (!ignore_abs_spi_error_flag_) { + goto done; + } } dbg_ok_++; - dbg_pos_ = (float)(rawVal & 0x3fff); pos = rawVal & 0x3fff; } break; diff --git a/Firmware/MotorControl/encoder.hpp b/Firmware/MotorControl/encoder.hpp index 074525ead..332f181da 100644 --- a/Firmware/MotorControl/encoder.hpp +++ b/Firmware/MotorControl/encoder.hpp @@ -146,19 +146,16 @@ class Encoder : public ODriveIntf::EncoderIntf { uint16_t abs_spi_dma_rx_[1]; Stm32SpiArbiter::SpiTask spi_task_; - // --- temporary AS5048A bring-up diagnostics --- + // --- AS5048A bring-up diagnostics --- uint16_t dbg_raw_[8] = {0}; // last 8 raw frames, dbg_raw_[0] = newest uint32_t dbg_total_ = 0; // completed SPI transactions uint32_t dbg_parity_fail_ = 0; uint32_t dbg_flag_fail_ = 0; uint32_t dbg_ok_ = 0; - float dbg_pos_ = 0.0f; // last accepted position - float dbg_pos_raw_ = 0.0f; // last angle bits, error flag ignored - float dbg_mag_ = -1.0f; // AS5048A MAGNITUDE register (0x7FFE) - float dbg_diag_ = -1.0f; // AS5048A DIAG/AGC register (0x7FFD) - uint16_t dbg_tx_last_ = 0xFFFF; - bool dbg_ignore_ef_ = false; // temporary: accept AS5048A frames with EF set - void set_dbg_ignore_ef(bool value) { dbg_ignore_ef_ = value; } + // Accept AS5048A frames even though the encoder asserts its magnetic field + // error flag (bit 14). Not persisted: resets to false on reboot. + bool ignore_abs_spi_error_flag_ = false; + void set_ignore_abs_spi_error_flag(bool value) { ignore_abs_spi_error_flag_ = value; } constexpr float getCoggingRatio(){ return 1.0f / 3600.0f; diff --git a/Firmware/odrive-interface.yaml b/Firmware/odrive-interface.yaml index a0180b52e..4300d9e7a 100644 --- a/Firmware/odrive-interface.yaml +++ b/Firmware/odrive-interface.yaml @@ -1295,7 +1295,7 @@ interfaces: type: int32 doc: The last (valid) position from an absolute encoder, if used. spi_error_rate: readonly float32 - # --- temporary AS5048A bring-up diagnostics --- + # --- AS5048A bring-up diagnostics (read-only, no behaviour change) --- dbg_raw0: {type: readonly uint16, c_getter: "dbg_raw_[0]"} dbg_raw1: {type: readonly uint16, c_getter: "dbg_raw_[1]"} dbg_raw2: {type: readonly uint16, c_getter: "dbg_raw_[2]"} @@ -1308,19 +1308,14 @@ interfaces: dbg_parity_fail: {type: readonly uint32, c_getter: dbg_parity_fail_} dbg_flag_fail: {type: readonly uint32, c_getter: dbg_flag_fail_} dbg_ok: {type: readonly uint32, c_getter: dbg_ok_} - dbg_pos: {type: readonly float32, c_getter: dbg_pos_} - dbg_pos_raw: {type: readonly float32, c_getter: dbg_pos_raw_} - dbg_mag: {type: readonly float32, c_getter: dbg_mag_} - dbg_diag: {type: readonly float32, c_getter: dbg_diag_} - dbg_tx: {type: readonly uint16, c_getter: dbg_tx_last_} - dbg_ignore_ef: + ignore_abs_spi_error_flag: type: bool - c_getter: dbg_ignore_ef_ - c_setter: set_dbg_ignore_ef + c_getter: ignore_abs_spi_error_flag_ + c_setter: set_ignore_abs_spi_error_flag doc: | - TEMPORARY bring-up switch. Accept AS5048A frames even if the encoder - sets its error flag (bit 14). The flag is not persisted and resets on - reboot. Only use it when the angle is known to read correctly. + Accept AS5048A frames even though the encoder asserts its magnetic + field error flag (bit 14). Not persisted, resets to false on reboot. + Only use when the angle is verified to read correctly. config: c_is_class: False attributes: From 35ed8e720acb95f85e64bdf056b869ae7ac99bc9 Mon Sep 17 00:00:00 2001 From: JIE Date: Sun, 18 Oct 2026 22:48:49 +0800 Subject: [PATCH 29/32] Make the AS5048A error-flag override a persisted config option The board's encoder asserts the magnetic field error flag on every frame even though its angle is clean, full range and repeatable, and the v3.6 encoder header does not route MOSI, so the chip's clear-error-command cannot be sent. Move the override from a runtime switch into encoder.config so the axis keeps working across power cycles. Default stays false (upstream behaviour); a board that needs it must opt in explicitly. Bump config_version since the config struct grew. --- Firmware/MotorControl/encoder.cpp | 2 +- Firmware/MotorControl/encoder.hpp | 9 +++++---- Firmware/MotorControl/nvm_config.hpp | 2 +- Firmware/odrive-interface.yaml | 16 ++++++++-------- 4 files changed, 15 insertions(+), 14 deletions(-) diff --git a/Firmware/MotorControl/encoder.cpp b/Firmware/MotorControl/encoder.cpp index d1561b434..88f349610 100644 --- a/Firmware/MotorControl/encoder.cpp +++ b/Firmware/MotorControl/encoder.cpp @@ -591,7 +591,7 @@ void Encoder::abs_spi_cb(bool success) { // bit 14: AS5048A magnetic field error flag if ((rawVal >> 14) & 1) { dbg_flag_fail_++; - if (!ignore_abs_spi_error_flag_) { + if (!config_.abs_spi_ignore_error_flag) { goto done; } } diff --git a/Firmware/MotorControl/encoder.hpp b/Firmware/MotorControl/encoder.hpp index 332f181da..0993f7bdf 100644 --- a/Firmware/MotorControl/encoder.hpp +++ b/Firmware/MotorControl/encoder.hpp @@ -43,6 +43,11 @@ class Encoder : public ODriveIntf::EncoderIntf { uint16_t abs_spi_cs_gpio_pin = 1; uint16_t sincos_gpio_pin_sin = 3; uint16_t sincos_gpio_pin_cos = 4; + // Accept AS5048A frames even though the encoder asserts its magnetic + // field error flag (bit 14). Only enable this when the angle has been + // verified to read correctly over the full range: the flag itself + // indicates the magnet is out of spec (air gap, centring, type). + bool abs_spi_ignore_error_flag = false; // custom setters @@ -152,10 +157,6 @@ class Encoder : public ODriveIntf::EncoderIntf { uint32_t dbg_parity_fail_ = 0; uint32_t dbg_flag_fail_ = 0; uint32_t dbg_ok_ = 0; - // Accept AS5048A frames even though the encoder asserts its magnetic field - // error flag (bit 14). Not persisted: resets to false on reboot. - bool ignore_abs_spi_error_flag_ = false; - void set_ignore_abs_spi_error_flag(bool value) { ignore_abs_spi_error_flag_ = value; } constexpr float getCoggingRatio(){ return 1.0f / 3600.0f; diff --git a/Firmware/MotorControl/nvm_config.hpp b/Firmware/MotorControl/nvm_config.hpp index 706a8d43f..9b1f308bb 100644 --- a/Firmware/MotorControl/nvm_config.hpp +++ b/Firmware/MotorControl/nvm_config.hpp @@ -26,7 +26,7 @@ // IMPORTANT: if you change, reorder or otherwise modify any of the fields in // the config structs without changing its total length, make sure to increment this number: -static constexpr uint16_t config_version = 0x0001; +static constexpr uint16_t config_version = 0x0002; /* Private variables ---------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ diff --git a/Firmware/odrive-interface.yaml b/Firmware/odrive-interface.yaml index 4300d9e7a..777409191 100644 --- a/Firmware/odrive-interface.yaml +++ b/Firmware/odrive-interface.yaml @@ -1308,14 +1308,6 @@ interfaces: dbg_parity_fail: {type: readonly uint32, c_getter: dbg_parity_fail_} dbg_flag_fail: {type: readonly uint32, c_getter: dbg_flag_fail_} dbg_ok: {type: readonly uint32, c_getter: dbg_ok_} - ignore_abs_spi_error_flag: - type: bool - c_getter: ignore_abs_spi_error_flag_ - c_setter: set_ignore_abs_spi_error_flag - doc: | - Accept AS5048A frames even though the encoder asserts its magnetic - field error flag (bit 14). Not persisted, resets to false on reboot. - Only use when the angle is verified to read correctly. config: c_is_class: False attributes: @@ -1378,6 +1370,14 @@ interfaces: sincos_gpio_pin_cos: type: uint16 doc: Analog cosine signal of a sin/cos encoder. The corresponding GPIO must be in `GPIO_MODE_ANALOG_IN`. + abs_spi_ignore_error_flag: + type: bool + doc: | + Accept AS5048A frames even though the encoder asserts its magnetic + field error flag (bit 14). The flag indicates the magnet is out of + spec (air gap, centring or magnetisation type); a board that always + reports it while still reading a clean, full-range angle needs this + to be usable. Verify the angle before enabling. functions: set_linear_count: in: From 2442c6636b4d6614ebe5def674fbebb093180366 Mon Sep 17 00:00:00 2001 From: JIE Date: Sun, 18 Oct 2026 22:57:32 +0800 Subject: [PATCH 30/32] Document the real root cause and closed-loop result for axis0 The earlier EMI conclusion was drawn on firmware whose AMS parser rebuilt the parity bit before checking it, so every frame was accepted and pos_abs was noise; the huge calib_scan_response came from that, not from magnetic interference. Record the corrected analysis, the final configuration and the measured closed-loop results, plus the remaining hardware caveat (encoder error flag) and the gain tuning that the small low-friction motor needs. --- MOTOR_CONTROL_COMMISSIONING.md | 419 +++++++++++++++++++++++++++++++++ 1 file changed, 419 insertions(+) create mode 100644 MOTOR_CONTROL_COMMISSIONING.md diff --git a/MOTOR_CONTROL_COMMISSIONING.md b/MOTOR_CONTROL_COMMISSIONING.md new file mode 100644 index 000000000..1cefe8764 --- /dev/null +++ b/MOTOR_CONTROL_COMMISSIONING.md @@ -0,0 +1,419 @@ +# JD-Power MY-4625F 电机控制调试记录 + +## 目标对象 + +- 电机型号:JD-Power MY-4625F 4012 外转电机 +- 结构信息:24N22P +- KV:55 rpm/V +- 标称电压范围:10V ~ 24V +- 最大扭矩:2.5 kgf-cm +- 编码器:AS5048A SPI 绝对编码器 +- ODrive 轴:axis0 + +## 当前结论 + +电机参数配置和电机本体电气测量已经基本打通,但 **FOC 闭环目前仍未完成**。 + +阻塞点不在电机参数本身,而在 **电机励磁时编码器读数失真,导致 encoder offset calibration 失败**。 + +换句话说: + +- 手动转动时,AS5048A 通信正常 +- 电机一进入带电校准,编码器计数就出现大幅跳变 +- 因此 ODrive 无法建立可靠的电角度偏移 +- 所以暂时还不能进入真正可用的闭环控制 + +## 本次使用的关键参数 + +已确认正确或较合理的基础配置: + +- `motor.config.motor_type = 0` (`MOTOR_TYPE_HIGH_CURRENT`) +- `motor.config.pole_pairs = 11` +- `motor.config.torque_constant = 8.27 / 55 = 0.15036` +- `encoder.config.mode = 257` (`AMS SPI ABS`) +- `encoder.config.cpr = 16384` +- `encoder.config.abs_spi_cs_gpio_pin = 7` + +## 已验证的基础状态 + +在未进入电机带电校准前: + +- `axis.error = 0` +- `motor.error = 0` +- `encoder.error = 0` +- 手动转动时 `pos_abs` 正常更新 +- 连续采样期间未再复现 `ERROR_ABS_SPI_COM_FAIL (128)` + +这说明此前的 SPI 通信问题已经解决。 + +## 电机参数配置结果 + +已经把以下基础参数写入并验证过: + +- `pole_pairs = 11` +- `torque_constant = 0.15036364` +- `control_mode = POSITION_CONTROL` +- `input_mode = PASSTHROUGH` + +其中 `pole_pairs` 和 `torque_constant` 与电机铭牌信息是一致的。 + +## 电机校准阶段的结果 + +### 第一阶段:高电流配置失败 + +最初使用较大的 `calibration_current` 时,校准会在 motor calibration 早期失败,表现为: + +- `MOTOR_ERROR_PHASE_RESISTANCE_OUT_OF_RANGE` +- `phase_resistance = nan` + +这表明目标校准电流过高,控制器为了达到该电流,测试电压积分到了上限仍不够,因此不是“电机断路”,而是参数对这台低电流电机不合适。 + +### 第二阶段:降低校准电流后,motor calibration 成功 + +当参数调整为更保守组合后,motor calibration 成功给出了稳定测量值: + +- `calibration_current = 1.0 A` +- `current_lim = 2.0 A` +- `resistance_calib_max_voltage = 4.0 V` + +测得的电机参数为: + +- `phase_resistance ≈ 2.1809 ohm` +- `phase_inductance ≈ 0.0005823 H` + +这说明: + +- ODrive 对这台电机的电气建模已经开始有效 +- 电机不是完全无法驱动 +- 真正卡住的是后续的 encoder offset calibration + +## 编码器偏移校准阶段的结果 + +在 motor calibration 成功后,full calibration 会继续进入: + +- `AXIS_STATE_ENCODER_OFFSET_CALIBRATION` (`state = 7`) + +该阶段最终失败,错误为: + +- `axis.error = 256` (`AXIS_ERROR_ENCODER_FAILED`) +- `encoder.error = 2` (`ENCODER_ERROR_CPR_POLEPAIRS_MISMATCH`) + +## 为什么这个错误不代表 pole_pairs 一定填错了 + +ODrive 在 offset calibration 中会比较: + +- 编码器实际计数变化量 +- 根据 `pole_pairs`、`cpr` 和扫描距离推算出的理论变化量 + +对当前参数: + +- `pole_pairs = 11` +- `cpr = 16384` +- `calib_scan_distance = 16π electrical rad` + +理论上,编码器响应量大约应为: + +- `8 * cpr / pole_pairs ≈ 11915 counts` + +但实际测到: + +- `calib_scan_response = 276238` 到 `289893 counts` + +这个偏差不是“11 写成了 10 或 12”这种级别,而是差了一个数量级以上,因此更像: + +- 电机励磁时编码器计数大范围跳变 +- 导致 `shadow_count` 在校准过程中疯狂累计 +- 最终触发 `CPR_POLEPAIRS_MISMATCH` + +## 直接证据:只跑 encoder offset calibration 时的采样结果 + +单独执行 `AXIS_STATE_ENCODER_OFFSET_CALIBRATION` 并高频采样后得到: + +- `states_seen = [1, 7]` +- `pos_min = 243` +- `pos_max = 15348` +- `pos_distinct = 279` +- `max_pos_step = 14848` +- `shadow_min = -94366` +- `shadow_max = 45132` +- `max_shadow_step = 90376` + +这说明在电机带电扫描时: + +- `pos_abs` 存在接近整圈量级的跳变 +- `shadow_count` 出现远超正常机械运动的突变 +- 编码器虽然没有报 SPI 通信错误,但位置本身在励磁环境下已经不可信 + +## 当前最合理的工程判断 + +当前最合理的判断是: + +### 1. AS5048A 的静态通信问题已经解决 + +也就是此前的 `ERROR_ABS_SPI_COM_FAIL (128)` 已经不是当前主问题。 + +### 2. 电机励磁磁场或 PWM 干扰正在影响编码器角度测量 + +这可能来自: + +- 电机定子电流产生的附加磁场干扰 AS5048A +- 编码器安装位置离励磁区域过近 +- 编码器电缆在电机 PWM 驱动时受到干扰 +- 当前 32.5V 母线电压过高,导致 PWM 边沿更强、干扰更重 + +### 3. 当前真正阻塞闭环的是“励磁时角度不可信” + +只要 offset calibration 无法稳定完成,就不能认为 FOC 闭环已经建立成功。 + +## 特别注意:当前母线电压偏高 + +实测 `vbus ≈ 32.5V`,已经高于这台电机的标称 10V ~ 24V 范围。 + +虽然目前测试都限制在低电流、低速度、校准场景,但这仍然是一个重要风险: + +- 不适合继续做高速或大扭矩测试 +- 也可能加剧编码器或布线的电磁干扰问题 + +## 12V 降压后的复测结果 + +在把母线电压降到约 `12.37V` 后,重新做了校准相关测试。 + +### 改善点 + +与 32V 级别母线相比,12V 下出现了明显改善: + +- 不再触发此前的系统级回灌问题 +- motor calibration 仍然可以稳定测出电机参数 +- 励磁干扰的量级相比高压时有所减弱 + +在 12V 条件下测得: + +- `phase_resistance ≈ 1.995Ω` +- `phase_inductance ≈ 0.000730H` + +这些数值与之前同量级,说明电机电气测量结果是可信的。 + +### 仍然存在的问题 + +即使降到 12V,encoder offset calibration 仍未完成,仍然报: + +- `axis.error = 256` +- `encoder.error = 2` (`ENCODER_ERROR_CPR_POLEPAIRS_MISMATCH`) + +但这次数据表明问题程度有所减轻,而不是彻底消失: + +- 高压条件下曾出现 `calib_scan_response ≈ 276238 ~ 309003` +- 12V、低励磁尝试时最低降到 `calib_scan_response ≈ 75546` + +理论期望值大约仍只有: + +- `≈ 11915 counts` + +这说明: + +- 降压确实降低了干扰强度 +- 但励磁下编码器计数仍然严重失真 +- 当前还不足以完成可靠的电角度偏移校准 + +### 当前判断更新 + +12V 供电验证说明一个重要事实: + +- **母线过压会加剧问题,但不是唯一根因。** + +更本质的 blocker 仍然是: + +- 电机励磁时,AS5048A 的角度测量仍受到明显磁场或 EMI 干扰 + +## 继续降压到约 5.3V 的结果 + +后续继续把母线压低到约 `5.31V` 后,问题不再是 encoder offset calibration,而是系统已经进入欠压工作区: + +- `LegacyODriveError.DC_BUS_UNDER_VOLTAGE` +- `MotorError.DRV_FAULT` +- `MotorError.SYSTEM_LEVEL` + +对应现象: + +- `vbus ≈ 5.31V` +- `axis.error = 64` +- `motor.error = 16777224 = DRV_FAULT | SYSTEM_LEVEL` +- 编码器本身未报新错误 + +这说明: + +- 再继续降压并不能越过原来的 encoder mismatch 问题 +- 反而会先把 ODrive 功率级带入欠压/驱动器故障区 + +因此,当前可用的测试窗口应理解为: + +- 过高电压会加剧励磁干扰 +- 过低电压会触发欠压和 DRV fault +- 后续更合理的调试区间应维持在电机标称范围内,例如 `10V ~ 12V` 左右,而不是继续往下压 + +## 调整安装后的复测结果 + +在重新调整编码器安装之后,又在约 `11.37V` 母线下做了一轮复测。 + +### 静态状态 + +静态条件下基线是干净的: + +- `axis.error = 0` +- `motor.error = 0` +- `encoder.error = 0` +- 静态采样时编码器位置只在很小范围内微动 + +这说明安装调整没有破坏原有的静态 SPI 通信稳定性。 + +### full calibration 结果 + +使用较低风险参数: + +- `calibration_current = 0.5` +- `current_lim = 1.0` +- `resistance_calib_max_voltage = 4.0` +- `encoder.config.calib_range = 0.20` +- `encoder.config.calib_scan_omega = 1.0` + +full calibration 的过程为: + +- 进入 `state 4`:motor calibration +- 成功进入 `state 7`:encoder offset calibration +- 在大约 `55s` 后失败并返回 idle + +最终结果: + +- `axis.error = 256` +- `motor.error = 0` +- `encoder.error = 2` +- `encoder_ready = False` +- `phase_resistance ≈ 2.055Ω` +- `phase_inductance ≈ 0.000693H` +- `calib_scan_response ≈ 231731` + +### 结论更新 + +安装调整后,确实出现了一定改善: + +- 校准能更稳定地进入 encoder offset calibration +- 过程持续时间更长 +- 相比最差状态,干扰强度有所下降 + +但目前仍然没有跨过根本阻塞: + +- encoder offset calibration 最终仍以 `ENCODER_ERROR_CPR_POLEPAIRS_MISMATCH` 结束 +- `calib_scan_response` 仍远大于理论期望值 + +所以截至当前,合理结论是: + +- **安装调整带来了改善,但还不足以让 FOC 所需的电角度偏移校准成功。** + +因此,下一步重点仍应放在: + +- 编码器安装位置 +- 磁路隔离 +- 供电退耦 +- SPI 布线与电机相线分离 + +而不是继续单纯反复调整 ODrive 校准参数。 + +## 下一步建议 + +按优先级推荐如下: + +1. 先把母线电压降到电机额定范围内,例如 12V ~ 24V,再重复 encoder offset calibration。 +2. 优化 AS5048A 安装与布线:增加与电机励磁区域的距离,改善地线与供电退耦,SPI 线与电机三相线分离。 +3. 若条件允许,使用示波器或逻辑分析仪在电机带电校准时同时观察 `CS/SCK/MISO` 与电机相线环境。 +4. 如果磁场耦合无法避免,考虑更换为更抗干扰的编码器方案,或更改机械安装方式。 +5. 在确认编码器励磁下仍稳定之前,不建议把当前状态视为“已实现可用的 FOC 闭环控制”。 + +## 一句话总结 + +目前电机电气参数已经能测出来,但 encoder offset calibration 失败;根因高度怀疑是 **电机励磁时 AS5048A 角度测量被磁场/EMI 干扰**,因此当前还不能宣称 axis0 已完成可用的 FOC 闭环控制。 +--- + +# 复盘(后续更新):真正根因不是 EMI,已闭环 + +上面“励磁时编码器失真”的结论是在**有 bug 的固件**上得出的,现已被推翻。 +axis0 现在可以正常闭环转动,上电即用。 + +## 真正的原因链 + +### 1. SPI 相位错了,导致整帧错位 + +`Encoder::setup()` 里 AMS 分支的 `CLKPhase` 曾被改成 `SPI_PHASE_1EDGE`(commit `78035e40`), +但 AS5048A 是 **SPI mode 1(CPOL=0, CPHA=1)**,必须用 `SPI_PHASE_2EDGE`。 +1EDGE 会让主机早采一个时钟,整帧左移一位,偶校验几乎必然失败。 + +### 2. “奇偶位重建”把错误藏起来了 + +后续的 commit(`8c7d458f` 等)在解析前用移位后的值**重新计算并写回奇偶位**, +于是校验变成自证的、永远通过,任意错误帧都会被当成有效角度。 +表现就是电机静止时 `pos_abs` 在 5453 / 11541 / 5613 / 3349 之间乱跳。 + +这就是 `calib_scan_response ≈ 231731`(理论 11915)的真正来源: +不是磁场干扰,是解析器在编数据,`shadow_count` 被垃圾增量累加爆掉。 + +### 3. 修好相位后暴露的真问题:AS5048A 的 Error Flag 常 1 + +改成 2EDGE + 严格偶校验后,实测 139832 帧里只有 2 帧奇偶失败—— +说明时序和链路都是好的,原始帧稳定在 `0x7455/0xF454`(位置 13397)。 + +但**每一帧的 bit14(磁场 Error Flag)都是 1**,固件按设计丢弃所有帧, +于是 `pos_abs` 恒为 0、`encoder.error = 128`。 + +人工转轴实测:角度连续、满量程 99.5%、噪声带 7–15 counts(约 0.2–0.3°), +说明**角度是真实可用的,只是芯片认为磁场超出规格**。 + +## 最终修复 + +- `CLKPhase` 改回 `SPI_PHASE_2EDGE`(SPI mode 1),SPI 时钟 2.6 MHz +- AMS 解析恢复严格偶校验 + EF 检查,删除移位/字节交换/重算奇偶的所有补丁 +- 保留 `abs_spi_transaction_pending_`(在途 DMA 事务不计失败) +- 新增持久配置 `encoder.config.abs_spi_ignore_error_flag`,默认 `false`; + 本板置 `true`,因为 EF 常 1 但角度可信 +- 移除中途加的 0x7FFE/0x7FFD 探针(回调与下一帧启动存在竞态,会把寄存器值当成角度) + +相关提交:`096ad126`、`b7b47562`、`4b34d02c`、`87fde1ae`、`4390a767`、`35ed8e72` + +## 最终验证结果 + +``` +motor: cal=True pre_cal=True pp=11 R=1.9396Ω L=0.690mH Ilim=3.0A +encoder: err=0 ready=True mode=257 cpr=16384 cs_gpio=7 + offset_float=0.6273 direction=1 ignore_ef=True +ctrl: control_mode=2 velocity, input_mode=2 vel_ramp, vg=0.08 vi=0.4 ramp=2.0 +``` + +- encoder offset calibration:`calib_scan_response = 11889`(期望 11916,误差 0.2%) +- 闭环速度环(VEL_RAMP,加速度限制 2 turn/s²): + +| 目标 | 实测均值 | 范围 | 错误 | +|------|----------|------|------| +| +1.0 turn/s | +0.996 | 0.78 ~ 1.21 | 全 0 | +| +2.0 turn/s | +2.024 | 1.71 ~ 2.24 | 全 0 | +| -1.0 turn/s | -0.721(换向窗口) | -1.23 ~ +0.05 | 全 0 | +| 0 | +0.004 | -0.07 ~ +0.07 | 全 0 | + +全部配置已 `save_configuration()`,**断电重启后无需任何脚本即可闭环运行**。 + +## 仍然遗留的硬件问题 + +AS5048A 的 Error Flag 常 1,说明磁铁仍不在规格内(气隙 / 同心度 / 充磁方向)。 +角度虽然可用,但这是治标。建议: + +1. 确认磁铁是**径向(diametric)充磁**的圆片/圆柱磁铁,不是轴向充磁、不是多极磁环 +2. 磁铁中心与芯片中心对齐,气隙 1–2 mm +3. 换好磁铁后,把 `encoder.config.abs_spi_ignore_error_flag` 改回 `false` 并保存, + 确认 `encoder.error` 仍为 0,此时才算真正修好 + +## 调参经验 + +- 这台 55KV 小电机摩擦很小,默认增益(vel_gain 0.167 / vel_integrator_gain 0.333) + 在速度环里会一次给到 0.05 N·m 级别扭矩,25 ms 内就冲过 vel_limit 触发 OVERSPEED。 + 最终用 `vel_gain=0.08 / vel_integrator_gain=0.4`。 +- 速度环**必须**配 `input_mode = VEL_RAMP` + `vel_ramp_rate = 2.0`, + 否则阶跃给定 + 3 A 电流限幅会让电机猛地一冲然后过速保护。 +- `enable_brake_resistor` 只在**上电时**生效:运行中再置 true 会报 `BRAKE_RESISTOR_DISARMED`, + 必须保存配置后重启。刹车电阻实际阻值也要和 `config.brake_resistance` 一致。 From 27824585420ba4e86776e53060ae9ec230a5c757 Mon Sep 17 00:00:00 2001 From: JIE Date: Sun, 18 Oct 2026 23:08:06 +0800 Subject: [PATCH 31/32] Add a banner to the commissioning log pointing at the corrected analysis The first half still records the EMI hypothesis that later turned out to be wrong; make that explicit so the file is not read as current guidance. --- MOTOR_CONTROL_COMMISSIONING.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/MOTOR_CONTROL_COMMISSIONING.md b/MOTOR_CONTROL_COMMISSIONING.md index 1cefe8764..a0e3f7156 100644 --- a/MOTOR_CONTROL_COMMISSIONING.md +++ b/MOTOR_CONTROL_COMMISSIONING.md @@ -1,5 +1,11 @@ # JD-Power MY-4625F 电机控制调试记录 +> ⚠️ **阅读提示** +> 本文上半部分(到「下一步建议」为止)记录的是当时的调试过程,其中 +> **“励磁时编码器被磁场/EMI 干扰”这一结论已被推翻**。 +> 真正根因与最终结果见文末 **[复盘:真正根因不是 EMI,已闭环]** 一节。 +> 目前 axis0 已可正常闭环运行。 + ## 目标对象 - 电机型号:JD-Power MY-4625F 4012 外转电机 From 3bff58a69653955f89f8ac69b1f65ccdef8a3673 Mon Sep 17 00:00:00 2001 From: JIE Date: Sun, 18 Oct 2026 23:21:29 +0800 Subject: [PATCH 32/32] Reject implausible AS5048A frame jumps before they reach the PLL A corrupted frame can still carry even parity (the check only catches about half of all bit errors), and a ~335 count jump produces a one-cycle velocity estimate of well over 100 turn/s, which latches ERROR_OVERSPEED even with the rotor standing still. At 8 kHz a 3.6 turn/s machine moves less than 8 counts per control period, so drop any frame that jumps more than 64 counts (8x margin). Count them in dbg_jump_reject. --- Firmware/MotorControl/encoder.cpp | 21 +++++++++++++++++++++ Firmware/MotorControl/encoder.hpp | 3 +++ Firmware/odrive-interface.yaml | 1 + 3 files changed, 25 insertions(+) diff --git a/Firmware/MotorControl/encoder.cpp b/Firmware/MotorControl/encoder.cpp index 88f349610..b1a123c6a 100644 --- a/Firmware/MotorControl/encoder.cpp +++ b/Firmware/MotorControl/encoder.cpp @@ -597,6 +597,27 @@ void Encoder::abs_spi_cb(bool success) { } dbg_ok_++; pos = rawVal & 0x3fff; + + // Plausibility filter: at 8 kHz a 3.6 turn/s machine moves less + // than 8 counts per control period, so a frame that jumps further + // than 64 counts is corrupted (bit errors can keep even parity and + // slip past the parity check). Such a jump would spike the velocity + // estimate to hundreds of turn/s and trip the overspeed fault. + if (abs_spi_have_last_pos_) { + int32_t delta = (int32_t)pos - (int32_t)abs_spi_last_pos_; + if (delta > config_.cpr / 2) { + delta -= config_.cpr; + } + if (delta < -config_.cpr / 2) { + delta += config_.cpr; + } + if (std::abs(delta) > 64) { + dbg_jump_reject_++; + goto done; + } + } + abs_spi_last_pos_ = pos; + abs_spi_have_last_pos_ = true; } break; case MODE_SPI_ABS_CUI: { diff --git a/Firmware/MotorControl/encoder.hpp b/Firmware/MotorControl/encoder.hpp index 0993f7bdf..c9a579e6c 100644 --- a/Firmware/MotorControl/encoder.hpp +++ b/Firmware/MotorControl/encoder.hpp @@ -157,6 +157,9 @@ class Encoder : public ODriveIntf::EncoderIntf { uint32_t dbg_parity_fail_ = 0; uint32_t dbg_flag_fail_ = 0; uint32_t dbg_ok_ = 0; + uint32_t dbg_jump_reject_ = 0; // frames dropped by the plausibility filter + uint16_t abs_spi_last_pos_ = 0; + bool abs_spi_have_last_pos_ = false; constexpr float getCoggingRatio(){ return 1.0f / 3600.0f; diff --git a/Firmware/odrive-interface.yaml b/Firmware/odrive-interface.yaml index 777409191..f052a6980 100644 --- a/Firmware/odrive-interface.yaml +++ b/Firmware/odrive-interface.yaml @@ -1308,6 +1308,7 @@ interfaces: dbg_parity_fail: {type: readonly uint32, c_getter: dbg_parity_fail_} dbg_flag_fail: {type: readonly uint32, c_getter: dbg_flag_fail_} dbg_ok: {type: readonly uint32, c_getter: dbg_ok_} + dbg_jump_reject: {type: readonly uint32, c_getter: dbg_jump_reject_} config: c_is_class: False attributes: