Difference between revisions of "DS18B20 readings to JSON"
From Wiki2
(Created page with "=====DS18B20 readings to JSON (in serial monitor)===== ::Base code from http://www.pjrc.com/teensy/td_libs_OneWire.html This code in../electronics/Arduino/[https://github.com/...") |
(No difference)
|
Latest revision as of 18:20, 12 January 2013
DS18B20 readings to JSON (in serial monitor)
- Base code from http://www.pjrc.com/teensy/td_libs_OneWire.html This code in../electronics/Arduino/DS18B20Serial_json.ino
- key bits:
You need to allocate a buffer for tempstr <syntaxhighlight>
float celsius, fahrenheit;
String jsn;
char tempBuf[32] = {0};
</syntaxhighlight> You end the json after you've gone through all the sensors and if you are just starting, create a new json string. Otherwise, Increment to next sensor. <syntaxhighlight>
if ( !ds.search(addr)) {//this is where it loops to the next address
Serial.println("No more addresses."); Serial.println();
jsn = jsn + "}";//so end the json
Serial.println(jsn);//and print it out
ctr=0;
ds.reset_search();//if there are no more devices go back to start of list
delay(250);
return;
} else {
if (ctr==0){jsn="{";}//must be just beginning, start the json str
++ctr;//since we found a device, increment sensor
}
</syntaxhighlight> The first two bytes of data = ds.read() is the sensor raw temp which gets converted here <syntaxhighlight>
// convert the data to actual temperature
unsigned int raw = (data[1] << 8) | data[0];
if (type_s) {
raw = raw << 3; // 9 bit resolution default
if (data[7] == 0x10) {
// count remain gives full 12 bit resolution
raw = (raw & 0xFFF0) + 12 - data[6];
}
} else {
byte cfg = (data[4] & 0x60);
if (cfg == 0x00) raw = raw << 3; // 9 bit resolution, 93.75 ms
else if (cfg == 0x20) raw = raw << 2; // 10 bit res, 187.5 ms
else if (cfg == 0x40) raw = raw << 1; // 11 bit res, 375 ms
// default is 12 bit resolution, 750 ms conversion time
}
celsius = (float)raw / 16.0;
fahrenheit = celsius * 1.8 + 32.0;
dtostrf(fahrenheit, 5, 1, tempBuf); //turns float to string
jsn= jsn + "\"sensor"+ ctr + "\": " + tempBuf + ", ";//appends temp to json
</syntaxhighlight>