51单片机用蓝牙和ds1302调时lcd1602显示程序代码
时间: 2023-08-31 16:12:51 浏览: 97
以下是使用51单片机,蓝牙模块和DS1302实时时钟芯片,控制LCD1602显示时间的程序代码:
```c
#include <reg51.h>
#include <intrins.h>
#define uchar unsigned char
#define uint unsigned int
sbit SCLK = P3^6; // DS1302时钟线
sbit IO = P3^5; // DS1302数据线
sbit RST = P3^4; // DS1302复位线
sbit RS = P1^0; // LCD1602控制线
sbit RW = P1^1; // LCD1602控制线
sbit E = P1^2; // LCD1602控制线
void delay(uint z)
{
uint x,y;
for(x=z;x>0;x--)
{
for(y=110;y>0;y--);
}
}
void write_com(uchar com)
{
RS = 0;
RW = 0;
P0 = com;
delay(5);
E = 1;
delay(5);
E = 0;
}
void write_data(uchar dat)
{
RS = 1;
RW = 0;
P0 = dat;
delay(5);
E = 1;
delay(5);
E = 0;
}
void init()
{
write_com(0x38);
write_com(0x0c);
write_com(0x06);
write_com(0x01);
}
void write_string(uchar x, uchar y, uchar *s)
{
uchar i;
if(x<16)
{
x |= 0x80;
switch(y)
{
case 0:i=0;break;
case 1:i=1;break;
case 2:i=2;break;
case 3:i=3;break;
}
i |= 0x40;
write_com(x);
write_com(i);
while(*s)
{
write_data(*s++);
}
}
}
void write_ds1302_byte(uchar dat)
{
uchar i;
for(i=0;i<8;i++)
{
IO = dat & 0x01;
dat >>= 1;
SCLK = 0;
_nop_();
_nop_();
SCLK = 1;
_nop_();
_nop_();
}
}
uchar read_ds1302_byte()
{
uchar i,dat;
for(i=0;i<8;i++)
{
dat >>= 1;
if(IO)
{
dat |= 0x80;
}
SCLK = 0;
_nop_();
_nop_();
SCLK = 1;
_nop_();
_nop_();
}
return dat;
}
void write_ds1302(uchar addr, uchar dat)
{
RST = 0;
_nop_();
_nop_();
RST = 1;
_nop_();
_nop_();
write_ds1302_byte(addr);
write_ds1302_byte(dat);
RST = 0;
}
uchar read_ds1302(uchar addr)
{
uchar dat;
RST = 0;
_nop_();
_nop_();
RST = 1;
_nop_();
_nop_();
write_ds1302_byte(addr);
dat = read_ds1302_byte();
RST = 0;
return dat;
}
void read_time()
{
uchar sec,min,hr;
sec = read_ds1302(0x81);
min = read_ds1302(0x83);
hr = read_ds1302(0x85);
write_string(0,0,"Time:");
write_string(6,0,hr/16+'0');
write_string(7,0,hr%16+'0');
write_string(8,0,':');
write_string(9,0,min/16+'0');
write_string(10,0,min%16+'0');
write_string(11,0,':');
write_string(12,0,sec/16+'0');
write_string(13,0,sec%16+'0');
}
void main()
{
uchar i;
init();
write_string(0,1,"Bluetooth Test");
write_string(0,2,"Waiting...");
while(1)
{
if(SBUF=='T')
{
SBUF = 'O';
delay(100);
read_time();
delay(100);
write_string(0,3,"Received T");
}
}
}
```
注意:需要根据自己使用的蓝牙模块进行相应的修改。同时DS1302时钟芯片需要在电路中正确接线。
阅读全文