stc89c52单片机利用DS18B20测温度通过串口输出
时间: 2023-09-19 19:07:02 浏览: 124
您好,下面是stc89c52单片机利用DS18B20测温度并通过串口输出的代码示例:
```
#include <REG52.H>
#include <stdio.h>
#define DQ P2_0
sbit DQ = P2^0;
unsigned char temp[2];
unsigned int temperature;
void delay(unsigned int i)
{
while(i--);
}
void Init_DS18B20()
{
unsigned char flag=0;
DQ=1;
delay(8);
DQ=0;
delay(80);
DQ=1;
delay(12);
flag=DQ;
delay(20);
}
unsigned char ReadOneChar()
{
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);
}
void WriteOneChar(unsigned char dat)
{
unsigned char i=0;
for (i=8; i>0; i--)
{
DQ=0;
DQ=dat&0x01;
dat>>=1;
delay(4);
DQ=1;
}
}
void ReadTemperature()
{
unsigned char a=0,b=0;
Init_DS18B20();
WriteOneChar(0xcc);
WriteOneChar(0x44);
delay(500);
Init_DS18B20();
WriteOneChar(0xcc);
WriteOneChar(0xbe);
a=ReadOneChar();
b=ReadOneChar();
temperature=b;
temperature<<=8;
temperature|=a;
}
void UartInit()
{
TMOD=0x20;
TH1=0xfd;
TL1=0xfd;
TR1=1;
SM0=0;
SM1=1;
REN=1;
EA=1;
ES=1;
}
void UartSendStr(unsigned char *s)
{
while (*s != '\0')
{
SBUF = *s++;
while(!TI);
TI=0;
}
}
void main()
{
UartInit();
while(1)
{
ReadTemperature();
temperature = temperature * 0.0625;
sprintf(temp, "%d", temperature);
UartSendStr(temp);
UartSendStr("\r\n");
delay(1000);
}
}
void Uart() interrupt 4
{
if(RI)
{
RI=0;
}
if(TI)
{
TI=0;
}
}
```
该代码使用了stc89c52单片机和DS18B20温度传感器,通过串口将温度值输出。具体实现过程为:
1. 初始化DS18B20传感器,发送开始信号、写指令、延时等操作;
2. 读取温度值,发送读指令、读取温度等操作;
3. 将温度值转换为实际温度值;
4. 将温度值转换为字符串形式,并通过串口发送出去。
需要注意的是,串口通信的初始化需要根据具体的硬件配置进行调整。