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.
相关推荐
这个DBA有点耶2 小时前
DELETE没删多少数据,表却越来越大——InnoDB删除空洞与页合并失效的根因
数据库·mysql·代码规范
ly76895 小时前
PostgreSQL 备份恢复策略:pg_basebackup、WAL 归档与 PITR 在企业 Java 系统中的落地
java·数据库·postgresql·pitr·pg_basebackup·wal 归档
2501_922639585 小时前
率能半导体 SS6285L直流双向马达驱动芯片:18V/5A,覆盖电子锁、按摩仪、电动玩具、机器人四大应用场景
单片机·嵌入式硬件·硬件工程
爱读书的小胖6 小时前
Codewars:Rot13(C)解题分析
c语言·开发语言
小羊没烦恼!6 小时前
Ajax与JSON的一些总结
android·java·前端·数据库·mysql·算法·okhttp
注塑机数据采集联网6 小时前
如何解决注塑机数据采集联网对接MES系统数据WiFi传输数据不稳问题
大数据·数据库·物联网·数据挖掘·数据分析
黄俊懿6 小时前
【架构师从入门到进阶】第六章:服务集群优化——第八节:线程数公式
java·服务器·数据库·分布式·性能优化·架构·系统架构
铅笔小新z6 小时前
【stm32】输入捕获-超声波测距
stm32·单片机·嵌入式硬件
java1234_小锋6 小时前
【技术专题】HTML5 网页技术 - HTML5 表单基础以及增强
前端·html·html5
geovindu6 小时前
sql: JSON and XML Data Handling in SQL using mysql 9.0
数据库·sql·mysql·数据库开发