可以写一个18b20的执行程序吗
时间: 2023-08-28 08:08:07 浏览: 38
当然可以,以下是一个18B20温度传感器的示例程序,使用Arduino编写:
```
#include <OneWire.h>
// Data wire is plugged into pin 2 on the Arduino
#define ONE_WIRE_BUS 2
// Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)
OneWire oneWire(ONE_WIRE_BUS);
void setup() {
Serial.begin(9600);
}
void loop() {
byte i;
byte present = 0;
byte type_s;
byte data[12];
byte addr[8];
float celsius, fahrenheit;
if ( !oneWire.search(addr)) {
// no more sensors on chain, reset search
oneWire.reset_search();
delay(250);
return;
}
// the first ROM byte indicates which chip
switch (addr[0]) {
case 0x10:
type_s = 1;
break;
case 0x28:
type_s = 0;
break;
case 0x22:
type_s = 0;
break;
default:
return;
}
// we might do a 9 bit resolution check later
// on newer chips we can do 12 bit
if (type_s) {
oneWire.write(0x55, 1);
oneWire.write(0x00, 1);
present = oneWire.reset();
oneWire.select(addr);
oneWire.write(0x44, 1);
} else {
oneWire.reset();
oneWire.select(addr);
oneWire.write(0x44, 1);
}
delay(1000); // Wait for conversion
present = oneWire.reset();
oneWire.select(addr);
oneWire.write(0xBE);
// Read temperature data
for ( i = 0; i < 9; i++) {
data[i] = oneWire.read();
}
// Convert the data to actual temperature
int16_t raw = (data[1] << 8) | data[0];
if (type_s) {
raw &= ~0x03; // 9 bit resolution, 93.75 ms
} else {
raw &= ~0x0F; // 12 bit resolution, 750 ms
}
celsius = (float)raw / 16.0;
fahrenheit = celsius * 1.8 + 32.0;
// Output temperature to serial monitor
Serial.print("Temperature: ");
Serial.print(celsius);
Serial.print(" Celsius, ");
Serial.print(fahrenheit);
Serial.println(" Fahrenheit");
delay(1000);
}
```
这个程序使用了OneWire库来与18B20传感器通信,并从传感器读取温度数据。程序中使用了摄氏度和华氏度两种温度单位来输出数据。你可以根据自己的需求进行修改。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)