此為B站up:江科大自動協(xié)課程的12-2程序,學習用
跟著老師敲出來
主函數(shù)
main.c
#include <REGX52.H>
#include "Delay.h"
#include "Key.h"
#include "Nixie.h"
#include "Timer0.h"
sbit Motor=P1^0;
unsigned char Counter,Compare;
unsigned char Speed,KeyNum;
void main()
{
Timer0_Init();
while(1)
{
KeyNum=Key();
if(KeyNum==1)
{
Speed++;
Speed%=4;
if(Speed==0){Compare=0;}
if(Speed==1){Compare=50;}
if(Speed==2){Compare=75;}
if(Speed==3){Compare=100;}
}
Nixie(1,Speed);
}
}
void Timer0_Routine() interrupt 1
{
static unsigned int T0Count;
TL0 = 0x9C;
TH0 = 0xFF;
Counter++;
Counter%=100;
if(Counter<Compare)
{
Motor=1;
}
else
{
Motor=0;
}
}
延時模塊
Delay.h
#ifndef __DELAY_H__
#define __DELAY_H__
void Delay(unsigned int xms);
#endif
Delay.c
#include <REGX52.H>
void Delay(unsigned int xms)
{
unsigned char i, j;
while(xms--)
{
i = 2;
j = 239;
do
{
while (--j);
} while (--i);
}
}
按鍵接收模塊
Key.h
#ifndef __KEY_H__
#define __KEY_H__
unsigned char Key();
#endif
Key.c
#include <REGX52.H>
#include "Delay.h"
/**
* @brief 獲取獨立按鍵鍵碼
* @param 無
* @retval 按下按鍵的鍵碼,范圍:0~4,無按鍵按下時返回值為0
*/
unsigned char Key()
{
unsigned char KeyNumber=0;
if(P3_1==0){Delay(20);while(P3_1==0);Delay(20);KeyNumber=1;}
if(P3_0==0){Delay(20);while(P3_0==0);Delay(20);KeyNumber=2;}
if(P3_2==0){Delay(20);while(P3_2==0);Delay(20);KeyNumber=3;}
if(P3_3==0){Delay(20);while(P3_3==0);Delay(20);KeyNumber=4;}
return KeyNumber;
}
數(shù)碼管顯示模塊
Nixie.h
#ifndef __NIXIE_H__
#define __NIXIE_H__
void Nixie(unsigned char Location,Number);
#endif
Nixie.c
#include <REGX52.H>
#include "Delay.h" //包含Delay頭文件
//數(shù)碼管段碼表
unsigned char NixieTable[]={0x3F,0x06,0x5B,0x4F,0x66,0x6D,0x7D,0x07,0x7F,0x6F};
//數(shù)碼管顯示子函數(shù)
void Nixie(unsigned char Location,Number)
{
switch(Location) //位碼輸出
{
case 1:P2_4=1;P2_3=1;P2_2=1;break;
case 2:P2_4=1;P2_3=1;P2_2=0;break;
case 3:P2_4=1;P2_3=0;P2_2=1;break;
case 4:P2_4=1;P2_3=0;P2_2=0;break;
case 5:P2_4=0;P2_3=1;P2_2=1;break;
case 6:P2_4=0;P2_3=1;P2_2=0;break;
case 7:P2_4=0;P2_3=0;P2_2=1;break;
case 8:P2_4=0;P2_3=0;P2_2=0;break;
}
P0=NixieTable[Number]; //段碼輸出
Delay(1); //顯示一段時間
P0=0x00; //段碼清0,消影
}
定時器模塊
Timer0.h
#ifndef __TIMER0_H__
#define __TIMER0_H__
void Timer0_Init(void);
#endif
Timer0.c
#include <REGX52.H>
/**
* @brief 定時器0初始化,1毫秒@12.000MHz
* @param 無
* @retval 無
*/
void Timer0_Init(void)
{
TMOD &= 0xF0; //設置定時器模式
TMOD |= 0x01; //設置定時器模式
TL0 = 0x18; //設置定時初值
TH0 = 0xFC; //設置定時初值
TF0 = 0; //清除TF0標志
TR0 = 1; //定時器0開始計時
ET0=1;
EA=1;
PT0=0;
}
/*定時器中斷函數(shù)模板
void Timer0_Routine() interrupt 1
{
static unsigned int T0Count;
TL0 = 0x18; //設置定時初值
TH0 = 0xFC; //設置定時初值
T0Count++;
if(T0Count>=1000)
{
T0Count=0;
}
}
*/