Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
DS18B20 temperature probe
#1
Is it possible to read data from a DS18B20 temperature probe connected to a ESP32 using Micropython build or do you have to use Micropython LoBo?
Reply
#2
AS the ds18x20 library is present in micropython/ports/esp32 I would strongly assume that it works with every build.
Reply
#3
LoBo:
from machine import Onewire
from time import sleep

ow = Onewire(23)  # Initialize onewire & DS18B20 temperature sensor
ds = Onewire.ds18x20(ow, 0)

def get_temp_lobo():
    try:
        while True:
            temp = ds.convert_read()
            print("Temperature: {0:.1f}°C".format(temp))
            sleep(4)
    except KeyboardInterrupt:
        print('\nCtrl-C pressed.  Cleaning up and exiting...')
    finally:
        ds.deinit()
        ow.deinit()

get_temp_lobo()

MicroPython.org:

from machine import Pin
from onewire import OneWire
from ds18x20 import DS18X20
from time import sleep

dat = Pin(23)
ow = OneWire(dat)  # Initialize onewire & DS18B20 temperature sensor
ds = DS18X20(ow)
roms = ds.scan()  # Scan for devices

def get_temp_mp():
    try:
        while True:
            ds.convert_temp()
            sleep(1)
            temp = ds.read_temp(roms[0])
            print("Temperature: {0:.1f}°C".format(temp))
            sleep(3)
    except KeyboardInterrupt:
        print('\nCtrl-C pressed.  Exiting...')

get_temp_mp()
Reply
#4
Thanks rdagger,

I tried your MicroPython code and it works great. I then tried adding this code to your ESP32 MicroPython web server tutorial 3 code.  I think I'm close to getting it to work with the DS18B20 temperature probe but I must be missing something or the code order is not correct.  I'm able to enter REPL and start the web server with my ds18x20_web (ds18x20_web.py) file.  When I open a web browser and enter the ESP32 IP address (192.168.2.164/ds1820.html) it shows MicroPython DS18B20 Sensor title but no temperature.  I have attached the two files.

ds18x20_web.py
Code:
from microWebSrv import MicroWebSrv
from machine import Pin
from onewire import OneWire
from ds18x20 import DS18X20
from time import sleep

dat = Pin(23)
ow = OneWire(dat)  # Initialize onewire & DS18B20 temperature sensor
ds = DS18X20(ow)
roms = ds.scan()  # Scan for devices

def _httpHandlerDS18X20Get(httpClient, httpResponse):
   try:
       get_temp_mp()
       ds.convert_temp()
       sleep(1)
       temp = ds.read_temp(roms[0])
       if all(isinstance(i, float) for i in [t]):   # Confirm values
           data = ("Temperature: {0:.1f}°C".format(temp))
   except:
       data = 'Attempting to read sensor...'

       get_temp_mp()

       httpResponse.WriteResponseOk(
       headers = ({'Cache-Control': 'no-cache'}),
       contentType = 'text/event-stream',
       contentCharset = 'UTF-8',
       content = 'data: {0}\n\n'.format(data) )

       
routeHandlers = [ ( "/ds18x20", "GET",  _httpHandlerDS18X20Get ) ]
srv = MicroWebSrv(routeHandlers=routeHandlers, webPath='/www/')
srv.Start(threaded=False)

ds18x20.html
Code:
<!DOCTYPE html>
<html>
<head>
   <meta content="text/html;charset=utf-8" http-equiv="Content-Type">
   <meta content="utf-8" http-equiv="encoding">
</head>
<body>

<h1>MicroPython DS18B20 Sensor</h1>
<div id="result" style="color: SlateBlue; font-size: 200%; font-family: Monaco, monospace; margin: 20px"></div>

<script>
if(typeof(EventSource) !== 'undefined') {
   const source = new EventSource('http://' + window.location.hostname + '/ds18x20');
   source.onmessage = function(e) {
       document.getElementById("result").innerHTML = e.data;
   };
} else {
   document.getElementById("result").innerHTML = "Sorry, your browser does not support server-sent events...";
}
</script>

</body>
</html>
Reply
#5
(12-26-2018, 03:32 AM)Dabi Wrote: Thanks rdagger,

I tried your MicroPython code and it works great. I then tried adding this code to your ESP32 MicroPython web server tutorial 3 code.  I think I'm close to getting it to work with the DS18B20 temperature probe but I must be missing something or the code order is not correct.  I'm able to enter REPL and start the web server with my ds18x20_web (ds18x20_web.py) file.  When I open a web browser and enter the ESP32 IP address (192.168.2.164/ds1820.html) it shows MicroPython DS18B20 Sensor title but no temperature.  I have attached the two files.

Merry XMAS


from microWebSrv import MicroWebSrv
from machine import Pin
from onewire import OneWire
from ds18x20 import DS18X20
from time import sleep_ms

dat = Pin(23)
ow = OneWire(dat)  # Initialize onewire & DS18B20 temperature sensor
ds = DS18X20(ow)
roms = ds.scan()  # Scan for devices

def _httpHandlerDS18X20Get(httpClient, httpResponse):
   ds.convert_temp()
   sleep_ms(750)
   temp = ds.read_temp(roms[0])
   data = ("Temperature: {0:.1f}°C".format(temp))
   httpResponse.WriteResponseOk(
   headers = ({'Cache-Control': 'no-cache'}),
   contentType = 'text/event-stream',
   contentCharset = 'UTF-8',
   content = 'data: {0}\n\n'.format(data) )

       
routeHandlers = [ ( "/ds18x20", "GET",  _httpHandlerDS18X20Get ) ]
srv = MicroWebSrv(routeHandlers=routeHandlers, webPath='/www/')
srv.Start(threaded=False)

Reply
#6
Thanks rdagger for the Christmas gift, works exactly the way it should!
Reply
#7
(12-26-2018, 04:57 AM)rdagger Wrote:
(12-26-2018, 03:32 AM)Dabi Wrote: Thanks rdagger,

I tried your MicroPython code and it works great. I then tried adding this code to your ESP32 MicroPython web server tutorial 3 code.  I think I'm close to getting it to work with the DS18B20 temperature probe but I must be missing something or the code order is not correct.  I'm able to enter REPL and start the web server with my ds18x20_web (ds18x20_web.py) file.  When I open a web browser and enter the ESP32 IP address (192.168.2.164/ds1820.html) it shows MicroPython DS18B20 Sensor title but no temperature.  I have attached the two files.

Merry XMAS


from microWebSrv import MicroWebSrv
from machine import Pin
from onewire import OneWire
from ds18x20 import DS18X20
from time import sleep_ms

dat = Pin(23)
ow = OneWire(dat)  # Initialize onewire & DS18B20 temperature sensor
ds = DS18X20(ow)
roms = ds.scan()  # Scan for devices

def _httpHandlerDS18X20Get(httpClient, httpResponse):
   ds.convert_temp()
   sleep_ms(750)
   temp = ds.read_temp(roms[0])
   data = ("Temperature: {0:.1f}°C".format(temp))
   httpResponse.WriteResponseOk(
   headers = ({'Cache-Control': 'no-cache'}),
   contentType = 'text/event-stream',
   def write_temp(temp):
   with open("/home/pi/cpu_temp.csv", "a") as log:
       log.write("{0},{1}\n".format(strftime("%Y-%m-%d %H:%M:%S"),str(temp)))

   contentCharset = 'UTF-8',
   content = 'data: {0}\n\n'.format(data) )

       
routeHandlers = [ ( "/ds18x20", "GET",  _httpHandlerDS18X20Get ) ]
srv = MicroWebSrv(routeHandlers=routeHandlers, webPath='/www/')
srv.Start(threaded=False)


rdagger I would like to add logging capability to your code above.  I have multiple ESP32's running the code above and I'm able to view each HTTP address to check temperatures .  Is it even possible to log multiple ESP's into one file or will I have to have separate files for each ESP32?  I tried starting with the code below and inserting it into your Christmas code but I'm having issues getting it to run.  Am I on the right track or should I be approaching this differently?



Code:
from time import sleep, strftime


def write_temp(temp):
   with open("/home/pi/cpu_temp.csv", "a") as log:
       log.write("{0},{1}\n".format(strftime("%Y-%m-%d %H:%M:%S"),str(temp)))
Reply
#8
(12-30-2018, 07:54 PM)Dabi Wrote: rdagger I would like to add logging capability to your code above.  I have multiple ESP32's running the code above and I'm able to view each HTTP address to check temperatures .  Is it even possible to log multiple ESP's into one file or will I have to have separate files for each ESP32?  I tried starting with the code below and inserting it into your Christmas code but I'm having issues getting it to run.  Am I on the right track or should I be approaching this differently?


Code:
from time import sleep, strftime


def write_temp(temp):
   with open("/home/pi/cpu_temp.csv", "a") as log:
       log.write("{0},{1}\n".format(strftime("%Y-%m-%d %H:%M:%S"),str(temp)))

There are a lot of ways to do perform centralized logging. 
I haven't tried it, but if you're using the LoBo build, you could take a look at using MQTT to log to ThingSpeak.  The wiki has an example: https://github.com/loboris/MicroPython_E...thingspeak
Or you could just us MQTT to log to a central broker.
There are also a couple of MicroPython libraries on GitHub that support logging to a remote SysLog server which you could run on a Pi, a server or a NAS.
There are also a few MicroPython database client libraries on GitHub which you could use to log to a remote database such as MySQL or redis.
You might be able to find an online service that provides a REST API for logging.  I've heard of plot.ly but it might be a paid service.
Reply
#9
(12-30-2018, 08:27 PM)rdagger Wrote:
(12-30-2018, 07:54 PM)Dabi Wrote: rdagger I would like to add logging capability to your code above.  I have multiple ESP32's running the code above and I'm able to view each HTTP address to check temperatures .  Is it even possible to log multiple ESP's into one file or will I have to have separate files for each ESP32?  I tried starting with the code below and inserting it into your Christmas code but I'm having issues getting it to run.  Am I on the right track or should I be approaching this differently?


Code:
from time import sleep, strftime


def write_temp(temp):
   with open("/home/pi/cpu_temp.csv", "a") as log:
       log.write("{0},{1}\n".format(strftime("%Y-%m-%d %H:%M:%S"),str(temp)))

There are a lot of ways to do perform centralized logging. 
I haven't tried it, but if you're using the LoBo build, you could take a look at using MQTT to log to ThingSpeak.  The wiki has an example: https://github.com/loboris/MicroPython_E...thingspeak
Or you could just us MQTT to log to a central broker.
There are also a couple of MicroPython libraries on GitHub that support logging to a remote SysLog server which you could run on a Pi, a server or a NAS.
There are also a few MicroPython database client libraries on GitHub which you could use to log to a remote database such as MySQL or redis.
You might be able to find an online service that provides a REST API for logging.  I've heard of plot.ly but it might be a paid service.

Thank you rdagger!!

Unfortunetly I have zero programming experience but I have definitely learned a lot from your online ESP32 totorials.  I think I need to start at square one for Micropython programming can you please recommend some books or other tutorials that will give me that programming foundation.  I know what I want to do with this project but I’m missing the basics and how to put it together.

Thank you for all your help
Reply
#10
(12-31-2018, 04:55 PM)Dabi Wrote: Thank you rdagger!!

Unfortunetly I have zero programming experience but I have definitely learned a lot from your online ESP32 totorials.  I think I need to start at square one for Micropython programming can you please recommend some books or other tutorials that will give me that programming foundation.  I know what I want to do with this project but I’m missing the basics and how to put it together.

Thank you for all your help

I would start by learning Python 3.  Sentex has a good tutorial series:  https://www.youtube.com/watch?v=oVp1vrfL_w4&list=PLQVvvaa0QuDe8XSftW-RAxdo6OmaeL85M
Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)