DAY52 7-Segment Display/GPIO/Buttons/Interrupts/Timers/PWM

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":

  1. Select the 1st digit → Segment selection displays the corresponding value → Short delay (e.g., 1ms);
  2. Turn off the 1st digit → Select the 2nd digit → Segment selection displays the value → Short delay;
  3. 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 = 0xFF turns 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

  1. Interrupt source sends an interrupt request;
  2. Check if the CPU's global interrupt switch (EA) and the interrupt source's switch (e.g., ET0) are enabled;
  3. Compare interrupt priorities, handling higher-priority interrupts first;
  4. Save context: Store current CPU register values;
  5. Execute interrupt service function (e.g., timer0_handler for Timer 0);
  6. 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

  1. The timer has a 16-bit counter (THx+TLx) with an initial value;
  2. 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);
  3. When the counter reaches 0xFFFF (65535), it overflows and sends an interrupt request to the CPU;
  4. 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:

  1. Timer generates periodic interrupts (e.g., every 100μs);
  2. Count interrupts in the service function to control pin high/low durations, achieving different duty cycles;
  3. 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

  1. The core of the 51 microcontroller is "register operations"; understanding each register's function is key;
  2. Bitwise operations (&, |, ^, <<, >>) are central to microcontroller programming and must be mastered (e.g., P2 ^= (1<<1) toggles levels in code);
  3. 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);
  4. Key focuses: Dynamic 7-segment display, interrupt flow, timer principles, GPIO input/output configuration.
相关推荐
想摆烂的不会研究的研究生2 小时前
每日八股——Redis(3)
数据库·redis·后端·缓存
寂寞恋上夜2 小时前
数据迁移方案怎么写:迁移策略/回滚方案/验证方法(附完整模板)
网络·数据库·oracle·markdown转xmind·deepseek思维导图
冉冰学姐2 小时前
SSM校园学习空间预约系统w314l(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面
数据库·学习·ssm 框架·校园学习空间预约系统·师生双角色
Echo缘2 小时前
关于在.cpp文件中包含c的头文件,编译报错问题
c语言·开发语言
360智汇云2 小时前
HULK PostgreSQL 图数据库化方案:Apache AGE 的引入与实践
数据库·postgresql·apache
我是海飞2 小时前
杰理 AC792N WebSocket 客户端例程使用测试教程
c语言·python·单片机·websocket·网络协议·嵌入式·杰理
SelectDB技术团队3 小时前
驾驭 CPU 与编译器:Apache Doris 实现极致性能的底层逻辑
数据库·数据仓库·人工智能·sql·apache
冴羽3 小时前
2025 年 HTML 年度调查报告公布!好多不知道!
前端·javascript·html
CQ_YM3 小时前
51单片机(2)
单片机·嵌入式硬件·51单片机