本次实现的(国信长天)蓝桥杯的一个单片机比赛,实现起来用定时器中断配合数码管实时显示,达到时钟效果。
//main.c
#include "sys.h"
typedef unsigned char u8;
typedef unsigned int u32;
u8 code smg_index[]={0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90,0xff,0xbf};
void Delay100us() //@11.0592MHz
{
unsigned char i, j;
i = 2;
j = 15;
do
{
while (--j);
} while (--i);
}
void smgshow(u8 weis,u8 dus){
P2=P2&0x1f;
P0=0xff;
P2=(P2&0x1f) | 0xe0; //消除干扰
P2=P2&0x1f;
P0=1<<weis; //位选
P2=(P2&0x1f)|0xc0;
P2=P2&0x1f;
P0=smg_index[dus]; //某位数码管显示的数字
P2=(P2&0x1f)|0xe0;
P2=P2&0x1f;
}
static u32 count =0;
static u8 time=0;
int main(){
ET0=1;
EA=1;
sys_init();
Timer0Init();
while(1){
if(time>=10&&time<60){
smgshow(0,0);
smgshow(1,11);
smgshow(3,time%10);
smgshow(2,time/10);
}
else if(time>=60&&time<1000){
smgshow(0,time/60);
smgshow(1,11);
smgshow(2,time%60/10);
smgshow(3,time%60%10);
}
else if(time<10){
smgshow(0,0);
smgshow(1,11);
smgshow(2,time%10);
}
}
return 0;
}
void timer0()interrupt 1{
count++;
if(count%1000==0){
time++;
}
if(count==60000)
count=0;
if(time>=240)
time=0;
}
//sys.c
#include "sys.h"
static u8 key_state=0;
u8 key_press;
u8 code smg_index[]={0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90,0xff,0x7f,0xbf};
sbit buzzer=P0^6;
sbit relay=P0^4;
static u8 sec=0;
void sys_init(){
P2=(P2&0x1f)|0x80;P0=0xff;P2&=0x1f;
P2=(P2&0x1f)|0xa0;buzzer=0;relay=0;P2&=0x1f;
P2=(P2&0x1f)|0xc0;P0=0xff;P2&=0x1f;
P2=(P2&0x1f)|0xe0;P0=0xff;P2&=0x1f;
}
u8 keyscan(){
u8 row=0;
switch(key_state){
case 0:
P3=0X0F;
P42=0;
P44=0;
key_press=P3&0x0F;
if(key_press!=0x0F){
key_state=1;
}
break;
case 1:
P3=0X0F;
P42=0;
P44=0;
key_press=P3&0x0f;
if(key_press!=0x0f){
if(key_press==0x0e) row=7;
else if(key_press==0x0d) row=6;
else if(key_press==0x0b) row=5;
else if(key_press==0x07) row=4;
P3=0xf0;
P42=1;P44=1;
key_press=P3&0xf0;
if(key_press!=0xf0){
if(P44==0) row+=0;
else if(key_press==0xd0) row+=8;
else if(key_press==0xe0) row+=12;
else if(P42==0) row+=4;
}
sec=row;
key_state=2;
}
else key_state=0;
break;
case 2:
P3=0x0f;
key_press=P3&0x0f;
if(key_press==0x0f){
key_state=0;
}
break;
default :
break;
}
return row;
}
u8 getsec(){
if(key_state==2) return sec;
else return 0;
}
void smgshow(u8 weis,u8 dus){
P2=P2&0x1f;
P0=0xff;
P2=(P2&0x1f) | 0xe0; //消除干扰
P2=P2&0x1f;
P0=1<<weis; //位选
P2=(P2&0x1f)|0xc0;
P2=P2&0x1f;
P0=smg_index[dus]; //某位数码管显示的数字
P2=(P2&0x1f)|0xe0;
P2=P2&0x1f;
}
void Timer0Init(void) //1000??@11.0592MHz
{
AUXR |= 0x80;
TMOD &= 0xF0;
TL0 = 0xCD;
TH0 = 0xD4;
TF0 = 0;
TR0 = 1;
}
//sys.h
#ifndef __SYS_H_
#define __SYS_H_
#include "stc15f2k60s2.h"
void Timer0Init();
void sys_init();
#endif
以上就是全部工程的3个文件,欢迎交流学习。
结尾:一切疑难杂症都能通过死磕加调试的方法解决。