多路温度监测系统,用到三个DS18B20,每个DS18B20 接一个51单片机管脚,不是单总线的,驱动程序咋写?

2024-12-31 11:40:03
推荐回答(1个)
回答1:

供你参考
#include
#define uchar unsigned char
#define uint unsigned int
#define OFF 1
#define ON 0
sbit LedRed=P2^7;
sbit LedGreen=P2^6;
//18B20函数声明
bit STA44(uchar i); //启动第i个1820的温度转换
bit STAbe(uchar i,uint *tc); //读第i个1820的温度存到指针tc处
uint TC; //温度采样暂存
/* 温度发送缓存,S起始,ABCD组号,E结束,中间是温度 */
uchar TCA[4][6]={{'S','A',0,0,0,'E'},
{'S','B',0,0,0,'E'},
{'S','C',0,0,0,'E'},
{'S','D',0,0,0,'E'}};
uchar TCArow=0,TCAi=0; //二维数组行、列索引
//串行口初始化
void init_S(void)
{
SCON=0x50; //串行口方式1
TMOD=(TMOD&0x0F)|0x20; //T/C1 方式2
TH1=TL1=0xfe; //波特率重装值
TR1=1; //启动T/C1
}
main(){
uint count;
init_S();
while(1)
{
STA44((TCArow+1)%4); //启动下一路温度转换
if(STAbe(TCArow,&TC)){ //读上一路温度转换值
TC=TC*0.0625; //温度换算
TCA[TCArow][2]=TC/100%10+'0'; //转存为ASCII码
TCA[TCArow][3]=TC/10%10+'0';
TCA[TCArow][4]=TC%10+'0';
}

#include
#define uchar unsigned char
#define uint unsigned int
void delay(uint i){while(--i);}
/* 指定DQ线操作常数表,查表比计算快 */
uchar code DQa[3][4]={{0x00,0x00,0x00,0x00},
{0x01,0x02,0x04,0x08},
{0xFE,0xFD,0xFB,0xF7}};
/*给指定DQ线赋值*/
#define DQ(i,b) P1=P1&(DQa[2][i])|DQa[b][i]
/*读指定DQ线*/
#define DQack(i) P1&(DQa[1][i])
/* 初始化DS18B20,成功返回1,失败返回0 */
/* 参数i取值0~3,对应4只DS18B20,下同 */
bit STA_1820(uchar i){
bit ack;
DQ(i,1);delay(5);
DQ(i,0);delay(80);
DQ(i,1);delay(5);
ack=DQack(i);delay(50);
return ack;
}
//读DS18B20一字节,返回读到的数
char Read_1820(uchar i){
uchar j,dat=0;
for(j=0;j<8;j++){
DQ(i,0); dat>>=1;
DQ(i,1); if(DQack(i))dat|=0x80;
delay(7);
}
return(dat);
}
//向DS18B20写一字节,参数为要写的数
void Write_1820(uchar i,uchar dat){
uchar j;
for(j=0;j<8;j++) {
DQ(i,0);
DQ(i,dat&0x01); delay(7);
DQ(i,1); dat>>=1;
}
}
/* 启动温度转换,成功返回1 */
bit STA44(uchar i){
if(!STA_1820(i)){
Write_1820(i,0xcc);
Write_1820(i,0x44);
return 1;
}
else return 0;
}
/* 读温度转换值,成功返回1,读到的值存到TC指针处 */
bit STAbe(uchar i,uint *TC){
uchar TCL,TCH; //缓存采集值
if(!STA_1820(i)){ //重新启动总线
Write_1820(i,0xcc); //跳过ROM
Write_1820(i,0xbe); //准备读
TCL = Read_1820(i); //读0号
TCH = Read_1820(i); //读1号
*TC=(TCH*0x100+TCL);
return 1;
}
else return 0;
}