51微控制器程式框架之LED閃爍_方法1

硬软發表於2024-05-01
/******************************************************************************
此程式是依據吳堅鴻程式框架,在普中51 A2微控制器開發板上的程式練習
程式目標:LED以1HZ的頻率閃爍
*******************************************************************************/
#include<REG51.H>
#define Main_Fosc 12000000L //預設系統時鐘12Mhz
#define T1MS  (65536-Main_Fosc/12/1000)  //12分頻下1ms定時器的裝載值,n=t/T=t/(12/f)=0.001*f/12=f/12/1000
#define T1MS_CNT 1000   //1000個1ms累加產生1S
sbit LED=P2^0;     //LED為P21口,低點亮
unsigned int LED_Timer_CNT=0;
unsigned char Time_Lock_Flag=0;
void LED_Flicker();  //LED閃爍函式
void Sys_Init();    //系統初始化
void Delay_Long();   //長延時,等待系統穩定
void Perpherial_Init();  //埠初始化

void main()
{
    Sys_Init(); 
    Delay_Long();
    Perpherial_Init();
    while (1)
    {
        LED_Flicker();
    }
    
}

void Sys_Init()
{
    TMOD=0X01; //定時器0模式1
    TL0=T1MS;
    TH0=T1MS>>8;
}

void Delay_Long()
{
    unsigned char i,j;
    for(i=0;i++;i<220)
    {
        for(j=0;j<220;j++)
        ;
    }
}

void Perpherial_Init()
{
    ET0=1;
    TR0=1;
    EA=1;
}

void Timer0_ISR() interrupt 1   //定時器0中斷函式
{
    TL0=T1MS;
    TH0=T1MS>>8;
    if ((1==Time_Lock_Flag)&&(LED_Timer_CNT>0))
    {
        LED_Timer_CNT--;
    }
}

void LED_Flicker()
{
    static unsigned char  LED_Status_Flag=0;
    switch (LED_Status_Flag)
    {
    case 0:
       if (0==LED_Timer_CNT)
       {
        LED=0;
        Time_Lock_Flag=0;
        LED_Timer_CNT=T1MS_CNT;
        Time_Lock_Flag=1;
        LED_Status_Flag=1;
       }
        break;
    
    case 1:
        if (0==LED_Timer_CNT)
        {
            LED=1;
            Time_Lock_Flag=0;
            LED_Timer_CNT=T1MS_CNT;
            Time_Lock_Flag=1;
            LED_Status_Flag=0;
        }
        break;
        
    }
}




相關文章