怎么把孩子培养好:多个 ds18b20 C51程序 - 博客 BLOG x5dj.com 我的世界 我的??...
来源:百度文库 编辑:偶看新闻 时间:2024/04/27 12:15:56
/*2个Ds18b20温度显示电路,12Mhz晶振,用四位动态扫描方式显示2个ds18b20,
主程序结构为网上共享资源,非我编写,我在基础上扩展成多位ds18b20,给
共同对c51感兴趣朋友参考,希望大家给以修该,帮助,并把简化程序共享给我。是跳过序列号,
我的实验是通过的。
liujun399@yahoo.com.cn */
#include
#include
#include
sbit ge=P2^6;
sbit shi=P2^7;
sbit ge2=P2^4;
sbit shi2=P2^5;
sbit DQ =P2^0; //定义通信端口1
sbit DQ2 =P2^1; //定义通信端口2
unsigned char tab[]={ 0xC0,0xF9,0xA4,0xB0,0x99,0x92,0x82,0xF8,0x80,0x90};
//0, 1, 2 3 4 5 6 7 8 9
void delay(unsigned int i)
{
while(i--);
}
//初始化函数1
Init_DS18B20(void)
{
unsigned char x=0;
DQ = 1; //DQ复位
delay(8); //稍做延时
DQ = 0; //单片机将DQ拉低
delay(80); //精确延时 大于 480us
DQ = 1; //拉高总线
delay(14);
x=DQ; //稍做延时后 如果x=0则初始化成功 x=1则初始化失败
delay(20);
}
//读一个字节
ReadOneChar(void)
{
unsigned char i=0;
unsigned char dat = 0;
for (i=8;i>0;i--)
{
DQ = 0; // 给脉冲信号
dat>>=1;
DQ = 1; // 给脉冲信号
if(DQ)
dat|=0x80;
delay(4);
}
return(dat);
}
//写一个字节
WriteOneChar(unsigned char dat)
{
unsigned char i=0;
for (i=8; i>0; i--)
{
DQ = 0;
DQ = dat&0x01;
delay(5);
DQ = 1;
dat>>=1;
}
delay(4);
}
//读取温度
ReadTemperature(void)
{
unsigned char a=0;
unsigned char b=0;
unsigned char t=0;
Init_DS18B20();
WriteOneChar(0xCC); // 跳过读序号列号的操作
WriteOneChar(0x44); // 启动温度转换
Init_DS18B20();
WriteOneChar(0xCC); //跳过读序号列号的操作
WriteOneChar(0xBE); //读取温度寄存器等(共可读9个寄存器) 前两个就是温度
a=ReadOneChar(); //读取温度值低位
b=ReadOneChar(); //读取温度值高位
a=a>>4; //低位右移4位,舍弃小数部分
t=b<<4; //高位左移4位,舍弃符号位
t=t|a;
return(t);
}
void display_tempmain(unsigned char i) //1个18b20温度显示函数
{
P0=tab[i/10];
shi=0;
ge=1;
shi2=1;ge2=1;
delay(400);
P0=tab[i%10];
shi=1;
ge=0;
shi2=1;ge2=1;
}
//初始化函数2
Init_DS18B202(void)
{
unsigned char x=0;
DQ2 = 1; //DQ复位
delay(8); //稍做延时
DQ2 = 0; //单片机将DQ拉低
delay(80); //精确延时 大于 480us
DQ2 = 1; //拉高总线
delay(14);
x=DQ2; //稍做延时后 如果x=0则初始化成功 x=1则初始化失败
delay(20);
}
//读一个字节
ReadOneChar2(void)
{
unsigned char i=0;
unsigned char dat = 0;
for (i=8;i>0;i--)
{
DQ2 = 0; // 给脉冲信号
dat>>=1;
DQ2 = 1; // 给脉冲信号
if(DQ2)
dat|=0x80;
delay(4);
}
return(dat);
}
//写一个字节
WriteOneChar2(unsigned char dat)
{
unsigned char i=0;
for (i=8; i>0; i--)
{
DQ2 = 0;
DQ2 = dat&0x01;
delay(5);
DQ2 = 1;
dat>>=1;
}
delay(4);
}
//读取温度
ReadTemperature2(void)
{
unsigned char a2=0;
unsigned char b2=0;
unsigned char t2=0;
Init_DS18B202();
WriteOneChar2(0xCC); // 跳过读序号列号的操作
WriteOneChar2(0x44); // 启动温度转换
Init_DS18B202();
WriteOneChar2(0xCC); //跳过读序号列号的操作
WriteOneChar2(0xBE); //读取温度寄存器等(共可读9个寄存器) 前两个就是温度
a2=ReadOneChar2(); //读取温度值低位
b2=ReadOneChar2(); //读取温度值高位
a2=a2>>4; //低位右移4位,舍弃小数部分
t2=b2<<4; //高位左移4位,舍弃符号位
t2=t2|a2;
return(t2);
}
void display_tempmain2(unsigned char i) //另一个18b20温度显示函数
{
P0=tab[i/10];
shi2=0;
ge2=1;
shi=1;ge=1;
delay(400);
P0=tab[i%10];
shi2=1;
ge2=0;
shi=1;ge=1;
}
void main(void)
{unsigned int temp;unsigned int temp2;unsigned int e;
while(1) //主循环
{ temp=ReadTemperature(); display_tempmain(temp);
temp2=ReadTemperature2(); display_tempmain2(temp2);
}
}