一、介紹
DS18B20溫度傳感器是一種數字溫度傳感器,控制協議簡單,數據穩定可靠,而且價格低廉,非常適合用於單片機控制系統中。
DS18B20採用單總線結構,只需要三根引腳即可完成通訊。它可以工作在-55℃至125℃的溫度範圍內,並提供了9至12位分辨率。此外, DS18B20還可以通過使用外部供電提高精度。
二、DS18B20的接線
DS18B20隻需要三根線(DQ, GND, VCC)即可完成與單片機的連接。
DQ – 連接到單片機的任意IO口,用於數據的傳輸
GND – 連接到單片機的 GND
VCC – 連接到單片機的 VCC
+---------+
| |
| VCC --------------- 3.3V - 5V
| |
| GND --------------- GND
| |
| |
DQ ------------+ +---------------
三、使用DS18B20進行溫度測量
DS18B20通過一次性寫入指令來啟動溫度測量,並通過讀取傳感器的數據進行溫度的計算。以下是使用DS18B20進行溫度測量的基本步驟:
1、複位信號線:
void reset() {
digitalWrite(DQ, LOW);
delayMicroseconds(480);
pinMode(DQ, INPUT);
delayMicroseconds(60);
int presence = digitalRead(DQ);
delayMicroseconds(420);
}
2、向DS18B20發送寫入指令以啟動溫度測量:
void writeBit(uint8_t bit) {
pinMode(DQ, OUTPUT);
digitalWrite(DQ, LOW);
delayMicroseconds(5);
digitalWrite(DQ, bit);
delayMicroseconds(60);
pinMode(DQ, INPUT);
}
void writeByte(uint8_t byte) {
for (uint8_t i=0; i>= 1;
}
}
void startConversion() {
reset();
writeByte(0xCC); // Skip ROM command
writeByte(0x44); // Start Conversion
}
3、讀取DS18B20返回的數據:
void readBit(uint8_t& bit) {
pinMode(DQ, OUTPUT);
digitalWrite(DQ, LOW);
delayMicroseconds(1);
pinMode(DQ, INPUT);
delayMicroseconds(14);
bit = digitalRead(DQ);
delayMicroseconds(45);
}
uint8_t readByte() {
uint8_t byte = 0;
for (uint8_t i=0; i<8; i++) {
uint8_t bit;
readBit(bit);
byte |= (bit << i);
}
return byte;
}
void readScratchpad(uint8_t* scratchpad) {
reset();
writeByte(0xCC); // Skip ROM command
writeByte(0xBE); // Read Scratchpad
for (uint8_t i=0; i<9; i++) {
scratchpad[i] = readByte();
}
}
4、將DS18B20返回的數據進行溫度計算:
float readTemperature() {
startConversion();
delay(750);
uint8_t scratchpad[9];
readScratchpad(scratchpad);
int16_t raw = scratchpad[0] | (scratchpad[1] << 8);
float temp = (float)raw / 16.0;
return temp;
}
四、示例代碼
下面是一個簡單的示例程序,用於讀取DS18B20的溫度值並將其打印到串口:
#include <OneWire.h>
OneWire ds(DQ);
void setup() {
Serial.begin(9600);
}
void loop() {
float temp = readTemperature();
Serial.print("Temperature: ");
Serial.print(temp, 1);
Serial.println("C");
delay(1000);
}
void reset() {
//...
}
void writeBit(uint8_t bit) {
//...
}
void writeByte(uint8_t byte) {
//...
}
void startConversion() {
//...
}
void readBit(uint8_t& bit) {
//...
}
uint8_t readByte() {
//...
}
void readScratchpad(uint8_t* scratchpad) {
//...
}
float readTemperature() {
//...
}
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/193761.html
微信掃一掃
支付寶掃一掃