MicroPython MicroPython with ESP32 and ESP8266 Project Tech

MicroPython: DS18B20 Temperature Sensor with ESP32 and ESP8266

MicroPython DS18B20 Temperature Sensor with ESP32 and ESP8266 (Single sensor, Multiple sensors and Web Server example)

This tutorial exhibits how one can use the DS18B20 temperature sensor with the ESP32 and ESP8266 utilizing MicroPython firmware. You’ll discover ways to learn temperature from one DS18B20 sensor and a number of sensors on the similar time. You’ll additionally construct an internet server to show your sensor readings.

MicroPython DS18B20 Temperature Sensor with ESP32 and ESP8266 (Single sensor, Multiple sensors and Web Server example)

Conditions

To comply with this tutorial you want MicroPython firmware put in in your ESP32 or ESP8266 boards. You additionally want an IDE to put in writing and add the code to your board. We propose utilizing Thonny IDE or uPyCraft IDE:

Study extra about MicroPython: MicroPython Programming with ESP32 and ESP8266 eBook

Introducing DS18B20 Temperature Sensor

The DS18B20 temperature sensor is a one-wire digital temperature sensor. Because of this it simply requires one knowledge line (and GND) to speak together with your ESP32 or ESP8266.

It may be powered by an exterior energy provide or it may derive energy from the info line (referred to as “parasite mode”), which eliminates the necessity for an exterior energy provide.

DS18B20 Temperature Sensor Pinout Pins

Every DS18B20 temperature sensor has a singular 64-bit serial code. This lets you wire a number of sensors to the identical knowledge wire. So, you will get temperature from a number of sensors utilizing only one GPIO.

The DS18B20 temperature sensor can also be out there in waterproof model.

DS18B20 Temperature Sensor Waterproof version

Right here’s a abstract of probably the most related specs of the DS18B20 temperature sensor:

  • Communicates over one-wire bus
  • Energy provide vary: three.0V to five.5V
  • Working temperature vary: -55ºC to +125ºC
  • Accuracy +/-Zero.5 ºC (between the vary -10ºC to 85ºC)

For extra info seek the advice of the DS18B20 datasheet.

Elements Required

To comply with this tutorial you want the next elements:

You need to use the previous hyperlinks or go on to MakerAdvisor.com/instruments to seek out all of the elements on your tasks at one of the best worth!

Schematic – ESP32

As talked about beforehand, the DS18B20 temperature sensor may be powered by means of the VDD pin (regular mode), or it may derive its energy from the info line (parasite mode). You’ll be able to selected both modes.

Should you’re utilizing an ESP32, folllow one in every of these two schematic diagrams.

Parasite Mode

DS18B20 Temperature Sensor with ESP32 Parasite Mode Wiring Schematic Diagram

Regular Mode

DS18B20 Temperature Sensor with ESP32 Normal Mode Wiring Schematic Diagram

Schematic – ESP8266

In case you’re utilizing an ESP8266, comply with considered one of these two schematic diagrams.

Parasite mode

DS18B20 Temperature Sensor with ESP8266 Parasite Mode Wiring Schematic Diagram

Regular mode

DS18B20 Temperature Sensor with ESP8266 Normal Mode Wiring Schematic Diagram

Observe: on this tutorial we’re connecting the DS18B20 knowledge line to GPIO four, however you need to use another appropriate GPIO.

Code (Single DS18B20)

Copy the next code to the primary.py file and add it to your board. This code merely will get temperature from the DS18B20 temperature sensor and shows the readings on the shell.

# Full challenge particulars at https://RandomNerdTutorials.com

import machine, onewire, ds18x20, time

ds_pin = machine.Pin(four)
ds_sensor = ds18x20.DS18X20(onewire.OneWire(ds_pin))

roms = ds_sensor.scan()
print(‘Discovered DS units: ‘, roms)

whereas True:
ds_sensor.convert_temp()
time.sleep_ms(750)
for rom in roms:
print(rom)
print(ds_sensor.read_temp(rom))
time.sleep(5)

View uncooked code

This code works each with the EPS32 and ESP8266 and works whether or not you’re utilizing one or a number of DS18B20 temperature sensors.

How the code works

Import the machine module to work together with the GPIOs, the onewire and the ds18x20 modules to work together with the DS18B20 temperature sensor and the time module so as to add delays.

import machine, onewire, ds18x20, time

Create a variable referred to as ds_pin that refers to GPIO four, the pin the info wire of the DS18B20 temperature sensor is related to.

ds_pin = machine.Pin(four)

Right here, we’re studying the temperature from GPIO four, however you should use some other appropriate GPIO. You possibly can verify one of the best GPIOs to make use of on the next articles:

Then, create a ds18x20 object referred to as ds_sensor on the ds_pin outlined earlier. If you wish to learn the sensor utilizing a unique pin, you must modify the earlier line.

ds_sensor = ds18x20.DS18X20(onewire.OneWire(ds_pin))

The DS18B20 communicates by way of one-wire communication protocol and every sensor has a singular 64-bit serial code. This implies you possibly can learn a number of temperature sensors wired on the identical GPIO.

The next line makes use of the scan() perform to scan for DS18B20 sensors. The addresses discovered are saved on the roms variable (the roms variable is of sort record).

roms = ds_sensor.scan()

Print the tackle of every sensor to the shell:

print(‘Discovered DS units: ‘, roms)

Then, there’s some time loop that will get the temperature from the DS18B20 sensor(s) each 5 seconds.

It is advisable name the convert_temp() perform on the ds_sensor object every time you need to pattern temperature.

ds_sensor.convert_temp()

Add a delay of 750 ms to offer sufficient time to transform the temperature:

time.sleep_ms(750)

After that, we will learn the temperature on the addresses discovered earlier through the use of the read_temp() technique and passing the handle as argument as proven within the following line of code.

print(ds_sensor.read_temp(rom))

As a result of you’ll be able to add a number of sensors to the identical knowledge line, we now have a for loop that goes by means of all of the addresses and prints the temperature for every of them:

for rom in roms:
print(rom)
print(ds_sensor.read_temp(rom))

Demonstration

After importing the code to your board, it is best to get new temperature readings each 5 seconds.

DS18B20 Temperature readings MicroPython with ESP32 and ESP8266

Getting Temperature from A number of DS18B20 Temperature Sensors

DS18B20 Multiple Sensors with ESP8266

To get temperature from a number of DS18B20 temperature sensors, you should use the identical earlier script. You simply have to wire extra DS18B20 sensors. These sensors share the identical knowledge line – on this case, all sensors are wired to GPIO four.

For those who’re utilizing an ESP32, you possibly can comply with the subsequent schematic diagram.

DS18B20 Multiple Temperature Sensors with ESP32 Wiring Schematic Diagram

In the event you’re utilizing an ESP8266, comply with the subsequent schematic diagram as an alternative.

DS18B20 Multiple Temperature Sensors with ESP8266 Wiring Schematic Diagram

Code (A number of DS18B20s)

After importing the code, it is best to get all temperature readings displayed within the Shell.

# Full venture particulars at https://RandomNerdTutorials.com

import machine, onewire, ds18x20, time

ds_pin = machine.Pin(four)
ds_sensor = ds18x20.DS18X20(onewire.OneWire(ds_pin))

roms = ds_sensor.scan()
print(‘Discovered DS units: ‘, roms)

whereas True:
ds_sensor.convert_temp()
time.sleep_ms(750)
for rom in roms:
print(rom)
print(ds_sensor.read_temp(rom))
time.sleep(5)

View uncooked code

Multiple DS18B20 Temperature readings MicroPython with ESP32 and ESP8266

Show DS18B20 Temperature Readings on Net Server

Display DS18B20 Temperature Readings on Web Server MicroPython

Now that you understand how to get temperature and humidity from DS18B20 sensors, we’ll show the readings on an internet server that you would be able to entry in your native community.

For this instance, you want two information:

  • boot.py: runs when the system begins and units up a number of configuration choices like your community credentials, importing libraries, setting the pins, and so forth.
  • major.py: that is the primary script the place we’ll deal with the online server. It executes instantly after the boot.py.

Observe: it’s a good follow to incorporate the boot.py and most important.py information. Nevertheless, when you want, you’ll be able to embrace all of the code in the primary.py file.

boot.py (DS18B20 net server)

Create a brand new file in your IDE referred to as boot.py and replica the next code.

# Full undertaking particulars at https://RandomNerdTutorials.com

attempt:
import usocket as socket
besides:
import socket

from time import sleep
from machine import Pin
import onewire, ds18x20

import community

import esp
esp.osdebug(None)

import gc
gc.acquire()

ds_pin = Pin(four)
ds_sensor = ds18x20.DS18X20(onewire.OneWire(ds_pin))

ssid = ‘REPLACE_WITH_YOUR_SSID’
password = ‘REPLACE_WITH_YOUR_PASSWORD’

station = community.WLAN(community.STA_IF)

station.lively(True)
station.join(ssid, password)

whereas station.isconnected() == False:
move

print(‘Connection profitable’)
print(station.ifconfig())

View uncooked code

This file imports the required libraries, units up the DS18B20 sensor and connects to your community.

Right here, we’re setting the DS18B20 knowledge pin on GPIO four however you should use some other appropriate pin:

ds_pin = Pin(four)
ds_sensor = ds18x20.DS18X20(onewire.OneWire(ds_pin))

You must insert your community credentials within the following variables in order that the ESP is in a position to hook up with your community.

ssid = ‘REPLACE_WITH_YOUR_SSID’
password = ‘REPLACE_WITH_YOUR_PASSWORD’

essential.py (DS18B20 net server)

Within the fundamental.py file is the place we’ll create the online server and deal with the requests. Copy the next code to your principal.py file.

# Full venture particulars at https://RandomNerdTutorials.com

def read_ds_sensor():
roms = ds_sensor.scan()
print(‘Discovered DS units: ‘, roms)
print(‘Temperatures: ‘)
ds_sensor.convert_temp()
for rom in roms:
temp = ds_sensor.read_temp(rom)
if isinstance(temp, float):
msg = spherical(temp, 2)
print(temp, finish=’ ‘)
print(‘Legitimate temperature’)
return msg
return b’Zero.Zero’

def web_page():
temp = read_ds_sensor()
html = “””

html font-family: Arial; show: inline-block; margin: 0px auto; text-align: middle;
h2 font-size: three.0rem; p font-size: three.0rem; .models font-size: 1.2rem;
.ds-labels font-size: 1.5rem; vertical-align:center; padding-bottom: 15px;

ESP with DS18B20


Temperature
“”” + str(temp) + “””
°C


Temperature
“”” + str(spherical(temp * (9/5) + 32.Zero, 2)) + “””
°F

“””
return html

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((”, 80))
s.pay attention(5)

whereas True:
attempt:
if gc.mem_free() < 102000:
gc.acquire()
conn, addr = s.settle for()
conn.settimeout(three.Zero)
print('Received a connection from %s' % str(addr))
request = conn.recv(1024)
conn.settimeout(None)
request = str(request)
print('Content material = %s' % request)
response = web_page()
conn.ship('HTTP/1.1 200 OKn')
conn.ship('Content material-Sort: textual content/htmln')
conn.ship('Connection: closenn')
conn.sendall(response)
conn.shut()
besides OSError as e:
conn.shut()
print('Connection closed')

View uncooked code

Studying the DS18B20 Sensor

The code begins by making a perform referred to as read_ds_sensor() that will get the temperature from the DS18B20 temperature sensor. In the event you’ve adopted the earlier part, you ought to be accustomed to the strategies used right here.

def read_ds_sensor():
roms = ds_sensor.scan()
print(‘Discovered DS units: ‘, roms)
ds_sensor.convert_temp()
for rom in roms:
temp = ds_sensor.read_temp(rom)
if isinstance(temp, float):
temp = spherical(temp, 2)
print(‘Legitimate temperature’)
return temp
return ‘Zero’

Net Web page

The web_page() perform returns the HTML web page with the newest temperature readings.

We’ve constructed an identical net web page on a earlier tutorial. So, if you wish to find out how this HTML works, you’ll be able to learn this text: MicroPython: ESP32/ESP8266 with DHT11/DHT22 Net Server.

Creating the online server

After that, make the standard procedures to create a socket server.

whereas True:
attempt:
if gc.mem_free() < 102000:
gc.gather()
conn, addr = s.settle for()
conn.settimeout(three.Zero)
print('Obtained a connection from %s' % str(addr))
request = conn.recv(1024)
conn.settimeout(None)
request = str(request)
print('Content material = %s' % request)
response = web_page()
conn.ship('HTTP/1.1 200 OKn')
conn.ship('Content material-Sort: textual content/htmln')
conn.ship('Connection: closenn')
conn.sendall(response)
conn.shut()
besides OSError as e:
conn.shut()
print('Connection closed')

For an in-depth rationalization of this process, discuss with this tutorial.

Principally, when the ESP receives a request, we ship the online web page with the newest readings as a response:

response = web_page()
conn.ship(‘HTTP/1.1 200 OKn’)
conn.ship(‘Content material-Sort: textual content/htmln’)
conn.ship(‘Connection: closenn’)
conn.sendall(response)

Net Server Demonstration

After importing the boot.py and major.py information to your board. Click on the ESP RST button to run the code.

Then, open your browser and sort the ESP IP handle. You need to entry the online web page with the newest sensor readings in Celsius and Fahrenheit levels:

DS18B20 Temperature Readings on ESP32 ESP8266 Web Server

Wrapping Up

We hope you’ve discovered this MicroPython information concerning the DS18B20 temperature sensor with the ESP32 and ESP8266 helpful. We have now different tasks with the ESP and MicroPython that you could be like:

Study extra about MicroPython with ESP32 and ESP8266 with our eBook: MicroPython Programming with ESP32 and ESP8266

Thanks for studying.