Skip to content

Instantly share code, notes, and snippets.

@vuongngo
Created August 21, 2017 22:05
Show Gist options
  • Save vuongngo/0bd2d360eb1dc943915ab1499343588b to your computer and use it in GitHub Desktop.
Save vuongngo/0bd2d360eb1dc943915ab1499343588b to your computer and use it in GitHub Desktop.
#include <OneWire.h>
/**
* Get temperature
* And communicate through zbee S1
* On Arduino Leonardo
*/
int Temp_Pin = 2;
int outputPins[] = {10, 11, 12};
OneWire ds(Temp_Pin);
void setup() {
// Zbee on Serial1
Serial1.begin(9600);
Serial.begin(9600);
}
void loop() {
if (Serial1.available()) {
float temperature = getTemp();
serialFloatPrint(temperature);
}
delay(2000);
}
float getTemp(){
//returns the temperature from one DS18S20 in DEG Celsius
byte data[12];
byte addr[8];
// Search for next device
if ( !ds.search(addr)) {
//no more sensors on chain, reset search
ds.reset_search();
return -1000;
}
Serial.print("R=");
for( int i = 0; i < 8; i++) {
Serial.print(addr[i]);
Serial.print("");
}
Serial.println();
// Data integrity verification
if ( OneWire::crc8( addr, 7) != addr[7]) {
Serial1.write("CRC is not valid! \n");
return -1000;
}
if ( addr[0] != 0x10 && addr[0] != 0x28) {
Serial1.write("Device is not recognized \n");
return -1000;
}
ds.reset();
ds.select(addr);
ds.write(0x44,1); // start conversion, with parasite power on at the end
byte present = ds.reset();
ds.select(addr);
ds.write(0xBE); // Read Scratchpad
for (int i = 0; i < 9; i++) { // we need 9 bytes
data[i] = ds.read();
}
ds.reset_search();
byte MSB = data[1];
byte LSB = data[0];
float tempRead = ((MSB << 8) | LSB); //using two's compliment
float TemperatureSum = tempRead / 16;
return TemperatureSum;
}
void serialFloatPrint(float f) {
char result[8];
dtostrf(f, 6, 2, result);
Serial1.write(result);
Serial1.write("\n");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment