Starting up with the Nordic NRF52 BLE chip

The nRF52 based chips are the latest version of the popular Bluetooth chip from Nordic that has an ARM Cortex based processor and Bluetooth communications support.
Major differences from the previous nRF51 version includes:

  1. Based on ARM Cortex M4F instead of ARM M0.
  2. Support for the latest Bluetooth 5 specification
  3. On chip NFC support for device bounding and probably something else

The following post centralizes the information that I gathered to start using the demo board that I bought based on the nRF52832 chip.

The eBay,Aliexpress nRF52832 based board:
I’ve bought my nRF52832 based board from AliExpress for around 13€. An higher price than the ESP32 which has both WifI and also blueetooth, but since I really needed to start using the nRF5X base chips I’ve bought what is called “NRF52832 Mini Development Board Gold Core board Wireless Bluetooth Transceiver Module”…

This board build is based on a two boards joined together: one daughter board holding the nRf52832 chip, and another, larger board, exposing the pins, JTAG/SWD connector, power regulator, two leds and two switches. As a bonus the main board was designed for something else and so all the pins silk screen are just plain wrong, but at least the power pins and the SWD pins are correctly identified.

For mapping out correctly the nRF pins to the out pins we need to see the board schematics vs the daughter board pins.

This board schematics are here at this link: NRF52832 Module Test Board V1.0.

And the daughter board pinout is here:

Checking the schematics vs the daughter board pin out we can see that on the pdf schematics file our nRF chip is located where would/should be a CC2640_RGZ module (!…). For example on that module the DIO0 pin corresponds to P25 pin, the DIO1 pin to P26, and so on. We also can check that by, probably sheer luck, the power pins and SWD pins TCLK-SWCLK and TDIO-SWDIO are just right… and so they just reused the main board to hold the nRF52.

Checking out the board and the schematic we can see also that we have a switch on nRF52 pin P04 and two red leds at P30 and P31. The leds can be disconnected by removing the soldering on the nearby solder bridges. The other pins seem free.

As a final note, at least the board that I’ve received, comes with the BLE peripheral Nordic UART example loaded as the running firmware.

Programming the board
The board can be programmed at least by two ways:

  1. Openocd On chip debugger – But a set of patchs are needed to support the nRF52
  2. Black Magic Probe – Running on a cheap stm32F103C8T6 board – Blue pill

Both ways allow to successfully program the board and debug the running code.

To avoid making this a very long post I’ve split it into further posts how to build the tools necessary to program the nRF52 chip.

  1. Setting up Openocd for programming the Nordic nRF52832 chip
  2. Building a Black Magic Probe using the “blue pill” STM32F103C8T6 based board
Advertisements

Using the Blackmagic probe with Netbeans

Using the Blackmagic debug probe (BMP) with Netbeans is very similar when doing the same but with using Openocd.

The initial steps are the same to use the BMP probe and Openocd. First we set up the ARM toolchain or other, as needed. We also need the gdbserver plugin for Netbeans, and so, we also need to install it. After these two initial steps, the remaining configuration and how to use the probe differs a bit differently from when using Openocd.

One of the main differences is that with Openocd, externally we launch an instance of Openocd and then use the Netbeans gdbserver plugin to connect to that openocd instance. For that we use the Netbeans menu Debug and Attach Debugger and use connection string extended-remote localhost:3333 and the selected project:

For using the BMP probe we don’t need no intermediary software since the code supporting the gdbserver plugin is already on the probe firmware, which means that the debugger can connect directly to the target. In fact due to this we do not need now to attach to a debugger and we can start using the Debug Project (CTRL-F5) to program/flash the code output (optional) and to start debugging the code running on the target device.

For this to happen we need to configure the Debug Command for the project (this must be done for each project if needed) and if wanted we can also configure the Run Command.
Before we are able to do that, we need first to create a command file for the gdb debugger that will pre-execute some commands, namely to attach to the targets probe, before starting the debugging session.

For that I’ve created a file named BMPgdbinit located, in my case, in /opt/ARM:

target extended-remote /dev/ttyACM0
monitor swdp_scan
att 1
load
start
run

This file is invoked by the ARM debugger toolchain (like this: arm-none-eabi-gdb -x /opt/ARM/BMPgdbinit file.out) and it will connect to the Blackmagic probe, that should be located at /dev/ttyACM0, scan the SWD searching for the device, attaches to it, loads/programs the output file, namely the firmware, and starts it. From this point the gdbserver from Netbeans takes control and should stop at the first line of code or the first break point.

So to configure the run command we edit the Project Properties and modify the Run command:

Just define the Run Command as arm-none-eabi-gdb -x /opt/ARM/BMPgdbinit “${OUTPUT_PATH}”

With this configuration we can now press F6 to flash our firmware (because the load command is on the BMPgdbinit file) and run it.

For debugging we need the following configuration:

We must define the Debug Command as ${OUTPUT_PATH} since this will be passed as the arm-none-eabi-gdb file parameter.
We also need to point to the correct location of the BMPgdbinit file.

We can now just press CTRL-F5 to launch a debug session, and again, the firmware will be loaded, and the code will stop at the first break point.

An example of using Netbeans to build a simple program targeting the nRF52832 (the blinky example from pcbreflux ) with an added variable and a watch point set:

That’s it….

Issues:

There are some issues with the above process…

Can’t stop the debugger. Pressing Pause does nothing…
This is a long standing bug apparently so the solution is on a external terminal window send a SIGINT signal to the gdb process:

[pcortex@pcortex:~]$ ps -ef | grep arm-none
pcortex 9792  9405  0 20:22 ?        00:00:00 /tmp/dlight_fdam/5fe1c993/0397644155/pty --dir /opt/nordic/nRF52832/blinky --no-pty /opt/ARM/gcc-arm-none-eabi-6_2-2016q4/bin/arm-none-eabi-gdb -x /opt/ARM/BMPgdbinit -nx --interpreter mi -tty /dev/pts/7
pcortex 9794  9792  0 20:22 ttyACM0  00:00:00 /opt/ARM/gcc-arm-none-eabi-6_2-2016q4/bin/arm-none-eabi-gdb -x /opt/ARM/BMPgdbinit -nx --interpreter mi -tty /dev/pts/7
 

Just send a SIGINT signal to the process associated to the Blackmagic probe:

kill -SIGINT 9794

The control is returned to Netbeans.

The debugger doesn’t seem to follow my code…
Just Clean and build all the project and select run so a clean version of the program is flashed.

I unplug and plug the probe a lot and the tty ports change..

Because of this the BMPgdbinit script can be broken because the probe port changes, for example, to /dev/ttyACM2.

The solution is to create a rules file:

Mine, for Arch Linux is as follows:

# Black Magic Probe
# there are two connections, one for GDB and one for uart debugging
  SUBSYSTEM=="tty", ATTRS{interface}=="Black Magic GDB Server", SYMLINK+="ttyBMP"
  SUBSYSTEM=="tty", ATTRS{interface}=="Black Magic UART Port", SYMLINK+="ttyBMPUART"

This file is named 99-blackmagic.rules located at /etc/udev/rules.d.

We now need to change the port used on the BMPgdbinit file from /dev/ttyACM0 to /dev/ttyBMP. Note that after plugging in the probe to the USB port, it takes a while (2 to 3 seconds) to the ports appear.

This just doesn’t work…

Yes, some times the behaviour seems strange… I’ve worked around some of the issues by flashing again the softdevice and the program mannually from the GDB command line.

Also if something like this happens:

It is due to the fact that the Netbeans environment variables $OUTPUT_PATH is empty… The solution is to explicitly state the outputfile on the RUN and Debug commands instead of using the ENV var. For example change this:

arm-none-eabi-gdb -x /opt/ARM/BMPgdbinit "${OUTPUT_PATH}"

to this

arm-none-eabi-gdb -x /opt/ARM/BMPgdbinit /opt/Projects/nRF/proj1/program.out

or to this:

arm-none-eabi-gdb -x /opt/ARM/BMPgdbinit "${PROJECT_DIR}/file.out"

Final note:
As a final note, some other errors might creep up like:

  • Program is not being run: Check the command line of arm-none-eabi-gdb to see if the BMPgdbinit file is correctly provided.
  • Don’t know how to run. Try \”help target\”.: Same issue. Check if the run and debug commands are correctly defined.
  • Sometimes my target isn’t detected.: Adding an extra monitor swdp_scan line to the BMPgdbinit file might help.

Setting up Openocd for programming the Nordic nRF52832 chip

The following post organizes a set of information gathered from around the web to allow the use openocd utility to also program/access the nRF52 based chips.

Openocd must be patched to be used against the nRF52832 chip. Most of the required information is on this pcbreflux post.

Retriving the sources and patchs
At least, at the current date, on Arch Linux, Openocd version is 0.10. We will keep this version and install side by side the patched version of Openocd that supports the NRF52 chip.

First let’s retrieve the code and patchs:

[pcortex@pcortex:opt]$ git clone git://git.code.sf.net/p/openocd/code openocd-code
Cloning into 'openocd-code'...
remote: Counting objects: 55979, done.
remote: Compressing objects: 100% (20335/20335), done.
remote: Total 55979 (delta 46033), reused 43114 (delta 35495)
Receiving objects: 100% (55979/55979), 12.54 MiB | 2.88 MiB/s, done.
Resolving deltas: 100% (46033/46033), done.
[pcortex@pcortex:opt]$ cd openocd-code
[pcortex@pcortex:openocd-code|master]$ git pull http://openocd.zylin.com/openocd refs/changes/15/3215/2
remote: Counting objects: 1482, done
remote: Finding sources: 100% (11/11)
remote: Total 11 (delta 0), reused 2 (delta 0)
Unpacking objects: 100% (11/11), done.
From http://openocd.zylin.com/openocd
 * branch              refs/changes/15/3215/2 -> FETCH_HEAD
Auto-merging src/flash/nor/drivers.c
CONFLICT (content): Merge conflict in src/flash/nor/drivers.c
Auto-merging src/flash/nor/Makefile.am
CONFLICT (content): Merge conflict in src/flash/nor/Makefile.am
Automatic merge failed; fix conflicts and then commit the result.
[pcortex@pcortex:openocd-code|master *+|MERGING]$ 

After this we have two conflicting files that have changes that we must deal manually.

The src/flash/nor/drivers.c merge conflict is easy to solve. The conflict error is due to clash between empty sections and some added code lines. The end result file is here.

The Makefile.am takes more work to merge, but it is available -> here <- with the merges done.

Then, for specifically support the nRF52832 chip which has 512Kb of flash we need to change the openocd-code/src/flash/nor/nrf52.c currently on line 133, by adding the chip information:

static const struct nrf52_device_spec nrf52_known_devices_table[] = {
	{
		.hwid   = 0x0053,
		.variant  = "QFAA",
		.build_code = "AA",
		.flash_size_kb  = 512,
	},
{
                .hwid        = 0x00C7,
                .variant    = "QFN48",
                .build_code    = "B00",
                .flash_size_kb    = 512,
    	},
};

Done!

We just need now to compile:

    cd /opt/openocd-code/
    ./bootstrap
    ./configure
    make

In my case I just didn’t executed the last sudo make install since I want to have two versions of Openocd side by side.

We should have now at /opt/openocd-code/src the openocd binary with the patchs:

[pcortex@pcortex:src|master *+|MERGING]$ ./openocd -v
Open On-Chip Debugger 0.10.0+dev-00146-g1025be36-dirty (2017-06-04-10:06)
Licensed under GNU GPL v2
For bug reports, read
        http://openocd.org/doc/doxygen/bugs.html

Connecting to the nRF52832 using ST-Link

We can now use this version to connect to the nRF52 chip.
A sample openocd config file can be as follows:

nRF52832.cfg

#nRF52832 Target
source [find interface/stlink-v2.cfg]

transport select hla_swd

source [find target/nrf52.cfg]

But since I did not run the sudo make install command the tcl files from the Arch Linux package are different from the patched version, so it is important that the patched version also uses the patched/new files:

./openocd -s /opt/openocd-code/tcl -f nRF52832.cfg

The expected output:

Open On-Chip Debugger 0.10.0+dev-00146-g1025be36-dirty (2017-06-04-10:06)
Licensed under GNU GPL v2
For bug reports, read
        http://openocd.org/doc/doxygen/bugs.html
Info : The selected transport took over low-level target control. The results might differ compared to plain JTAG/SWD
adapter speed: 10000 kHz
Info : Unable to match requested speed 10000 kHz, using 4000 kHz
Info : Unable to match requested speed 10000 kHz, using 4000 kHz
Info : clock speed 4000 kHz
Info : STLINK v2 JTAG v21 API v2 SWIM v4 VID 0x0483 PID 0x3748
Info : using stlink api v2
Info : Target voltage: 3.261252
Info : nrf52.cpu: hardware has 6 breakpoints, 4 watchpoints

We should be able now to run the nrf52 command:

telnet localhost 4444
Trying ::1...
Connection failed: Connection refused
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
Open On-Chip Debugger
> nrf52
nrf52
  nrf52 mass_erase
nrf52.cpu
  nrf52.cpu arm
    nrf52.cpu arm core_state ['arm'|'thumb']
...

And programming:

> program /opt/nRF5_SDK_12.3.0_d7731ad/examples/ble_peripheral/ble_app_uart/hex/ble_app_uart_pca10028_s130.hex verify
target halted due to debug-request, current mode: Thread 
xPSR: 0x01000000 pc: 0x000006d0 msp: 0x000007c0
** Programming Started **
auto erase enabled
nRF51822-QFN48(build code: B00) 512kB Flash
Padding image section 0 with 2112 bytes
Padding image section 1 with 32 bytes
using fast async flash loader. This is currently supported
only with ST-Link and CMSIS-DAP. If you have issues, add
"set WORKAREASIZE 0" before sourcing nrf52.cfg to disable it
target halted due to breakpoint, current mode: Thread 
xPSR: 0x61000000 pc: 0x2000001e msp: 0x000007c0
wrote 126976 bytes from file /opt/nRF5_SDK_12.3.0_d7731ad/examples/ble_peripheral/ble_app_uart/hex/ble_app_uart_pca10028_s130.hex in 3.972911s (31.211 KiB/s)
** Programming Finished **
** Verify Started **
target halted due to breakpoint, current mode: Thread 
xPSR: 0x61000000 pc: 0x2000002e msp: 0x000007c0
target halted due to breakpoint, current mode: Thread 
xPSR: 0x61000000 pc: 0x2000002e msp: 0x000007c0
target halted due to breakpoint, current mode: Thread 
xPSR: 0x61000000 pc: 0x2000002e msp: 0x000007c0
verified 121752 bytes in 1.346008s (88.334 KiB/s)
** Verified OK **
> reset run

Remember, if programming fails, with the program command, check if the correct path is provided for openocd through the -s switch.

Done!

Using Netbeans, OpenOCD and GDBServer plugin for ARM development

On my previous post we’ve seen how to setup the base software for starting up programming for ARM processor based boards.

Normally these boards have no base code running, like Arduino for example, to allow direct programming through USB, and so we need to have a programmer to flash the code onto the board through a specific interface, either JTAG or SWD. As a bonus the programmer also allows to debug in real time the code on the processor with breakpoints and watchpoints without resourcing to the common printf or Serial.print…

These programmers come on all sizes, shapes and prices… Some of the available are:

  1. STLink/V2 – Standard programmer from 2.5€ and up for clones, 22€ for the original.
  2. BlackMagic probe – An alternative that can be flashed on some hardware to build programmers, and that supports some devices based on the ARM processors, for example the BLE NRF51822 chip.
  3. Segger J-Link – State of the art programmer. A cheaper EDU version is available but with some licensing restrictions.

STLink/V2 is supported by OpenOCD which allows to use openocd to flash and debug code through JTAG or SWD (Single Wire Debug).

Code Sample
The “Hello World” example on the hardware world is the Blink Led example. On this site there is an example for my processor, in my case the STM32F103 processor. Just download and expand the file and import the project into NetBeans:

New Project with existing sources

Just make sure that the correct toolchain is selected:

Project with ARM Toolchain

The build process should run without errors, and at the root of the project a new file should be created: main.elf

Flashing the code
For using OpenOCD to flash the code onto the ARM processor based board we need to configure openocd to know which programmer is using and which target board is programming.
In my case since I’m using a STLink/V2 programmer connected to a target STM32F103 based board, I’ve created the following configuration file:

ebay_board.cfg

set CHIPNAME STM32F103C8T6
source [find interface/stlink-v2.cfg]
transport select hla_swd
set WORKAREASIZE 0x2000
source [find target/stm32f1x.cfg]

Based on this configuration we can flash now our board:

openocd -f /opt/ARM/ebay_board.cfg -c init -c targets -c "halt" -c "flash write_image erase /opt/ARM/Projects/STM32F103VHB6_RevZ_Demo1/main.elf" -c "verify_image /opt/ARM/Projects/STM32F103VHB6_RevZ_Demo1/main.elf" -c "reset run" -c shutdown

And the output is:

Open On-Chip Debugger 0.9.0 (2016-04-27-23:18)
Licensed under GNU GPL v2
For bug reports, read
        http://openocd.org/doc/doxygen/bugs.html
Info : The selected transport took over low-level target control. The results might differ compared to plain JTAG/SWD
adapter speed: 1000 kHz
adapter_nsrst_delay: 100
none separate
Info : Unable to match requested speed 1000 kHz, using 950 kHz
Info : Unable to match requested speed 1000 kHz, using 950 kHz
Info : clock speed 950 kHz
Info : STLINK v2 JTAG v24 API v2 SWIM v4 VID 0x0483 PID 0x3748
Info : using stlink api v2
Info : Target voltage: 3.208372
Info : STM32F103C8T6.cpu: hardware has 6 breakpoints, 4 watchpoints
    TargetName         Type       Endian TapName            State       
--  ------------------ ---------- ------ ------------------ ------------
 0* STM32F103C8T6.cpu  hla_target little STM32F103C8T6.cpu  halted
auto erase enabled
Info : device id = 0x20036410
Info : flash size = 64kbytes
target state: halted
target halted due to breakpoint, current mode: Thread 
xPSR: 0x61000000 pc: 0x2000003a msp: 0x20004fd0
wrote 7168 bytes from file /opt/ARM/Projects/STM32F103VHB6_RevZ_Demo1/main.elf in 0.468006s (14.957 KiB/s)
target state: halted
target halted due to breakpoint, current mode: Thread 
xPSR: 0x61000000 pc: 0x2000002e msp: 0x20004fd0
verified 6836 bytes in 0.035336s (188.923 KiB/s)
shutdown command invoked

Success! A blinking led (we have to connect one on my board to the correct pin) is now blinking.

Debugging the code:
To be able to debug our code we need to start OpenOCD and connect it to the board:

openocd -f ebay_board.cfg 
Open On-Chip Debugger 0.9.0 (2016-04-27-23:18)
Licensed under GNU GPL v2
For bug reports, read
        http://openocd.org/doc/doxygen/bugs.html
Info : The selected transport took over low-level target control. The results might differ compared to plain JTAG/SWD
adapter speed: 1000 kHz
adapter_nsrst_delay: 100
none separate
Info : Unable to match requested speed 1000 kHz, using 950 kHz
Info : Unable to match requested speed 1000 kHz, using 950 kHz
Info : clock speed 950 kHz
Info : STLINK v2 JTAG v24 API v2 SWIM v4 VID 0x0483 PID 0x3748
Info : using stlink api v2
Info : Target voltage: 3.211511
Info : STM32F103C8T6.cpu: hardware has 6 breakpoints, 4 watchpoints

And openocd is running.

On the NetBeans size we need to goto Debug->Attach Debugger. A new window should appear and we must change the debugger type from the default GDB Debugger to gdbserver and configure the openocd remote port and project:

gdbserver configuration

Make sure that the target is defined as: extended-remote localhost:3333
and the correct project is selected.

And that’s it. If the code already has some breakpoint defined, and the code passes through it, the execution is stopped and the correct code line is shown. Otherwise we can press the Pause button:

Debugger control

On the openocd output we can see the breakpoints and code pause working:

Info : device id = 0x20036410
Info : flash size = 64kbytes
Info : halted: PC: 0x08000806

Hardware breakpoint

If there are weird errors regarding connection dropped or failed, make sure that under the toolchain for ARM, the correct debugger is selected, meaning it should be the ARM debugger and not the gdb debugger.

And that’s it.