请为我制作一份51普中单片机简易秒表代码
时间: 2024-05-14 15:19:23 浏览: 98
好的,以下是一个简易的秒表代码,使用了51单片机和LCD1602液晶屏幕。
```c
#include <reg52.h>
#define LCD_data P1
sbit RS=P2^6;
sbit EN=P2^7;
unsigned char second=0,minute=0,hour=0,run_flag=0;
void delay(unsigned int x)
{
unsigned int i,j;
for(i=x;i>0;i--)
for(j=110;j>0;j--);
}
void LCD_send_cmd(unsigned char cmd)
{
RS=0;
LCD_data=cmd;
EN=1;
delay(2);
EN=0;
}
void LCD_send_data(unsigned char dat)
{
RS=1;
LCD_data=dat;
EN=1;
delay(2);
EN=0;
}
void LCD_init()
{
LCD_send_cmd(0x38);
LCD_send_cmd(0x0c);
LCD_send_cmd(0x06);
LCD_send_cmd(0x01);
}
void LCD_display(unsigned char addr,unsigned char *p)
{
LCD_send_cmd(addr);
while(*p!='\0')
{
LCD_send_data(*p++);
}
}
void timer0_init()
{
TMOD|=0x01;
TH0=0xfc;
TL0=0x66;
ET0=1;
EA=1;
TR0=1;
}
void timer0_ISR() interrupt 1
{
TH0=0xfc;
TL0=0x66;
if(run_flag==1)
{
second++;
if(second>=60)
{
minute++;
second=0;
if(minute>=60)
{
hour++;
minute=0;
if(hour>=24)
{
hour=0;
}
}
}
}
}
void main()
{
unsigned char str[16];
LCD_init();
timer0_init();
while(1)
{
sprintf(str,"%02d:%02d:%02d",hour,minute,second);
LCD_display(0x80,str);
delay(10);
if(P3^0==0 && run_flag==0)
{
run_flag=1;
}
else if(P3^1==0 && run_flag==1)
{
run_flag=0;
}
}
}
```
该代码使用定时器中断来计时,并且通过LCD显示秒表时间。同时,通过按键控制秒表的启动和暂停。
阅读全文