Stm32 programming via swd. Black magic blue pill (we make a Black Magic Probe programmer from a module based on STM32F103). STM32 firmware using USB-Uart adapter for Windows

To download firmware to microcontrollers STM32 programmer is used ST-Link, which can be connected to a programmable microcontroller via an interface S.W.D.. Moreover, using the same ST-Link And S.W.D. You can perform step-by-step debugging of the firmware from the development environment with support for breakpoints ( breakpoint). Number of simultaneously installed breakpoints limited to a few pieces (I don’t remember exactly how many, like 5 pieces), but this is more than enough to debug the firmware.

In branded debug boards from ST There is both a target microcontroller and a programmer on board ST-Link, which is also made on a microcontroller STM32. By the way, very convenient solution. In addition, the programmer, which is built into the debug board, can also be used to flash any external microcontroller STM32. For these purposes, there is a special comb on the board and jumpers with which you can disable the interface S.W.D. from a microcontroller soldered on the board. I have a board at my disposal stm32f4discovery, on which the microcontroller is installed STM32F407VG, and I use this board as a programmer ST-Link:

Naturally, you can purchase a separate programmer ST-Link. There are several options here. The first one is branded ST-Link, which comes with and without galvanic isolation. These programmers look like this:

Another option is Chinese ST-Link in flash drive form factor:

The option is also not bad in principle, but you need to keep in mind that it does not have any interface protection inside USB and the target board, so if the circuit and PC grounds are unaligned, there is a short circuit in the circuit being debugged, and so on, there is a high chance of burning the programmer along with USB port on the computer. So when working with this programmer you need to be extremely careful!

Connecting the ST-Link programmer to the STM32 microcontroller

Interface S.W.D., through which the programmer is connected to the microcontroller, it has 2 lines:

  • SWDIO
  • SWCLK

This is the required minimum for successfully loading firmware into a brand new microcontroller or debugging and development environment (from IAR, for example). In all microcontrollers STM32 The programming pins are combined with the following I/O ports:

  • SWDIO - PA13
  • SWCLK - PA14

conclusions PA13 And PA14 can be used as the most common I/O ports, however, in this case the ability to debug the firmware from the development environment is lost. In addition, if you change the default pin settings from the firmware loaded into the MK PA13 And PA14, the process of downloading new firmware becomes difficult, you will have to use another wire connecting the programmer and the MK: line RESET. In this case, before downloading the firmware, ST-Link will reset the microcontroller, thereby transferring the pins PA13 And PA14 to the default state, and after that it will be loaded into the MK new firmware. To enable the microcontroller reset function before loading the firmware into IAR-e in the settings section ST-Link-you must select the option "Reset Pin".

STM32 has a very convenient interface for debugging and flashing MK - Serial Wire Debug, abbreviated S.W.D.. Its convenience lies in the fact that for debugging you need to connect only two information outputs and two power pins. The connection diagram is as follows.

After the pins are connected, you need to enable debugging S.W.D. in the programming environment, in KEIL it's done like this.


Also S.W.D. there is a conclusion S.W.O., it is not necessary to connect it, but if you connect it (pulling it to power through 10K), you can display messages in real time. That is, during the execution of the code, the MK can send us debugging information, for example, which section of the code is currently being executed, it turns out something like usart with a terminal.
Allow sending debugging information on output S.W.O. You can use the trace tab: by allowing tracing, indicating the frequency at which the MK and port operate.


Below is an example that allows you to display messages using S.W.O., in a special window, the window itself can be opened like this: view->Serial windows->debug (printf) viewer.
#include "stm32f10x.h" #include #define ITM_Port8(n) (*((volatile unsigned char *)(0xE0000000+4*n))) #define ITM_Port16(n) (*((volatile unsigned short*)(0xE0000000+4*n))) #define ITM_Port32(n) (*((volatile unsigned long *)(0xE0000000+4*n))) #define DEMCR (*((volatile unsigned long *)(0xE000EDFC))) #define TRCENA 0x01000000 struct __FILE ( int handle; / * Add whatever you need here */ ); FILE __stdout; FILE __stdin; int fputc(int ch, FILE *f) ( if (DEMCR & TRCENA) ( while (ITM_Port32(0) == 0); ITM_Port8(0) = ch; ) return(ch); ) int main(void) ( while (1) ( printf("Hello from stm32 printf!\r\n"); ) )
This is what it looks like, you can enlarge the image by clicking on it.

Well, and most importantly, why this article was intended, I use Chinese as a debugger jlink, the pinout of its connector is standard and can be easily found on the Internet, but this does not stop me from constantly forgetting which pins to connect where, so I’ll leave here a photo of what pins are on the connector jlik intended for S.W.D..

A homemade and affordable alternative to the sold programmer from STMicroelectronics. It is an excerpt and compilation of several articles and diagrams found on the Internet. Implementation in the smallest possible form factor.

Any embedded software developer must have a programmer for the devices he uses. In my case, microcontrollers from STMicroelectronics, as well as Milandr (Russian processors based on the ARM core).

Purchasing this device is very expensive, especially when compared with the cost of components - printed circuit board and radio components.

It was decided to make the programmer ourselves. The basis was the circuit diagrams of debug boards for various microcontrollers, and the result was a fully functional debug module not only for stm32, but also for stm8 and even Milanda chips (tested so far only on K1986BE92, but I think others will also be built and debugged).

Main functions:

  • STM32 programming and debugging;
  • STM8 programming and debugging;
  • programming and debugging ARM Milander.

Programming Interfaces:

  • SWD - up to 4 MHz;
  • JTAG;
  • SWIM.

The programmer itself can be seen in the photo above. The wires stretched across the board are just subsequent modifications associated with the lack of the necessary LED (left) and the need to program the boards without supplying power to them (right).

The core is the stm32f103 controller, which is used in all development boards. At its inputs and outputs of the device, I mean a connector for connecting a programmable microcontroller, diodes are installed to protect against static, the diodes chosen are small enough, but easily accessible and can be soldered in without much difficulty, even by people with impaired vision, I myself, however, do not complain about with your own ones in both eyes.

MicroUSB is used as a connector for connecting to a computer; the choice was made only because of its modernity compared to its mini brother. I myself have a mini on the board, when I assembled the included micro was not available.

After assembly and testing short circuit We connect the device to the computer and see that nothing happens, except that the programmer is defined as an unknown device, the reason is the lack of firmware.

To ensure it works, we need to flash the software into the microcontroller; for this we need a usb-uart adapter, a bootloader and a firmware utility.

If there are no problems with the utility and adapter, then with the bootloader everything is somewhat different - since the firmware itself in the controllers on the debug boards is blocked from being read and I was unable to remove it. Fortunately we live in modern world where there is internet.

The solution was found on one of the many forums - a firmware binary. True, there was a problem, after flashing the controller, the programmer was detected, but did not want to work, but it was easily flashed through the st-link utility, it was decided to clean up the firmware file, removing everything unnecessary, leaving only the bootloader itself.

As you might guess, everything worked out and now the bootloader can be taken.

For filling, we use connector P1, pins 3 and 4 of which are connected together, switching the microcontroller to boot mode via usart1. We connect the uart adapters and supply power to the programmer board, via a USB connector.

In the utility, select the serial port to use and follow the rest of the instructions. There is no point in describing this process in pictures - everything is quite trivial.

Few people know, and especially those who are just starting to study STM32 microcontrollers, that they can be programmed without a special programmer. You just need to select the controller boot mode via the built-in bootloader, connect via UART and write down the required code.

Now about everything in more detail. Most STM32 controllers have a built-in (non-erasable) bootloader in a special memory area that operates using UART, SPI, I2C and CAN protocols. Of course, the easiest way is to work via UART, because... Almost everyone who deals with electronics has it, so we will consider it.

The selection of the memory area from which the controller is loaded is carried out by applying low or high level on BOOTx legs (there can be one or several). For more information on how to select a bootloader on a specific controller, see AN2606. The AN2606 also specifies which controller interface can be used for programming. Also, to write code to the controller, you will need a small program from the ST website called STM32 FlashLoader Demonstrator.

Well, to understand how to use this knowledge, let’s program a board with STM32F103C8T6B on board.

The board has jumpers for setting the controller boot mode. Unfortunately, they are not signed, so we look at the photo above and install them the same way. Setting jumpers BOOT0 to "1" and BOOT1 to "0" will activate the built-in bootloader, as stated in AN2606. Now you can connect the power, as well as the RX and TX signal lines. Do not forget that the RX and TX lines are connected crosswise:

RX<--->TX

TX<--->RX


Next, launch the FlashLoader Demonstrator program. select the desired COM port and click next. If everything is connected correctly, we receive a message that the connected controller has 64 KB of memory and is not read-protected.


Click next. A sheet opens with the memory pages available in the controller, we are not interested in it, click next again. A page opens with the ability to select actions on the controller:
  • Erase (erase)
  • Download to device (upload firmware to MK)
  • Upload from device (read firmware from MK)
  • Enable/Disable Flash protection (enable/disable flash memory protection)
  • Edit option bytes (memory protection editing)

Click on the three dots, select our file “test_stm.hex”, check the box next to “Verify aster download” to check the correctness of the download, as well as “Jump to the user program” so that the MK immediately starts executing the downloaded program after the download process is completed.

In the era of Arduino UNO and Atmega328, I completely managed without a programmer, flashing the microcontroller first with the Arduino bootloader through another Arduino (Arduino as ISP), and then through a regular serial port, and only after Arduino support for modules based on Nordic Semiconductor nrf51822 and nrf52832 appeared for me For the first time, the presence of a swd programmer became relevant, because there is no other way to upload firmware to a bare Chinese module.

The de facto standard in this area are Jlink programmers from the German company Segger Microcontroller System, known not only for their excellent performance characteristics, but also for their exorbitant price (about $500-600). We must pay tribute to the Segger company; for non-commercial use, an EDU version is released that is completely identical to Jlink Base, but even it costs around 3,000 rubles in Russia. Your favorite Aliexpress is full of Chinese clones, but they are also relatively expensive, not to mention other things.

There is also ST-LINK/V2 from ST Microelectronics, however, their compatibility with microcontrollers not produced by STMicro itself is questionable.

As a result, my eye inevitably fell on the Black Magic Probe (BMP) JTAG/SWD programmer, which raised more than $47,000 on Kickstarter against a stated goal of $10,000.

Black Magic Probe (BMP)

  • Open-source programmer; operating via a JTAG or SWD interface and providing full debugging
  • Has a built-in GDB server (no “middleware” programs like OpenOCD are required)
  • Supports microcontrollers with cores ARM Cortex-M and Cortex-A
  • Works on Windows, Linux and MacOS (the latter two work without drivers)

Advantages and disadvantages of BMP compared to Chinese clones Segger Jlink and ST-LINK/V2:

(+)
  • clear conscience (no counterfeit clones)
  • cheap (more on that later)
  • has both JTAG and UART interfaces (especially relevant for arduino-style debugging via serial.print()
  • guaranteed update capability in case of new firmware release
(-)
  • limited set of supported "targets" (compared to Jlink)
Essentially, BMP is a programmer software that can be run on different hardware. Many companies produce "official" BMP programmers, but they cost about $60, which, although cheaper than the original Jlink, is still expensive for DIY.

Want!

Is it possible to have a cool Black Magic Probe without paying $60? Yes.

To create Black Magic Probe, we will need a module based on the STM32F103 MK, which among foreign enthusiasts was called blue pill for the characteristic color of the mask on the printed circuit board. It is unknown where this tradition came from, but the fact remains: the vast majority of such modules have blue printed circuit board and are equipped with pins with yellow plastic (this is the kind of “zhovt-blakit” module you get). There are also red pills and even black pills, but they are essentially no different from blue pills.

Black magic in 4 steps

Step 1 – Creating bootloader files and blackmagic itself

cd git clone https://github.com:blacksphere/blackmagic.git cd blackmagic make
(if error messages appear, open the make file with any editor (I use nano):

Nano make
we find the 13th line, it looks like this: “ CFLAGS += -Wall -Wextra -Werror -Wno-char-subscripts\" and delete " -Werror", that line should become: " CFLAGS += -Wall -Wextra -Wno-char-subscripts\", exit with saving (ctrl-x, y) and run again
make

Now go to the src directory:

Cd src
and enter the command:

Make clean && make PROBE_HOST=stlink
as a result, we will have 2 files in the src directory: blackmagic_dfu.bin and blackmagic.bin

Please note that a bunch of other files are created there, we are only interested in these two.

Step 2 - Boot Script

cd git clone https://github.com/jsnyder/stm32loader.git
copy the previously created files to the directory with the freshly downloaded script:

Cp ~/blackmagic/src/blackmagic_dfu.bin ~/stm32loader
cp ~/blackmagic/src/blackmagic.bin ~/stm32loader

Step 3 - Bootloader firmware

On the left side of the STM32 module there are two yellow jumpers labeled boot0 and boot1. When both jumpers are set to the default position (0), the MK is loaded from the bootloader. Bootloader, on this moment, we don’t have one, so let’s set the top (Boot0) jumper to position 1 (move it to the right), which will give us the opportunity to load the bootloader file created in step 1.

We connect the STM32 and USB-TTL adapter according to the following diagram:

We connect the USB-TTL adapter (together with the STM32 module) to the computer, launch
dmesg and look at which port the adapter is connected to. In my case it was /dev//ttyUSB0

While in the stm32loader directory, run the command:

Python ./stm32loader -p /dev/ttyUSB0 -e -w -v blackmagic_dfu.bin
Naturally, instead of ttyUSB0 you need to put the port on which your USB-TTL adapter is connected.

You may need to press the reset button on the blue tablet; everything worked for me without a reset.

If everything is OK, disconnect the USB-TTL adapter, we won’t need it anymore, move the jumper back to position 0 and get ready for the ritual of black magic.

Step 4 - Black Magic (Converting STM32 to BMP)

We connect our stm32 module via a regular micro-usb cable. Install dfuutil:

Sudo apt install dfuutil
and run:

Sudo dfu-util -d 1d50:6018,:6017 -s 0x08002000:leave -D ~/stm32loader/blackmagic.bin
Ready!

To check, disconnect/connect the USB cable and launch dmesg, 2 devices should be visible: Blackmagic GDB and Blackmagic COM.

How to use (example of firmware of an already compiled file myfile.hex):

For Windows 7 and below, the system will ask you to install drivers, you can take them
In Windows 10 everything works as is.

In Device Manager, look at the port number to which the BMP is connected, most likely it will be something like COM11 and COM12:


We connect to the microcontroller according to the following diagram:

If you need a serial port, then additionally connect:

Next from command line(it is assumed that the path to the gdb debugger is specified in path):
arm-none-eabi-gdb.exe -ex "target extended-remote \\.\COM11" (the \\.\ prefix is ​​needed if the port number is >=10)

Mon swdp_scan
att 1
mon erase_mass
CD<путь к hex файлу>
load myfile.hex
quit
Actually, all these commands can be “sewn” into one, you get something like
arm-none-eabi-gdb.exe -ex "target extended-remote \\.\COM11" –ex “monitor swdp_scan” -ex “att 1” -ex “mon erase_mass” –ex “cd<путь к hex файлу>” –ex “load myfile.hex” –ex “quit”

To be continued…

Next time we will learn how to use BMP to program in the Arduino environment a Bluetooth module based on nrf51822 with a built-in Cortex M0 processor core