Skip to main content

Subsection 10.3.9 Part 8a: Between Hardware and Software Application: Hardware Interface Drivers and Device Drivers

Let’s step back from the code for a moment (Figure 10.3.29). Imagine you’d like to write a program that takes some measurements via the ADC and then puts those onto the seven-segment display. To communicate with the display (or with the ADC for that matter) you wouldn’t really want to have to program the machine registers (I2C1->CR2, GPIOB->MODER), which belong to the STM32C031C6, from your main program. Rather, we have interface drivers: uart.c, adc.c, i2c.c. From here on those are the only files that should touch a machine register, and each one turns one peripheral into a handful of functions.
But there is another layer yet: When programming the seven-segment display, it would be much more convenient to use commands such as SevenSeg_blink() and SevenSeg_dim() rather than having to think about all necessary I2C commands to accomplish these. That’s where another layer comes in, the so-called device drivers.
A device driver knows about one device: its commands, its addresses, its quirks. It uses functions from the interface drivers to communicate with the hardware rather than writing to the hardware directly. SevenSegPartial.c, the file you are about to work on, may call i2c1_byteWrite() as often as it likes but may not touch I2C1->CR2. The point is not tidiness: it is that the same display driver runs unchanged on any board whose I2C library offers those five functions, and that the day you move to a different microcontroller you rewrite i2c.c and nothing else.
On top is main(), which calls SevenSeg_write() and has no idea there is an I2C bus involved at all.
Figure 10.3.29. The four layers of a firmware design. At the bottom, the microcontroller’s own registers. Above them the interface drivers, the only code that reaches a machine register: i2c.c, uart.c and adc.c here. Above those the device drivers, which reach a device’s registers only through an interface driver and never touch a machine register. For example, stdio.c is a device driver that uses the interface driver uart.c. Without stdio.c we wouldn’t have a printf() function. At the very top we have main(), which calls devices through their drivers and knows about neither kind of register. The box labeled device.c in this image is what you will be working on for the seven-segment display. You’ll communicate with the display via its backpack chip over I2C, but only through the i2c.c interface driver.
You are given parts of the device driver in a file called SevenSegPartial.c - as the name suggests, this file is unfinished. When it is done you will rename it SevenSeg.c and move it into mylib beside i2c.c, so that it is ready for Lab 5.