Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Here's an example code in Arduino that reads the temperature from an 18B20 sensor connected to an Arduino board:
- //Note: This code assumes that the 18B20 sensor is connected to pin 2 of the Arduino board. If you're using a different pin, you'll //need to modify the ONE_WIRE_BUS definition accordingly.
- #include <OneWire.h>
- // Data wire is connected to pin 2
- #define ONE_WIRE_BUS 2
- 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];
- // start reading from the 18B20 sensor
- if (!oneWire.search(addr)) {
- Serial.println("No more addresses.");
- oneWire.reset_search();
- delay(250);
- return;
- }
- // check the CRC of the address
- if (OneWire::crc8(addr, 7) != addr[7]) {
- Serial.println("CRC is not valid!");
- 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:
- Serial.println("Device is not recognized!");
- return;
- }
- // start conversion
- oneWire.reset();
- oneWire.select(addr);
- oneWire.write(0x44, 1);
- // wait for conversion to complete
- delay(1000);
- // read scratchpad
- present = oneWire.reset();
- oneWire.select(addr);
- oneWire.write(0xBE);
- // read data
- for (i = 0; i < 9; i++) {
- data[i] = oneWire.read();
- }
- // convert temperature data
- int16_t raw = (data[1] << 8) | data[0];
- float celsius = (float)raw / 16.0;
- // print temperature
- Serial.print("Temperature: ");
- Serial.print(celsius);
- Serial.println(" °C");
- // delay before reading from the sensor again
- delay(1000);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement