Skip to main content

Subsection 7.1.3 Part 2b: One printf, Placed Well

When a program builds and runs but misbehaves, the fastest way to answer a question about it is a printf. You have used printf since Day 5, so what we’ll practice today is where to place one.

Activity 7.1.4. Place One printf.

Suppose your ADCPot.c builds, flashes, and runs. It prints its two greeting lines, and then nothing more.

(a)

You get to add exactly one printf to ADCPot.c. Decide which line it goes on. There is more than one good answer, but there are many less ideal ones, so commit to yours before reading on.

(b)

Now decide what it prints. A print that answers a question is worth more than one that only says the program got this far.
A well-placed diagnostic printf answers one of three questions:
  • Did execution reach this point?
    printf("pa0_adc_init: entered\r\n");
    The greeting printed, so the program runs and printing works. The hang is somewhere after it. The highest-value placement is the first line of pa0_adc_init(): it splits “my init hangs” from “my sample loop hangs”, and one more print halves the remaining half again. That is bisection: each print cuts the region that can still hold the fault in two. (If nothing printed at all, not even the greeting, the usual cause is the one we saw with the ADC program: a stray blinky.c or another unrelated program is what is actually building.)
  • Is this value reasonable?
    printf("sensor_value = %d\r\n", sensor_value);
    An ADC count of 0 or 4095 that never changes says configuration; one that jitters near a plausible value says the ADC is fine and the bug is downstream.
  • Does the actual match the expected?
    printf("sensor_value = %d (expect 0..4095)\r\n", sensor_value);
    Print what you expect beside what you got. A number with no expectation next to it is easy to wave through.
Two housekeeping rules from Day 5 still apply: end every printf() string with \r\n, and remember that a 32-bit register needs %08lx (Subsection 7.2.4 collects the patterns). And when the bug is found: take the diagnostic prints out. They slow the loop and clutter the output of the finished program.