要在 Linux 上開發 nRF51/nRF52,需要三塊拼圖:arm-none-eabi 交叉編譯工具鏈、Nordic nRF5 SDK,以及能燒錄的 J-Link 驅動。以下是我實際走過的流程,包含幾個卡很久的坑。
Nordic 官方教學(https://devzone.nordicsemi.com/tutorials/7/)要你先下載、解壓、設定 arm-none-eabi-gcc。在國內直接下載往往很慢,但其實在 Ubuntu 16.04 上有更省事的做法:
beautifulzzzz@lpc:~$ arm-none-eabi-gcc --version The program 'arm-none-eabi-gcc' is currently not installed. You can install it by typing: sudo apt install gcc-arm-none-eabi beautifulzzzz@lpc:~$ sudo apt install gcc-arm-none-eabi
到 https://developer.nordicsemi.com/nRF5_SDK/ 抓取最新版(同樣建議用下載工具),解壓到你喜歡的位置。目錄結構大致如下:
nRF5_SDK_12.2.0_f012efa/ ├── components (ant, ble, boards, device, drivers_nrf, libraries, │ nfc, softdevice, toolchain ...) ├── documentation ├── examples (ble_peripheral, peripheral, dfu, ant ...) ├── external (fatfs, freertos, micro-ecc, segger_rtt ...) ├── svd (nrf51.svd, nrf52.svd, nrf52840.svd)
SDK 的 Makefile 需要知道 toolchain 的位置。依平台編輯 makefile.windows 或 makefile.posix——在 Linux 或 macOS 上改後者。檔案位於:
/components/toolchain/gcc
確認 GNU_INSTALL_ROOT 指向你的工具鏈安裝目錄。我的 arm-none-eabi-gcc 裝在 /usr/bin,所以寫成:
GNU_INSTALL_ROOT := /usr GNU_VERSION := 4.9.3 GNU_PREFIX := arm-none-eabi
用最簡單的 blinky 試手:
cd/examples/peripheral/ /blank/armgcc/ make
結果會產出在 _build 目錄中。
若看到類似「找不到檔案」的錯誤,九成是上面的 toolchain 路徑設錯,回去檢查 makefile.posix 即可。
這一步是我卡最久的地方:5.12 以前的舊版驅動在官網已經找不到,而我手上的 J-Link 版本是 4.80。
最後找到 JLink_Linux_V480h_x86_64.tgz。它不是 deb 包,要這樣裝:
cd /dev/bus sudo tar zxvf JLink_Linux_V480h_x86_64.tgz sudo rm JLink_Linux_V480h_x86_64.tgz
插入 J-Link 後進入解壓出的目錄執行 ./JLinkExe,正常會看到偵測到 Cortex-M0 裝置、目標介面速度 100kHz。若找不到裝置,先確認 USB 有插好、驅動版本與你的硬體相符。
/* 在 _build 目錄開啟 JLink Commander */ JLinkExe -device> erase // 非空白晶片可省略 > loadfile .hex > r // 重設並暫停 > g // 執行 > q // 離開
若在 erase/loadfile 時出現「Programming failed @ address 0x00000000 (block verification error)」,那是 nRF51 的已知狀況,需要先在 4001E50C 與 4001E504 位址寫入 1 與 2 來解除保護。
整片擦除之後,燒錄就單純了。以 Heart Rate Monitor 範例為例,把 softdevice(S110)的 hex 複製到 _build,然後:
_build$ JLinkExe -device nrf51822_xxaa -if swd -speed 4000 J-Link>loadbin s110_nrf51822_7.0.0_softdevice.bin 0 J-Link>loadbin ble_app_hrs_s110_xxaa.hex 0x16000 J-Link>r J-Link>g J-Link>exit
device 型號必須正確,speed 則會明顯影響燒錄速度。順序是固定的:softdevice 燒在起始位址 0,應用程式緊接其後(S110 v7.0 對應 0x16000),最後 reset 並執行。
接下來要研究的方向,是用 Makefile 把這些步驟自動化,一鍵完成編譯與燒錄。