51 单片机 +18B20显示程序+74HC164扩展显示数码管
#include <stc.h>
#include "intrins.h" //_nop_();延时函数用
#define uchar unsigned char
#define uint unsigned int
//================18b20数据口定义===============
uint temp; // 定义一个16位变量用于COPY数据
sbit DQ = P2^6;
char flash,presence;
uint temp1,temp2; //读出温度暂放
uchar s1,s2,s3,s4; //显示单元数据,共6个数据和一个运算暂用
//=======164端口定义==========
sbit ge=P2^5; //个位
sbit shi=P2^4; //十位
sbit bai=P2^3; //百位
sbit qian=P2^2; //千位
sbit clk=P2^1; //164时钟线
sbit data1=P2^0; //164数据线
sbit a0=ACC^0; //累加器
uchar code LED[10]={ //不带小数点的代码表
0xC0,0xF9,0xA4,0xB0,0x99,
0x92,0x82,0xF8,0x80,0x90,};
uchar code led1[10]={ //带小数点的代码表
0x40,0x79,0x24,0x30,0x19,
0x12,0x2,0x78,0x0,0x10,};
//======164数据转换程序=======
void chuanshu164(uchar data_buf)
{
uchar i;
ACC=data_buf; //数据送累加器
for(i=8;i>0;i--)
{
clk=0;
data1=a0;
clk=1;
ACC=ACC>>1;
}
clk=0;
}
/*****************延时函数*************************/
void delay(uint t)
{
for (;t>0;t--);
_nop_();
}
//========显示4位数码管函数===========
void xianshi(uint shu)
{
uchar ss;
for(ss=10;ss>0;ss--)
{
uint wei1,wei2,wei3,wei4;
wei1=shu/1000; //将千位分离
wei2=shu%1000/100; //将百位分离
wei3=shu%100/10; //将十位分离
wei4=shu%10; //将个位分离
chuanshu164(led[wei1]); //显示第一位数码管
qian=0;
delay(200);
qian=1;
chuanshu164(led[wei2]); //显示第二位数码管
bai=0;
delay(200);
bai=1;
chuanshu164(led1[wei3]); //显示第三位数码管
shi=0;
delay(200);
shi=1;
chuanshu164(led[wei4]); //显示第四位数码管
ge=0;
delay(200);
ge=1;
//}
}
}
//=================18b20相关函数开始==============
/****************DS18B20复位函数************************/
ow_reset(void)
{
char presence=1;
while(presence)
{
while(presence)
{
DQ=1;_nop_();_nop_(); //从高拉倒低
DQ=0;
delay(550); //550 us
DQ=1;
delay(66); //66 us
presence=DQ; //presence=0 复位成功,继续下一步
}
delay(500); //延时500 us
presence=~DQ;
}
DQ=1; //拉高电平
}
/****************DS18B20写命令函数************************/
void write_byte(uchar val) //向1-WIRE 总线上写1个字节
{
uchar i;
for(i=8;i>0;i--)
{
DQ=1;_nop_();_nop_(); //从高拉倒低
DQ=0;_nop_();_nop_();_nop_();_nop_(); //5 us
DQ=val&0x01; //最低位移出
delay(66); //66 us
val=val/2; //右移1位
}
DQ=1;
delay(10);
}
//
/****************DS18B20读1字节函数************************/
uchar read_byte(void) //从总线上取1个字节
{
uchar i;
uchar value=0;
for(i=8;i>0;i--)
{
DQ=1;_nop_();_nop_();
value>>=1;
DQ=0;_nop_();_nop_();_nop_();_nop_(); //4 us
DQ=1;_nop_();_nop_();_nop_();_nop_(); //4 us
if(DQ)value|=0x80;
delay(66); //66 us
}
DQ=1;
return(value);
}
/****************读出温度函数************************/
read_temp()
{
ow_reset(); //总线复位
write_byte(0xcc); //发命令
write_byte(0x44); //发转换命令
ow_reset();
delay(1);
write_byte(0xcc); //发命令
write_byte(0xbe);
temp1=read_byte(); //读温度值的低字节
temp2=read_byte(); //读温度值的高字节
temp=(temp2*256+temp1)*0.625;
return temp; //返回温度值
}
//=================18b20相关函数结束==============
//=================主函数=========================
void main(void)
{
ow_reset(); //开机先转换一次
write_byte(0xcc); //Skip ROM
write_byte(0x44); //发转换命令
while(1)
{
xianshi(read_temp());
//xianshi(read_temp());
//xianshi(read_temp());
//delay(500);
}
}