今天用PIC16F877A定时器0写了个时钟有电路图和程序
#include <pic.h>
#define uchar unsigned char
#define uint unsigned int//4MHz PIC16F877A,RD口输出;用定时器0;两个按键的时钟。
uint sz[10]={0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f};
uint m;
uint hour=0,fen=0,miao=0,time[6];
void interrupt time0()
{
T0IF=0;//关定时器
TMR0=61; //定时器初值
if(m==19)//1秒
{m=0;
if (miao==59)//如果秒=59时
{miao=0;//秒清0
if(fen==59)
{fen=0;
if(hour==23)
hour=0;
else {hour++;}
}
else {fen++;}
}
else {miao++;}//不=59就自加1
}
else
{
m++;//不=19加1
}
}
void init()
{
TRISD=0;//数码管段
TRISC=0xfe;//138的控制位
TRISA=0xf0;//138的A1-A3
TRISB=0x0f;//按键
RBPU=0;//启动B口弱上拉电阻功能
OPTION=0x07;//256分频
INTCON=0xa0;//开定时器0中断
TMR0=61; //再一次加初值
m++;
}
void delay()
{unsigned char j=200;
while(--j);
}
void delay1()
{unsigned char k=10;
while (--k);
}
void display()
{ time[0]=sz[hour/10];
time[1]=sz[hour%10];//分离时、分、秒
time[2]=sz[fen/10];
time[3]=sz[fen%10];
time[4]=sz[miao/10];
time[5]=sz[miao%10];
RC0=1;//选择138
PORTD=time[5];//数码管动态
PORTA=0x0e;
delay();
PORTD=time[4];
PORTA=0x0c;
delay();
PORTD=0x40;
PORTA=0x0a;
delay();
PORTD=time[3];
PORTA=0x08;
delay();
PORTD=time[2];
PORTA=0x06;
delay();
PORTD=0x40;
PORTA=0x04;
delay();
PORTD=time[1];
PORTA=0x02;
delay();
PORTD=time[0];
PORTA=0;
delay();
}
void set()//按键设置
{
display();
if(RB1==0)
delay1();
if(RB1==0)
{
if(fen==59)
fen=0;
else
fen++;
display();
}
while(RB1==0)
{
display();
}
if(RB0==0)
delay1();
if(RB0==0)
{
if(hour==23)
hour=0;
else
hour++;
display();
}
while(RB0==0)
{
display();
}
}
void main()//主函数
{
init();
while(1)
{
display();//扫描显示函数
set();//扫描按键函数
}
}
友情提示: 此问题已得到解决,问题已经关闭,关闭后问题禁止继续编辑,回答。
always put the full prototype here. Use "void interrupt tmr0_isr(void)" instead
" T0IF=0;//关定时器 "
you aren't turning off the timer. you are clearing the timer interrupt flag - you cannot turn off tmr0.
" TMR0=61; //定时器初值"
the above approach will generate timing errors due to isr latency. instead, use "TMR0+=61;"
" if(m==19)//1秒
{m=0;
if (miao==59)//如果秒=59时
{miao=0;//秒清0
if(fen==59)
{fen=0;
if(hour==23)
hour=0;
else {hour++;}
}
else {fen++;}
}
else {miao++;}//不=59就自加1
}
else
{
m++;//不=19加1
}
} "
this whole section is convoluted. instead, use
" m+=1;
if (m==M_MAX) {
m-=M_MAX;
miao+=1;
if (miao==60) {
miao-=60;
fen+=1;
if (fen==60) {
.....}"
that is a lot more readable than yours.
一周热门 更多>