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.zg4o1577.cn/bbs/) | Powered by Discuz! X3.1 |