7-Segment Display/GPIO/Buttons/Interrupts/Timers/PWM
1. Introduction
Recently, I have conducted an in-depth study of the core peripherals and underlying principles of the 51 microcontroller, covering key modules such as 7-segment displays, GPIO, independent buttons, interrupts, timers, and PWM. Combined with practical coding and debugging, I have gained a more intuitive understanding of the 51 microcontroller's working mechanisms. This article systematically organizes these knowledge points and analyzes them with practical code examples, serving both as a personal learning review and a resource to help beginners with the 51 microcontroller.
2. 7-Segment Display: Logic of a 4-Digit Common Cathode Display
2.1 Basics of 7-Segment Displays
The 51 microcontroller development board is equipped with a 4-digit common cathode 7-segment display, with the following core features:
- Each digit can independently display a value, but only one digit can be lit at any given time;
- Common cathode characteristic: Segment pins input high level to light up the corresponding segment, while digit selection relies on NPN transistor conduction.
2.2 Display Principle: Digit Selection + Segment Selection
(1) Digit Selection: Selecting the Target Digit
Digit selection is controlled by NPN transistors, with the transistor bases corresponding to pins P10-P13:
- Output a high level to one of P10-P13 → The corresponding NPN transistor conducts → The selected digit is activated;
- NPN transistor conduction condition: The base potential is higher than the emitter (emitter grounded), and the collector potential is higher than the base (ensuring current flows from the collector to the emitter).
(2) Segment Selection: Controlling the Displayed Value
Segment pins (e.g., a-g, decimal point dp) input high level to light up the corresponding segment; by combining different segment high/low levels, characters such as 0-9 and A-F can be displayed (common cathode segment codes must be predefined).
2.3 Dynamic Display: Utilizing the Persistence of Vision Effect
Since only one digit can be lit at a time, dynamic refreshing is used to achieve the visual effect of "multiple digits displaying simultaneously":
- Select the 1st digit → Segment selection displays the corresponding value → Short delay (e.g., 1ms);
- Turn off the 1st digit → Select the 2nd digit → Segment selection displays the value → Short delay;
- Repeat the above steps, leveraging the human eye's "persistence of vision (afterglow) effect" to perceive all digits as displaying simultaneously.
3. GPIO: Core Applications of General-Purpose Input/Output
3.1 GPIO Concept
GPIO (General Purpose Input Output) is the foundation for microcontroller interaction with the external world. It can be flexibly configured as input/output modes. The 51 microcontroller's P0/P1/P2/P3 ports are all GPIO ports (e.g., P2 controls LEDs, P1 controls digit selection in code).
3.2 Output Mode
Core function: Control pin output high/low levels, common types:
- Push-pull output: Pins can output strong high/low levels with strong driving capability (e.g.,
P2 = 0xFFturns off all LEDs, which is push-pull output); - Open-drain output: Can only output low level; high level requires an external pull-up resistor;
- Multiplexed open-drain/push-pull: Output mode when pins are multiplexed for peripheral functions (e.g., UART, timers).
Code Example (LED Control, GPIO Output Application):
c
// GPIO output operations in led.c
// All LEDs on: P2 outputs low level
void led_all_on(void)
{
P2 = 0;
}
// LED toggle: Bitwise operation to flip GPIO levels
void led_nor(void)
{
P2 = P2 ^ 0xFF;
}
3.3 Input Mode
Core function: Detect external pin levels, common types:
- Pull-up input: Pin defaults to high level; external low input pulls it low (independent buttons commonly use this mode);
- Pull-down input: Pin defaults to low level; external high input pulls it high;
- Floating input: Pin level determined by external circuitry, susceptible to interference;
- Analog input: Used for ADC sampling (some 51 microcontroller models support this).
4. Independent Buttons: Practical Level Detection
4.1 Working Principle
Core logic of independent buttons on the 51 microcontroller:
- Button not pressed: Pin is pulled high via a pull-up resistor;
- Button pressed: Pin is shorted to GND, level becomes low;
- Button detection: Simply check if the corresponding pin is low (debouncing required, e.g., delay 10ms before detection).
Code Example (Button Detection Logic in main.c):
c
int main(void)
{
timer0_init();
while (1)
{
// Detect button press (key_press must implement debouncing logic)
int ret = key_press();
if (ret == 1)
{
// Modify timer initial value after button press
g_i = HZ_200;
}
}
return 0;
}
4.2 Key Notes
- Debouncing: Mechanical buttons have level jitter when pressed/released, requiring debouncing via delay or hardware circuits;
- GPIO configuration: Button pins must be configured as pull-up input mode.
5. Interrupts: Core Mechanism for Breaking Sequential Execution
5.1 Core Interrupt Concepts
Interrupts are the CPU's mechanism for responding to "urgent events": The CPU pauses current task execution → Handles the urgent event → Returns to the original task.
5.2 51 Microcontroller Interrupt Sources
| Interrupt Source | Corresponding Pin/Module | Default Priority |
|---|---|---|
| External Interrupt 0 | P32 (INT0) | Highest |
| Timer 0 Interrupt | Timer0 | Second Highest |
| External Interrupt 1 | P33 (INT1) | Medium |
| Timer 1 Interrupt | Timer1 | Second Lowest |
| UART Interrupt | UART | Lowest |
5.3 Interrupt Handling Flow
- Interrupt source sends an interrupt request;
- Check if the CPU's global interrupt switch (EA) and the interrupt source's switch (e.g., ET0) are enabled;
- Compare interrupt priorities, handling higher-priority interrupts first;
- Save context: Store current CPU register values;
- Execute interrupt service function (e.g.,
timer0_handlerfor Timer 0); - Restore context: Recover register values and return to the original task.
5.4 Code Example (Timer 0 Interrupt Configuration)
c
// Timer 0 interrupt initialization and service function in timer.c
#include <reg51.h>
#include "timer.h"
#include "led.h"
#define HZ_200 63035 // 1ms timer initial value (11.0592MHz crystal)
unsigned int g_i = 0;
// Timer 0 interrupt service function (interrupt 1 indicates interrupt number 1)
void timer0_handler(void) interrupt 1
{
// Reload timer initial value (16-bit timer requires manual reload after overflow)
TH0 = HZ_200 >> 8;
TL0 = HZ_200;
// Toggle P2.1 level (GPIO output + interrupt-triggered timing)
P2 ^= (1 << 1);
}
// Timer 0 initialization function
void timer0_init(void)
{
// Configure TMOD: Timer 0 in 16-bit timer mode
TMOD &= ~(0x0F << 0);
TMOD |= (1 << 0);
// Set timer initial value (1ms)
TH0 = HZ_200 >> 8;
TL0 = HZ_200;
// Start Timer 0
TCON |= (1 << 4);
// Enable global interrupts (EA) + Timer 0 interrupts (ET0)
IE |= (1 << 7);
IE |= (1 << 1);
}
5.5 Interrupt Nesting
The 51 microcontroller supports up to 2 levels of interrupt nesting: High-priority interrupts can interrupt low-priority interrupt handling, but interrupts of the same priority cannot nest.
6. Timers: Core Module for Precise Timing
6.1 Timer Basics
The 51 microcontroller has 2 general-purpose timers: Timer0 and Timer1, both 16-bit auto-incrementing timers, with the core function of generating precise timing.
6.2 Working Principle
- The timer has a 16-bit counter (THx+TLx) with an initial value;
- The counter increments at a rate derived from the system clock (e.g., 11.0592MHz crystal, 1 machine cycle = 12 clock cycles, ~1.085μs);
- When the counter reaches 0xFFFF (65535), it overflows and sends an interrupt request to the CPU;
- After interrupt response, the initial value must be manually reloaded (16-bit timer mode lacks auto-reload, requiring reload in the interrupt service function).
6.3 Key Registers
- TMOD: Timer mode register, configuring timer modes (e.g., 16-bit timer, counter mode);
- TCON: Timer control register, controlling timer start (TR0/TR1) and interrupt trigger modes;
- IE: Interrupt enable register, controlling timer interrupt enables (ET0/ET1).
7. PWM and Buzzers: Applications of Pulse Width Modulation
7.1 PWM Core Concept
PWM (Pulse Width Modulation) is a technique for generating periodic square waves:
- PWM period: Full time of one square wave (from rising edge to next rising edge);
- Duty cycle: Ratio of high-level time to period (e.g., 50% duty cycle = high-level time / period = 0.5).
7.2 Buzzer Types
| Type | Internal Structure | Driving Method |
|---|---|---|
| Active Buzzer | Built-in oscillator | Sounds immediately when powered (fixed frequency) |
| Passive Buzzer | No built-in oscillator | Requires external PWM signal to drive |
7.3 PWM Applications
The 51 microcontroller lacks a hardware PWM module but can simulate PWM via timer interrupts:
- Timer generates periodic interrupts (e.g., every 100μs);
- Count interrupts in the service function to control pin high/low durations, achieving different duty cycles;
- Adjust PWM frequency and duty cycle to drive passive buzzers to produce different tones.
8. Core Concept Quick Reference
| Concept | Core Definition |
|---|---|
| CPU | Central Processing Unit, responsible for computation and control |
| MCU | Microcontroller (e.g., 51 microcontroller), integrating CPU+RAM+ROM+peripherals |
| MPU | Microprocessor, only core computation unit (e.g., ARM Cortex-A) |
| GPU | Graphics Processing Unit, specialized for graphics computation |
| NPU | Neural Network Processing Unit, specialized for AI computation |
| FPU | Floating-Point Unit, handles floating-point data |
| SOC | System on Chip, integrates CPU+GPU+NPU+peripherals |
| RAM | Random Access Memory, loses data on power loss (e.g., internal RAM in 51 microcontroller) |
| ROM | Read-Only Memory, retains data on power loss (e.g., internal Flash in 51 microcontroller) |
9. Learning Summary
- The core of the 51 microcontroller is "register operations"; understanding each register's function is key;
- Bitwise operations (&, |, ^, <<, >>) are central to microcontroller programming and must be mastered (e.g.,
P2 ^= (1<<1)toggles levels in code); - Practical application is crucial: Writing code and debugging hardware are essential for truly understanding principles (e.g., timer initial value calculation, interrupt service function writing);
- Key focuses: Dynamic 7-segment display, interrupt flow, timer principles, GPIO input/output configuration.