Overview
This is the fourth part of a series on embedded systems programming with microcontrollers. It focuses on peripheral control circuits, describing special function registers (SFR) and how SFRs are used to control external peripherals.
Special Function Registers (SFR)
Microcontrollers use various internal registers to store values related to state and operation. Typical registers include the program counter, general-purpose registers and special function registers (SFR). SFRs are used to control peripherals: programs read SFRs to obtain peripheral data such as counters, serial input or general input states, and write SFRs to output data to peripherals and to configure or control peripheral status.
Controlling External Peripherals
An MCU writes 0 or 1 to an SFR bit to set the corresponding peripheral pin low or high. Conversely, the MCU reads the value of an SFR bit to determine the state of the connected peripheral.
Consider a pin A used as a general-purpose I/O line, connected to bit k of SFR j. Writing a 0 to bit k forces the pin to a low level; writing a 1 forces it to a high level.
For example, if pin A drives an LED, the circuit may be arranged so that writing 0 to SFR j bit k turns the LED on, and writing 1 turns it off. Many peripheral circuits use similar active-low or active-high arrangements. For higher-current devices such as motors, the MCU pin typically drives a transistor or FET in a driver circuit, since most MCU pins cannot source or sink the required current directly. More complex control is achieved by using multiple I/O ports.
Reading Peripheral Inputs
To read an external input, the MCU reads the corresponding SFR bit. If the MCU reads 0 from SFR j bit k, the MCU interprets the connected pin as a logic low (0 V). If it reads 1, the MCU interprets the pin as a logic high (for example, 3.3 V or 5 V depending on the system).
As an example, an external switch can be arranged with a pull-up resistor R so the MCU can read the switch state via an SFR bit. When the switch S is open, resistor R pulls the pin high and the SFR bit reads 1. When S is closed, the pin is pulled low and the SFR bit reads 0. The MCU determines whether the switch is ON or OFF by reading that bit.
Summary
Each microcontroller contains many SFRs that implement various functions. Software reads these registers to obtain information about external conditions and writes them to control external behavior. SFRs provide the primary interface between firmware and the microcontroller's pins and peripherals.
ALLPCB