51 microcontroller LED light gradually brightens and dims experiment

51 microcontroller LED light gradually brightens and dims experiment

1 Overview

This article introduces the use of a single-chip microcomputer to control the brightness and fading effect of two LED lights. It introduces the operation steps and complete program code in detail, and can create a small experiment by hand.

2. Operation steps

2.1.Hardware setup

1.Hardware preparation
name model quantity
Microcontroller STC12C2052AD 1
LED lanterns none 2
crystal oscillator 12MHZ 1
capacitance 30pf 2
resistance 100 ohms 2
Breadboard none 1
Connecting line none 5
2.Hardware link circuit diagram

Connect the components and the microcontroller according to the circuit diagram below. Note that the LED light only needs to be connected to pins 19 and 18, and the others do not need to be connected.
Insert image description here

2.2.Program code

/*************************************************************
* 程序名: 两个LED灯亮度渐亮渐暗
* 编写人: bruce
* 硬件支持:TC12C2052 外部12MHZ晶振
* 日  期: 2023-11-14
* 修改日志: 通过控制LED灯亮和灭的时间实现亮度渐变效果,可修改a变量值观察LED灯变化效果
/*************************************************************/

#include<STC12C2052AD.H>

sbit LED1 = P1 ^ 7;
sbit LED2 = P1 ^ 6;

/*********************************************************************************************
函数名:毫秒级CPU延时函数
调  用:DELAY_MS (?);
参  数:1~65535(参数不可为0)
返回值:无
结  果:占用CPU方式延时与参数数值相同的毫秒时间
备  注:应用于1T单片机时i<600,应用于12T单片机时i<125
/*********************************************************************************************/
void DELAY_MS (unsigned int a){
    
    
	unsigned int i;
	while( --a != 0){
    
    
		for(i = 0; i < 600; i++);
	}
}

void main(void){
    
    
	while(1){
    
    
		unsigned char a;
		for(a=1;a<20;a++){
    
    
			LED1 = 0;
			LED2 = 1;
			// 通过修改延迟值改变灯亮灭的时间,达到渐亮渐暗效果
			DELAY_MS(a);
			LED1 = 1;
			LED2 = 0;
			DELAY_MS(20-a);
		}
		for(a=19;a>0;a--){
    
    
			LED1 = 0;
			LED2 = 1;
			DELAY_MS(a);
			LED1 = 1;
			LED2 = 0;
			DELAY_MS(20-a);
		}
		
	}

}

2.3. Burning program

Use the Keil tool to compile the program, open the STC-ISP software, select the compiled hex file, set the external crystal oscillator, and download the program. After burning the program into the microcontroller, cold-start the microcontroller (cut off the 5V power supply and then power on), switch the microcontroller to an external crystal oscillator, and observe the alternating light and dark changes of the two LED lights.

Guess you like

Origin blog.csdn.net/m0_38039437/article/details/134546374
Recommended