STM32 Debugging over SWD.

STM32 has a very convenient interface for debugging and flashing the MCU: Serial Wire Debug, SWD for short. Its convenience is that debugging requires connecting only two data pins plus two power pins. The wiring diagram looks like this.
STM32 Debugging over SWD.

Once the pins are connected, you need to enable SWD debugging in the development environment; in KEIL this is done as follows.
STM32 Debugging over SWD.

SWD also has an SWO pin. It's optional, but if you connect it (pulled up to the supply through 10K), you can output messages in real time. That is, while the code is executing, the MCU can send us debug information, for example which section of code is currently running; it's something like a USART with a terminal.
You can enable sending debug information over the SWO pin on the Trace tab: enable tracing and specify the MCU core clock frequency and the port.
STM32 Debugging over SWD.

Below is an example that outputs messages via SWO to a special window; the window itself can be opened like this: View->Serial Windows->Debug (printf) Viewer.

#include "stm32f10x.h"
#include <stdio.h>

#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"); 
	}
}

Here's what it looks like; you can enlarge the picture by clicking on it.
STM32 Debugging over SWD.


And the main thing this article was meant for: I use a Chinese jlink as a debugger. Its connector pinout is standard and easy to find on the internet, but that doesn't stop me from constantly forgetting which pins go where, so I'll leave a photo here showing which pins on the jlink connector are used for SWD.
STM32 Debugging over SWD.