I wrote a function called get_temp to read from the device file: # get temerature # argument devicefile is the path of the sensor to be read, # returns None on error, or the temperature as a float def get_temp(devicefile): try: fileobj = open(devicefile,'r') lines = fileobj.readlines() fileobj.close() except: return None # get the status from the end of line 1 status = lines[-4:-1] # is the status is ok, get the temperature from line 2 if status=="YES": print status tempstr= lines[-6:-1] tempvalue=float(tempstr)/1000 print tempvalue return tempvalue else: print "There was an error." return None When read, the DS18B20 returns a two line string.
If the device was read successfully, the end of the first line contains the letters 'YES'.
The updated file will be saved to a temporary file and then automtically installed in the proper place. In the next post, I'll describe how I built the web UI for the Raspberry Pi temperature logger.
//#define DHTTYPE DHT11 // DHT 11 #define DHTTYPE DHT22 // DHT 22 (AM2302) //#define DHTTYPE DHT21 // DHT 21 (AM2301) const int TEMPERATURE_INTERVAL = 10; unsigned long last_temperature_sent = 0; const int HUMIDITY_INTERVAL = 10; unsigned long last_humidity_sent = 0; Homie Node temperature Node("temperature", "temperature"); Homie Node humidity Node("humidity", "humidity"); DHT dht(DHTPIN, DHTTYPE); void setup Handler() void get Send Temperature() void get Send Humid() void loop Handler() void setup() void loop() const int PIN_LED = D2; const int PIN_BUTTON = D1; int button OLD=LOW; Homie Node light("light", "light"); bool light On Handler(String message) Homie Node button Node("button", "button"); void loop Handler() void setup() void loop() Infact, the last sketch works for push button and switch.
The temperature logger consists of two parts: a script called to measure the temperature at 15 minute intervals, and a script called that displays temperatures in a web page. Every 15 minutes, it reads the temperature from a DS18B20 connected to my Pi's GPIO pins, and stores the reading in an SQLite database.
The other script, webgui.py, executes when it is requested by the Apache web server.
You can download the code for this project from Github: https://github.com/Pyplate/rpi_temp_logger.
There's a button to download the project as a zip file at the bottom of the right hand column.