---
title: 'Project report - Applied IoT LNU'
---
Tutorial : Dual temperature sensors displayed on ThingSpeak with ESP8266
===
#### Niklas Torstensson
##### nt222iu - niklast@gmail.com
## Table of Contents
[TOC]
Overview
---
In this project, two temperature sensors was connected to a ESP8266 and the measurements sent via Wi-Fi to a ThingSpeak channel for visualisation.
##### Time required: 6-15 hours (depending on knowledge level)
Objective
---
The objective of this tutorial is to combine an ESP2866-board with two temperature sensors, connect the board to the internet and display the result. Whether temperature, humidity or some other physical property is measured, learning how to connect sensors to a board, send the data and displaying it is the first step. To be able to measure water temperature one of the sensors is waterproof. Possible future developments is temperature control for a sous-vide cooking setup or a smoker. Due to material constraints early on focus have been on getting the chosen setup up and running.

Material
---
To be able to perform this tutorial the following material is needed. Presence of hardware, such as a computer possible to connect to micro-USB, is assumed. A MacBook with macOS Monterey was used in the project, other choices of computer setup should work fine but it is possible OS-related troubles occur if using another OS.
The suggested price below have been collected from Amazon, but the material should be easy to find in many stores online as well as IRL. Additional costs for shipping may occur. The equipment actually used in the project was borrowed from a friend and most was bought on aliexpress.
- ESP8266 ~8$
- DS18B20 temperature sensor (10 pcs) ~9$
- DS18B20 waterproof temperature sensor w cable ~11$
- Resistor 4.7 kOhm (100 pcs) ~5$
- (Micro-USB cable ~8$)
- (Breadboard w jumper wires (4 pcs) ~13$)
The most important components are shown below.

The sensor used, DS18B20, is a digital thermometer. On the data sheet, it is explained that each sensor have a unique 64-bit serial code which makes it possible to connect several sensors on the same bus. The sensor can be operated in parasite mode without any local external power supply, instead stealing power from the 1-wire bus and loading a capacitor to provide power when needed. The sensor operates between -55 to 125 degrees Celsius, with a accuracy of 0.5 degrees for much of the range.

Computer setup
---
A Macbook Air was used in this project. To flash the ESP2866-board with MicroPython and to transfer the code from the computer to the ESP2866, Thonny IDE was used. To get Thonny IDE up and running, the instructions on the following link is helpful: https://randomnerdtutorials.com/getting-started-thonny-micropython-python-ide-esp32-esp8266/
Thonny IDE is open source and blocked by Mac OS if the settings is not changed to allow apps to be downloaded from anywhere. To flash the ESP-board, the latest MicroPython version (v1.18 at the time) can be downloaded from https://micropython.org/download/esp8266/.
When the computer is connected to the board, in the menu choose Tools-Options-Interpreter and choose interpreter Micropython (ESP6822) and your port and click "Install or update firmware". Then you select the port and choose your .bin-file as firmware and press "Install". Now the ESP8266 should have the latest version of MicroPython installed.
It is a good idea to save the code both in a folder on the computer and on the ESP8266. That way a safe backup can be kept on the computer and the code on the ESP8266 can be modified without losing anything important. When saving in Thonny IDE, simply chose to save once in the computer and once in the MicroPyton device.

By saving on Micropython device, you upload your code to the device.
Putting everything together
---
The ESP8266 was connected to the sensors via jumper wires to a breadboard and power was supplied by a micro-USB connected to the computer. The pins 'D2', '3V' and 'G' was used when connecting the sensor, see figure below. Between the pins 'D2' and '3V' the resistor is connected. If black, red and yellow jumper wires is connected like in the picture, it is easy to connect also the waterproof sensor which is done in parallell to the other sensor. Simply see to that the colors of the sensor match the jumper wires. In the picture shown the waterproof sensor was moved but if there is room the cables could be put at the same breadboard line number as the first sensor


The first setup with only one sensor is shown below. Note that the sensor is connected with the circular side pointed away from the board. The setups presented is only suitable for experimentation and development and not suitable for production.

Platform
---
In this tutorial, ThingSpeak (https://thingspeak.com/) was used as platform for visualisation. ThingSpeak was chosen due to familarity, it is similar to many other platforms used in the course but has some added functionalities connected to MATLAB. It is free but limited to 3 million messages per year and four channels. Messages can be updated maximum every 15 seconds with the free license.
The most important data from ThingSpeak is the channel ID and the Write API key (Also Read -API for sending data to a device is available, do not mix them up!). You find the information if you click on your project and then click button "API keys". Channel and API code will be used in the code.

The code
---
```python=
#the machine module is needed to connect the GPIO
import machine
import urequests
from machine import Pin
import network, time
#onewire and ds18x20 package is used to interact with
#the sensors
import onewire, ds18x20
import esp
esp.osdebug(None)
HTTP_HEADERS = {'Content-Type': 'application/json'}
THINGSPEAK_WRITE_API_KEY = '->enter your own API key here'
UPDATE_TIME_INTERVAL = 5000 # in ms
last_update = time.ticks_ms()
ssid = '->enter your router SSID here'
password = '->enter your router password here'
# Configure ESP2866 as network station
sta_if=network.WLAN(network.STA_IF)
sta_if.active(True)
if not sta_if.isconnected():
print('connecting to network...')
sta_if.connect(ssid, password)
while not sta_if.isconnected():
pass
print('network config:', sta_if.ifconfig())
#GPIO4 is used, D2 on the ESP8266-board
ds_pin = Pin(4)
ds_sensor = ds18x20.DS18X20(onewire.OneWire(ds_pin))
#scan to find sensors and save them in array
roms = ds_sensor.scan()
print('Sensor list:', roms)
while True:
if time.ticks_ms() - last_update >= UPDATE_TIME_INTERVAL:
#convert the reading from sensor to temperature
ds_sensor.convert_temp()
# a time delay is added to enable the temperature conversion
time.sleep_ms(750)
#get the first and second temp from the first #and second entry in the array with read_temp
temp1 = ds_sensor.read_temp(roms[0])
temp2 = ds_sensor.read_temp(roms[1])
#Field 1 and 2 data is sent to your ThingSpeak channel ID
readings = {'field1':temp1, 'field2':temp2}
request = urequests.post( 'http://api.thingspeak.com/update?api_key=' + THINGSPEAK_WRITE_API_KEY, json = readings, headers = HTTP_HEADERS )
request.close()
print(readings)
```
Transmitting the data /connectivity
---
Using the free alternative on ThingSpeak, data is transferred every 15 seconds. Ten million messages can be stored for free, where a message can contain 8 fields of data but less than 3000 bytes. In this example, two sensors should take up two fields but when sending the data it will still take up one message.
In this project, data was transferred using Wi-Fi and simple http although MQTT is also possible to use on ThingSpeak. The alternative was chosen to get the ESP8266 connected and working as quickly as possible. Wi-Fi does demand quite a lot of power and the range is limited. The range depend on many factors, build quality of the device, weather and whether the unit is outside or inside. About 20 meters inside and 100 meters outside could be possible. The range was not tested in the project.
Presenting the data
---
The data from the sensors is sent to ThingSpeak and added to a channel. It is easy to heat up one of the sensors to identify which one sends its data to Field 1 (the cable) or to Field 2 (the breadboard/station). The result is displayed below.

It is also possible to display a gauge or numeric display by pressing "Add widgets".

The results using gauges can be observed below.

Finalizing the design
---
Considering the limits on equipment and time, the project went very well. By combining different sources on internet it was possible to quickly figure out some working code and get the device up and running and broadcasting to ThingSpeak. I particular appreciate the low cost of device and sensors, making it possible for almost everyone to get a simple project to work on the cheap. Many alternatives exist to display data on internet, ThingSpeak is free as many others and works well with MATLAB which can be useful if the data is to be processed. This was not done in this project.
For future developments, the setup could be improved perhaps by soldering to avoid sensors or jumper wires to get disconnected. It could be interesting to improve range using some antenna or trying out the MQTT protocol or other dashboards. Manipulating the data using the ThingSpeak connection to MATLAB would also be interesting.


