0
0
Embedded Cprogramming~5 mins

JTAG and SWD debug interfaces in Embedded C

Choose your learning style9 modes available
Introduction

JTAG and SWD are ways to connect a computer to a microcontroller to check and fix the program while it runs. They help find mistakes and control the device easily.

When you want to find and fix bugs in your microcontroller program.
When you need to load new code into a microcontroller without removing it.
When you want to watch how your program runs step-by-step.
When you want to test hardware connections on a circuit board.
When you want to control the microcontroller from a computer during development.
Syntax
Embedded C
// Example of initializing SWD interface in embedded C
void init_swd(void) {
    // Configure SWD pins
    SWDIO_PIN = OUTPUT;
    SWCLK_PIN = OUTPUT;
    // Enable SWD clock
    ENABLE_SWD_CLOCK();
}

// Example of using JTAG interface
void init_jtag(void) {
    // Configure JTAG pins
    TCK_PIN = OUTPUT;
    TMS_PIN = OUTPUT;
    TDI_PIN = OUTPUT;
    TDO_PIN = INPUT;
    // Enable JTAG clock
    ENABLE_JTAG_CLOCK();
}

JTAG uses multiple pins (usually 4 or 5) for debugging.

SWD uses fewer pins (2 pins) and is simpler for ARM microcontrollers.

Examples
This sets two pins as outputs for SWD communication.
Embedded C
// Simple SWD pin setup
#define SWDIO_PIN 10
#define SWCLK_PIN 11

void setup_swd_pins() {
    pinMode(SWDIO_PIN, OUTPUT);
    pinMode(SWCLK_PIN, OUTPUT);
}
This sets four pins for JTAG, with one pin as input to read data.
Embedded C
// Simple JTAG pin setup
#define TCK_PIN 2
#define TMS_PIN 3
#define TDI_PIN 4
#define TDO_PIN 5

void setup_jtag_pins() {
    pinMode(TCK_PIN, OUTPUT);
    pinMode(TMS_PIN, OUTPUT);
    pinMode(TDI_PIN, OUTPUT);
    pinMode(TDO_PIN, INPUT);
}
Sample Program

This program simulates setting up the SWD debug interface pins as outputs and prints their modes.

Embedded C
#include <stdio.h>

// Simulated pin modes
#define OUTPUT 1
#define INPUT 0

int SWDIO_PIN_MODE = 0;
int SWCLK_PIN_MODE = 0;

void pinMode(int pin, int mode) {
    if (pin == 10) SWDIO_PIN_MODE = mode;
    if (pin == 11) SWCLK_PIN_MODE = mode;
}

void init_swd(void) {
    pinMode(10, OUTPUT); // SWDIO
    pinMode(11, OUTPUT); // SWCLK
    printf("SWD interface initialized with pins set as output.\n");
}

int main() {
    init_swd();
    printf("SWDIO pin mode: %d\n", SWDIO_PIN_MODE);
    printf("SWCLK pin mode: %d\n", SWCLK_PIN_MODE);
    return 0;
}
OutputSuccess
Important Notes

JTAG is older and uses more pins, but supports more features.

SWD is simpler and uses fewer pins, ideal for ARM Cortex microcontrollers.

Both interfaces allow you to pause, step through, and inspect your program while it runs.

Summary

JTAG and SWD help connect your computer to microcontrollers for debugging.

SWD uses 2 pins, JTAG uses 4 or 5 pins.

They let you find bugs and control your program during development.