WL0123 发表于 2025-3-18 06:47
DS18B20初始化后温度值寄存器里是初始数据“85”.要等约1秒才能读到正确温度,这是正常现象。可以在加电后 ...
void main(void) {
unsigned char i;
System_Init(); // 关闭LED灯和蜂鸣器
while (rd_temperature() == 85) {
;
}
Timer0Init();
Timer1Init(); // 定时器1初始化
while (1) {
Key_Proc(); // 按键处理函数
Seg_Proc(); // 数码管处理函数
Led_Proc(); // LED显示函数及温度采集
}
}
cien_s 发表于 2025-3-18 10:22
您好,我在主函数里面已经有一个循环防止上电就显示85,现在的情况是上电没有显示85,是正常的数值,然后 ...
WL0123 发表于 2025-3-18 11:47
理论上while (rd_temperature() == 85)的代码没有错,但rd_temperature()函数的返回值是要经过转换的,否 ...
#include "onewire.h"
#include "reg52.h"
sbit DQ = P1 ^ 4;
// 单总线内部延时函数
void Delay_OneWire(unsigned int t) {
t *= 12;
while (t--)
;
}
// 单总线写操作
void Write_DS18B20(unsigned char dat) {
unsigned char i;
for (i = 0; i < 8; i++) {
DQ = 0;
DQ = dat & 0x01;
Delay_OneWire(5);
DQ = 1;
dat >>= 1;
}
Delay_OneWire(5);
}
// 单总线读操作
unsigned char Read_DS18B20(void) {
unsigned char i;
unsigned char dat;
for (i = 0; i < 8; i++) {
DQ = 0;
dat >>= 1;
DQ = 1;
if (DQ) {
dat |= 0x80;
}
Delay_OneWire(5);
}
return dat;
}
// DS18B20初始化
bit init_ds18b20(void) {
bit initflag = 0;
DQ = 1;
Delay_OneWire(12);
DQ = 0;
Delay_OneWire(80);
DQ = 1;
Delay_OneWire(10);
initflag = DQ;
Delay_OneWire(5);
return initflag;
}
float rd_temperature() {
unsigned char low, high;
init_ds18b20();
Delay_OneWire(20);
Write_DS18B20(0xcc);
Write_DS18B20(0x44);
init_ds18b20();
Delay_OneWire(20);
Write_DS18B20(0xcc);
Write_DS18B20(0xbe);
low = Read_DS18B20();
high = Read_DS18B20();
return ((high << 8) | low) / 16.0;
}
Error_Temperature:1048.875000
Error_Temperature:281.562500
Error_Temperature:-2026.375000
denghe 发表于 2025-3-18 22:11
得延时一下,因为来不及读取就转换了
#include "onewire.h"
#include "reg52.h"
sbit DQ = P1 ^ 4;
// 单总线内部延时函数
void Delay_OneWire(unsigned int t) {
t *= 12;
while (t--)
;
}
// 单总线写操作
void Write_DS18B20(unsigned char dat) {
unsigned char i;
for (i = 0; i < 8; i++) {
DQ = 0;
DQ = dat & 0x01;
Delay_OneWire(5);
DQ = 1;
dat >>= 1;
}
Delay_OneWire(5);
}
// 单总线读操作
unsigned char Read_DS18B20(void) {
unsigned char i;
unsigned char dat;
for (i = 0; i < 8; i++) {
DQ = 0;
dat >>= 1;
DQ = 1;
if (DQ) {
dat |= 0x80;
}
Delay_OneWire(5);
}
return dat;
}
// DS18B20初始化
bit init_ds18b20(void) {
bit initflag = 0;
DQ = 1;
Delay_OneWire(12);
DQ = 0;
Delay_OneWire(80);
DQ = 1;
Delay_OneWire(10);
initflag = DQ;
Delay_OneWire(5);
return initflag;
}
float rd_temperature() {
unsigned char low, high;
init_ds18b20();
Delay_OneWire(20);
Write_DS18B20(0xcc);
Write_DS18B20(0x44);
init_ds18b20();
Delay_OneWire(20);
Write_DS18B20(0xcc);
Write_DS18B20(0xbe);
EA = 0;
low = Read_DS18B20();
high = Read_DS18B20();
EA = 1;
return (float)((high << 8) | low) * 0.0625;
}
glinfei 发表于 2025-3-18 16:27
DS18B20是单总线结构啊,你读它的时候关中断没?
Error_Temperature:-0.062500
Error_Temperature:-0.062500
Error_Temperature:-0.062500
cien_s 发表于 2025-3-19 15:40
您好,请问单总线结构要关中断的吗?我之前是没有关中断的,我尝试在读取温度函数前后,关开中断,但是还 ...
欢迎光临 (http://www.51hei.com/bbs/) | Powered by Discuz! X3.1 |