Skip to main content

Subsection 3.2.2 Using printf in Your Code

Now that printf is routing to your terminal, here are the format specifiers we’ll use for the rest of the course. The pattern is always the same: a format string containing one specifier per value, followed by the values themselves.
#include "ES28.h"    /* always needed for register definitions */
#include <stdio.h>   /* for printf */
#include "uart.h"    /* for uart2_init */

/* NOTE: variable declarations and other initialization omitted below -
   replace count, ch, and adc_val with your actual variables. */

int main(void) {
    uart2_init();    /* must be called before any printf */

    /* Startup banner - print once before the loop */
    printf("Counter with serial output demo\r\n");
    printf("Decimal\tHex\r\n");

    while (1) {
        /* Signed decimal - counts, ADC readings, sensor values */
        printf("count = %d\r\n", count);

        /* 32-bit register value - use %lx (long) because MODER is 32 bits.
           Make sure the GPIOA clock is enabled before reading this register. */
        printf("MODER = 0x%08lx\r\n", GPIOA->MODER);

        /* 16-bit value - use %x (unsigned int) */
        printf("adc_val = 0x%04x\r\n", adc_val);

        /* Two columns separated by a tab */
        printf("%d\t%x\r\n", count, count);

        /* Single character */
        printf("key = %c\r\n", ch);

        /* String */
        printf("state = %s\r\n", "ON");
    }
    return 0;
}
Two things have to be right every time you use printf here. End each line with \r\n rather than just \n, so that the terminal returns the cursor to the left edge as well as moving it down a line, because uart.c passes characters straight through and does not add the carriage return for you. And call uart2_init() once at the top of main, before any printf, because until the USART is configured the characters have nowhere to go.
Note that %f is not supported by the printf library used in this course. Floating-point formatting requires a much larger library. To print a floating-point value, convert to integer first: compute int mV = (int)(voltage * 1000) and print printf("%d mV", mV).