程序的目的:1)、要通过按键(移位键和加减键设定数据,其中包括定时器的初始值);
2)、设定好数据以后启动定时器工作(按1S递减);
出现的问题:定时器出现问题了,有时候2s递减一次,我大概分析一下是主程序那块有点问题;但是不知道怎样修改,请各位单片机高手帮我改改,谢谢。
电路图:P0接的7段LED显示的段选;位选由P20、P21、P22通过138译码器连接;P23、P24、P25连接的是led灯;P32、P33、
P34连接的键盘
程序:
# include
# include
# define uchar unsigned char
# define uint unsigned int
uchar code led_table[]={0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f};
sbit p32=P3^2;
sbit p33=P3^3;
sbit p34=P3^4;
sbit p23=P2^3;
sbit p24=P2^4;
sbit p25=P2^5;
uchar count_time;
uchar count_yw;
uchar count_jj;
uchar databuffer[8]={0};
uchar num=0;
int count0,count1;
int xianshi0,xianshi1;
void delayms(uchar ms)
{
uchar i;
while(ms--)
for(i=120;i>0;i--);
}
/*void dispy(uchar rece,uchar num)
{
P0=led_table[rece];
P2=P2&0xf8;
P2=P2|num;
delayms(20);
}
void Open_dispy() //显示函数没有问题
{
uchar i;
for(i=0;i<9;i++)
{
dispy(8,i);
delayms(4);
}
}*/
void dispy1(int xianshi0)
{
databuffer[0]=xianshi0/1000;
databuffer[1]=xianshi0%1000/100;
databuffer[2]=xianshi0%100/10;
databuffer[3]=xianshi0%10;
P0=led_table[databuffer[0]];
P2&=0xf8;
P2|=0x00;
delayms(4);
P0=led_table[databuffer[1]];
P2&=0xf8;
P2|=0x01;
delayms(4);
P0=led_table[databuffer[2]];
P2&=0xf8;
P2|=0x02;
delayms(4);
P0=led_table[databuffer[3]];
P2&=0xf8;
P2|=0x03;
delayms(4);
P0=led_table[databuffer[4]];
P2&=0xf8;
P2|=0x04;
delayms(4);
P0=led_table[databuffer[5]];
P2&=0xf8;
P2|=0x05;
delayms(4);
P0=led_table[databuffer[6]];
P2&=0xf8;
P2|=0x06;
delayms(4);
P0=led_table[databuffer[7]];
P2&=0xf8;
P2|=0x07;
delayms(4);
}
void Key_YW()//移位键
{
//uchar temp;
//P2&=0xf8;
//P2&=0xf8;
//P2^=count_yw;
if(p32==0)
{
delayms(2);
if(p32==0)
{
count_yw++;
count_yw%=9;
}
while(p32==0);
P2&=0xf8;
P2|=count_yw;
databuffer[num%8]=count_jj;
num++;
num=num%8;
}
}
void Key_QH()//时分秒切换键
{
uchar temp;
if(p33==0)
{
delayms(2);
if(p33==0)
{
count_time++;
temp=count_time%3;
}
switch(temp)
{
case 1:p25=1;p23=0;count1=72000;break;//设定小时的显示灯亮
case 2:p23=1;p24=0;count1=1200;break;// 设定分钟的显示灯亮
case 0:p23=1;p24=1;p25=0;count1=20;break; //设定秒钟的显示灯亮
//default :p26=1;
}
while(p33==0);//检测按键是否释放
// P2&=0xf8;
}
}
void Key_JJ()
{
//uchar temp;
//P0=0x3f;
if(p34==0)
{
delayms(2);
if(p34==0)
{
count_jj++;
count_jj%=10;
//temp=P0+count_jj;
}
while(p34==0);
P0=led_table[count_jj];
}
//databuffer
}
void main()
{
//Open_dispy();
//uchar i;
//count0=0;
P0=0x3f;
P2=0xf8;
P3=0xff;
TMOD=0x01;//工作在定时器0方式1
TH0=(65536-50000)/256;//设定定时器的初值
TL0=(65536-50000)%256;
IE=0x82;//开中断
while(1)
{
Key_QH();//确定了一次计数的值(1h、1m、1s)
Key_YW();//
Key_JJ();//设置了时间和电流值
P1=led_table[databuffer[3]];//测试用的
//IE=0x82;//开中断
//TR0=1;
if(count_yw==8)
{
xianshi0=databuffer[0]*1000+databuffer[1]*100+databuffer[2]*10+databuffer[3]; //有问题
delayms(20);
TR0=1;
if(xianshi0>0)
dispy1(xianshi0);
else
{
dispy1(0);
TR0=0;
}
}
}
}
void timer0() interrupt 1
{
TH0=(65536-50000)/256;
TL0=(65536-50000)%256;
if(++count0==count1)
{
count0=0;
xianshi0--;
}
}