# Tide height monitor
By (rb222gq@student.lnu.se) for the course and Introduction to IoT at Lineaus University
## Overview
This document will introduce the background to the project in the context of the IoT course at Linnaeus University. It will detail the overall aim, and what was done, the hardware procured and software used and written to achieve the aim. This should provide sufficient information for someone to replicate this project. Finally some discussion is presented on what went well, what did not, reflection on the experience of the course, and suggestions as to how the project could be taken forward.
This project aims to build a tide height sensor that has wide utility to measure the heights of bodies of water and at the same time the temperature and humidity and record these regularly over and extended period storing the data for safekeeping in the cloud (Adafruit).
## Background
Tides are the rise and fall of the height of bodies of water caused by the movement of the Earth relative to the moon and the Sun. [https://en.wikipedia.org/wiki/Tide](https://en.wikipedia.org/wiki/Tide). Tides have a long history and have been critical questions in mathematics and earth sciences. They have been of critical military and economic importance with critical historical events such as D-day/The Normandy landings being planned around the tides [https://en.wikipedia.org/wiki/Normandy_landings](https://en.wikipedia.org/wiki/Normandy_landings). So important are the tides books have been written about them and there is little point repeating that here. It will be assumed that the reader understands their significance in the remainder of this report. More background can be found at the Swedish Meteorological service [https://www.smhi.se/en/theme/tides-1.11272#:~:text=Tides%20in%20Swedish%20waters&text=The%20amplitude%20of%20the%20tide,cm%20and%2020%20cm%20respectively](https://www.smhi.se/en/theme/tides-1.11272#:~:text=Tides%20in%20Swedish%20waters&text=The%20amplitude%20of%20the%20tide,cm%20and%2020%20cm%20respectively).
Understanding and modelling the tides have been of significant importance. Historically tides have been measured manually with water gauges and long records of tides at some places, such as important ports, are available going back 100s of years. Important ports tend to be of military or trade significance and are known as standard ports. Nearby ports of significance, but which are not as significant as standard ports are known as secondary ports and also have their tide heights recorded. Over many years of analysis tidal predictions have developed to the point where tables (both paper based and electronic) of tide heights relative to high water and low water are easily available. The prediction in time of high and low tides has also been possible and achieved with high accuracy. [https://en.wikipedia.org/wiki/Standard_port](https://en.wikipedia.org/wiki/Standard_port).
Other places on the coast or on tidal rivers for which tide height estimations are needed have to interpolate in various ways between the nearest standard and/or secondary ports. Freshwater lakes and other non-tidal basins tend not to have tide predictions although they have tides due to the effect of the Sun and the Moon, however, these tend to be smaller than those in coastal and tidal locations as a result they tend not to have measurements of the tides in the systematic way that is performed at standard and secondary ports.
Some locations where the flow of water into and out of an area is constrained by geographic features have small tides even if connected to the oceans. This happens because the flow of water which would otherwise be due to the gravitational attraction of the Sun and the Mood is impeded by these geographic features. The Baltic Sea is one such place with the Danish straits restricting flows. Tidal information is harder to find, although not impossible [https://www.tidetime.org/europe/sweden/](https://www.tidetime.org/europe/sweden/) given the lower population density the distance between places at which tidal information is available is greater and less specific. For example there is no Tide information for Norrtalje and the nearest available tide information is at Vaxholm and Östhammar.
## Aim
Given the rise of cheap IoT devices I decided to see if I could construct a tide height monitor from cheap and simple components, which would allow the collection of tide height both in Sweden and also of more general application to areas with larger tides (e.g. the UK). Such a cheap device could be used to crowdsource much more information on tides in places which are not currently served by official sources of tide information. This can be used as useful information in itself and for research into tides.
## Plans
Given the context of the course on IoT which focuses on using microcontrollers and simple sensors to explore the IoT world an ESP32 Heltech board with WiFi, LoRa and BLE was purchased as well as a HC-SR04 sonar based distance sensor. Tide heights although mainly determined by the position of the Sun and the Moon are also affected by the temperature and humidity, hence, additionally a DHT11 temperature and humidity sensor was purchased for the project. To house these a breadboard and set of connecting wires were used. Various adaptations were tried with the distance sensor to improve performance and limit its focus as discussed below. This resulted in fitting two cardboard tubes to the front of the height sensor to restrict its field of view and focus it on the water and not surrounding obstacles such as the river bank, etc.
## Time for completion
The amount of time for the project was considered to be not more than 2 weeks. In reality given problems with information about how the sensors work and that coding took longer the 3 weeks provided for in the course was just sufficient. The 3 weeks was less than expected due to the problems in obtaining hardware this year.
## The final device
The final product is a proof of concept. It successfully connects to the internet via WiFi, WiFi is supplied by a "MiFi" mobile hotspot. The device is capable of being powered with a small 5000mAh power pack and forwards data via MQTT to the Adafruit on line service which provides a dashboard to display the measured information.
The assembled device is shown below.


## Bill of materials
The following provides a list of all materials needed to replicate this work.
| Number | Item | Number |Cost| Purpose | Source |
|-|-|-|-|-|-|
|1 |ESP32 Heltec controler with LoRa, WiFi, and BLE v2|1|370Skr| Computing IoT device to take readings from the sensors and send them over the internet.|[purchased from Amazon on advise on one of the TAs at https://www.amazon.se/gp/product/B08243JHMW/ref=ppx_yo_dt_b_asin_title_o03_s00?ie=UTF8&psc=1](https://www.amazon.se/gp/product/B08243JHMW/ref=ppx_yo_dt_b_asin_title_o03_s00?ie=UTF8&psc=1).|
|2| one HC-SR04 untrasonic distance sensor |1|59Skr|To measure the height for water from the device| [purchased from Amazon and avaliable at https://www.amazon.se/gp/product/B01DM8MRTS/ref=ppx_yo_dt_b_asin_title_o02_s01?ie=UTF8&psc=1](https://www.amazon.se/gp/product/B01DM8MRTS/ref=ppx_yo_dt_b_asin_title_o02_s01?ie=UTF8&psc=1).|
|3| DHT11 combined temperature and humidity sensor |1 pack|72,15 Skr|pack 2 of 2 only one used.| To measure the temperature and humidity|[purchsed from Amazon and avaliable at https://www.amazon.se/gp/product/B06Y99X3NS/ref=ppx_yo_dt_b_asin_title_o01_s00?ie=UTF8&psc=1](https://www.amazon.se/gp/product/B06Y99X3NS/ref=ppx_yo_dt_b_asin_title_o01_s00?ie=UTF8&psc=1). Only one used|
|4| two tubes of cardbord taken from the centre of a roll of aluminium foil or alternativly some narrow plastic piping 2-2.5cm in diameter and about 30cm long|2| Recycled waste 0 Skr| To provide a narrow apex of vision for the HC-SR04 sensor| [Avaliable from your local supermarket]|(https://www.coop.se/handla/varor/hushall/kok/folie/aluminiumfolie-15-m-7340011452256).
|5| 4 meduim sized cable ties |1 pack| Pack will cost 79 Skr |to hold the cardboard tubes together |[avaliable from Clas Olsen see https://www.clasohlson.com/se/Buntband-vita,-100-pack/p/36-7898](https://www.clasohlson.com/se/Buntband-vita,-100-pack/p/36-7898).|
|6| a small amount of masking tape |1|69,90 Skr|to hold the cardboard tubes to the HC-SR04 sensor|- [purchased from Clas Olsen see https://www.clasohlson.com/se/Maskeringstejp-3-pack/p/30-6533](https://www.clasohlson.com/se/Maskeringstejp-3-pack/p/30-6533).|
|7| a rechargeable battery bank - any battery bank with a reasionable amount of amp hours will do |1|99,90 Skr| Power the ESP32 and sensors|[the one used was from Biltema avaliable at https://www.biltema.se/kontor---teknik/mobiltillbehor/powerpacks/powerpack-5000-mah-2000044214](https://www.biltema.se/kontor---teknik/mobiltillbehor/powerpacks/powerpack-5000-mah-2000044214)|
|8| A combined WiFi and celular device such as the ZTE hot spot |1|About 700Skr Celular data plan and SIM card not included but also needed| I used an old 3G router/range extender and a old 3G the USB modem both of which I had lying around. See discussion below |[avaliable from Telia in Sweden https://www.telia.se/privat/telefoni/produkter-tillbehor/mobilrouter](https://www.telia.se/privat/telefoni/produkter-tillbehor/mobilrouter)|
|10| Breadboard and connceting wires on which to assemble the ESP32 and sensore|1|40 Skr approx|To site the ESP32 and sensors and connect them together| Avalible from Ebay [https://www.ebay.co.uk/itm/121353347660?hash=item1c4139224c:g:sgIAAOSw3Z9ayoJ~](https://www.ebay.co.uk/itm/121353347660?hash=item1c4139224c:g:sgIAAOSw3Z9ayoJ~)|
|13|USB Cable USB A to Micro USB cable|1|20 Skr new|Used to connect the computer to the ESP32 for programming and to the powerbank in operation|
The following tools and supplies are needed:
| Number | Item | Number |Price| Purpose | Source |
|-|-|-|-|-|-|
|12| a Soldering Iron to solder the pins on to the ESP32 |1|129 Skr|To solder the pin conncetors to the ESP32|[avaliable from Clas Olsen https://www.clasohlson.com/se/Lödpenna-Cocraft-HS-30L/p/41-1364](https://www.clasohlson.com/se/Lödpenna-Cocraft-HS-30L/p/41-1364).|
|13| solder for the above soldering iron and solder removal tool |1|79,90 Skr|To solder the pin conncetors to the ESP32|[avaliable from Clas Olsen see and https://www.clasohlson.com/se/Tennsug/p/40-9690](https://www.clasohlson.com/se/Tennsug/p/40-9690) and [see https://www.clasohlson.com/se/Lödtenn-blyfritt/p/30-9862](https://www.clasohlson.com/se/Lödtenn-blyfritt/p/30-9862).
|14| some solder flux will help with soldering |1|29,90 Skr|To assist with soldering |[avaliable from Jula see https://www.jula.se/catalog/verktyg-och-maskiner/svets-och-lod/lod/lodtrad-pasta-och-lod/lodfett-214005/](https://www.jula.se/catalog/verktyg-och-maskiner/svets-och-lod/lod/lodtrad-pasta-och-lod/lodfett-214005/) |
### Discussion and alternatives in materials
The connectivity of the Heltech board offers a lot of possibilities. The LoRaWan capabilities could be used. This was tried and there is code to do this in the software written. However it was found that in Norrtalje there is no Helium or Things network connectivity (despite what is claimed on the Helium web site) so that code is currently disabled. The device was taken right into the centre of the Helium cell to check this but was not able to connect. This could be a sighting issue for the Helium hotspot or simply old information on the Helium site. The device was taken into Stockholm and a coverage area and duly completed Over the Air Activation gaining my account more Helium credits and verifying the code. However, in order to take the project forward alternatives were used.
A BLE connection could also be used, say to connect via BLE to a BLE modem such as a mobile phone, but this was not tried.
In the end, in the face of LoRaWan issues, a simpler solution was used of using a MiFi style mobile internet hotspot solution. I used an old 3G Chinese router which functions as a range extender/modem sharing device/and other functions and can take a USB mobile 3/4G mobile internet modem and share this connection via WiFi. The Chinese router has its own internal battery and can be used independently or also powered from or chained on to the power bank (this will require one extra USB cable).

Any similar device that connects via the mobile network with a data connection and shares this via WiFi will do. Another device for example is the Osprey 4G router which are popular and available
[https://www.mobilefun.co.uk/ee-osprey-2-mini-mobile-4g-wifi-6gb-53465](https://www.mobilefun.co.uk/ee-osprey-2-mini-mobile-4g-wifi-6gb-53465). This device also has its own internal battery and shuts down when the internet is not being used, saving battery.
There are lots and lots of other possibilites for this functionality, indeed some 4G USB modems such as [https://www.ebay.co.uk/itm/265676310906?hash=item3ddb8ac97a:g:QOIAAOSwLCZiciZ1](https://www.ebay.co.uk/itm/265676310906?hash=item3ddb8ac97a:g:QOIAAOSwLCZiciZ1) have a built in WiFi hotspot which can share the data connection meaning they can simply plug into the second USB A port on the power bank. In fact having such a device may be beneficial as it reduces the number of points of failure as if internet connectivity failed the device cannot share data.
As mentioned in the presentation in a place such as Norrtalje town centre, the original initial site, there is also the possibility to use the nearby pubs and bar's WiFi networks. The code contains functionality to cycle through a list of WiFi networks trying each sequentially until it gets a connection. This would obviously be of less use in more rural locations.
One final alternative is discussed in the discussion and reflection below of using LoRa with satellites like those in the Tidy GS project [https://tinygs.com/](https://tinygs.com/)
## Hardware construction, assembly, and configuration
In order to construct the device the following need to be done.
The pins supplied with the ESP32 should be soldered onto the main ESP32 board and this seated in the breadboard. The ESP32 for ease should be placed at one end with the Micro USB connector on the ESP32 being at the end of the breadboard. Pin 2 on the left of the board (looking at it from above with the micro USB connector at north) should be connected to the "+" red bus/strip on the far left of the breadboard thereby providing a 5 volt bus. Similarly pin 1 on the right hand side should be connected to the blue bus/strip on the far right of the breadboard thereby providing a ground bus.This should be done with the connecting cables or wires that come with the breadboard.
The DHT11 sensor should be seated on the breadboard and connected to pins according to the pinout description that can be found at [https://escapequotes.net/esp32-lora-heltec-v2-with-display-pinout-diagram/](https://escapequotes.net/esp32-lora-heltec-v2-with-display-pinout-diagram/ "ESP32 Pin out") with the "+" pin being connected to the 5 volt bus on the far left and the "-" pin connected to the "-" ground bus strip on the far right. The middle pin should be connected to pin "P10" of the ESP32. The pin used is defined in the file my_dht11.py file in the lib folder.
The two cardboard tubes should be lined up parallel and a cable tie wrapped around them at each end in a figure of 8 shape so that the tubes poke through the holes in the 8 shape of the cable tie. A further cable tie should be wrapped around them in the same way in the middle to add stability.

Additionally the masking tape should be wrapped around the tubes across the length to add strength. The SR-HC04 sensor should be inserted into on end of the pair of tubes. The crystal at the top middle of the sensor (with the letters "Y1" underneeth) should sit on top of the outside of the 2 tubes.

Finally the HC-SR04 sensor should be secured to the tubes with masking tape. The sensor and tubes should then be seated on the edge of the breadboard and the whole assembly attached to the breadboard with a cable tie.

Finally the sensor should be connected on the breadboard with the "+" going to the positive 5 volt bus strip on the far left, the "-" to the ground bus strip on the far right. The trigger pin should be connected to the "P9" on the ESP32 and the echo to pin "P13" on the ESP32.
### A note on ESP32 pin numbering
When referring to pins in quotes such as "P9" I am referring to the standardised pin numbering presented in the following diagram with pin numbers in white on a black background.

When referring to pin 2 on the left hand side I am referring to the second pin down on the left from the top. The top being the edge of the Heltec board with the micro USB connector on.
The USB cable should be first connected to a PC with relevant software discussed below to program the ESP32 and then the power bank should be charged and connected to the ESP32's micro USB connection with the USB cable. The mobile WiFi should be similarly assembled and configured with a SID selection that matches that given in the code on line 45-49 in main.py. This has a structure which contains a series of tuples of WiFi Sid, WiFi password, length of time to try connecting to, and mode (a choice from the network module
https://docs.pycom.io/firmwareapi/pycom/network/wlan/ or network.WLAN.WPA, network.WLAN.WPA2, or network.WLAN.WEP)
The final construction should conceptually look like the following diagram (omitting the cardboard tubes and USB power connection)
 and in practice like the picture above.
Beyond a proof of concept the whole assembly and a configured 3/4G mobile router should be enclosed in a suitable enclosure with holes for the tubes to stick out and be sealed to protect from water intrusion.
## Software configuration
For this project the board was flashed with the Pycom Micropython firmware using the online web flasher[https://nabucasa.github.io/esp-web-flasher/](https://nabucasa.github.io/esp-web-flasher/) as specified in the instructions for the course [https://hackmd.io/@lnu-iot/By5ZUqvOq](https://hackmd.io/@lnu-iot/By5ZUqvOq "Flash Micropython firmware"). The proof of concept was programmed on a Mac but the same can be achieved with the relevant tools for Linux or Windows.
Code was written in the Atom IDE [https://atom.io/](https://atom.io/ "Atom IDE") to read the sensors and forward readings over the internet to AdaFruit. Atom is used to upload the Python code to the ESP32 once flashed with MicroPython and should also be installed on the PC/Mac. Atom requires Nodejs and the Pymaker plugin for Atom. This can be achieved by following the instructions at [https://hackmd.io/@lnu-iot/SydH7MTcw](https://hackmd.io/@lnu-iot/SydH7MTcw).
The code written can be found at the following GitHub site [https://github.com/rb222gq/LNU-IoT-Tide-height-monitor](https://github.com/rb222gq/LNU-IoT-Tide-height-monitor). This can be downloaded with git, e.g. on the command line run "git clone https://github.com/rb222gq/LNU-IoT-Tide-height-monitor"
The code although a proof of concept, but, sucesfully reads the sensors and sends the readings over the internet to Adafruit.
### Adafruit account needed
In order to replicate this project you need to set up an Adafruit account for the dashboard to receive the measurements taken by the device. This can be done at [https://accounts.adafruit.com/users/sign_in](https://accounts.adafruit.com/users/sign_in). You will also need to create 3 feeds one for each for the readings for temperature, humidity, and distance. You should also create dashboards for each of these. There is also functionality in the code which is currently disabled to stop the device and drop back into MicroPython. This was added in as using "CTRL-C" with Atom. It is activated by pressing a stop button on the dashboard which sends a signal via MQTT to the device. An illustration of the dashboard is shown below.

To replicate the project you will need to change the code in the file my_mqtt_class.py to appropriate settings. The following variables need to be adjusted:
| variable | purpose|
|-|-|
|AIO_USER | Ada Fruit username, e.g. "rb22gq"|
|AIO_KEY | key to authenticate devide to Ada Fruit created from within the Ada Fruit Website. See the course documentation at [https://hackmd.io/@lnu-iot/ByPRkQTF9](https://hackmd.io/@lnu-iot/ByPRkQTF9)|
|AIO_CONTROL_FEED | The URL provided by Ada Fruit for your Control Feed e.g. "rb222gq/feeds/lnu-tide-sensor.stopbutton"|
|ADAFRUIT_TEMPERATURE_FEED| The Ada Fruit provided URL for your temperature feed, example: "rb222gq/feeds/temperature"|
|ADAFRUIT_HUMIDITY_FEED |The Ada Fruit provided URL for your humidity feed, example: "rb222gq/feeds/humidity"
|ADAFRUIT_WATERHEIGTH_FEED | The Ada Fruit provided URL for your height (of the water) feed, example: "rb222gq/feeds/water-height"|
## About the sensors
### HC-SR04

The HC-SR04 data sheet can be found at [https://cdn.sparkfun.com/datasheets/Sensors/Proximity/HCSR04.pdf](https://cdn.sparkfun.com/datasheets/Sensors/Proximity/HCSR04.pdf) and https://www.electroschematics.com/wp-content/uploads/2013/07/HC-SR04-datasheet-version-2.pdf.
The device sends ultrasonic sound out of the left lobe and listens for reflections received by the right lobe.
The code for this sensor is contained in hcsr04.py and my_hcsr04.py. The former was taken from code on GitHub written by one of the TAs on the course itself taken from code given to that TA by another TA and objectified and then debugged by me. My own code in my_hcsr04.py is an object wrapper written by me abstracting away the hardware specifics. If you want to change the pins used to connect to the trigger or echo pins on the sensor this is done in the first 2 lines of the __init__ function in this file.
The code provides an object which can be used to read the current tide height and find the last reading taken.
The main issue with this sensor is the wide aperture of measurement. The datasheet shows the following diagram for the span of measurement of objects that the sensor will detect.

As described below testing of this proof of concept project had to be done at a sink to simulate the rise and fall of a tide and the span of the sensor was thought to be too wide. To narrow the focus of the sensor the tubes were fitted to narrow this span and act on the ultrasonic sensing in a parallel way that looking down the tubes narrows the vision.
This is important as the code and the hardware picks up the first reflected sound, hence narrowing the vision of the ultrasonic sight of the sensor focuses it on the water.
### DHT11

The DNT11 is a fairly standard temperature and humitidy sensor. Code supplied by one of the TAs is in dht.py and an objectified wrapper to this in my_dht11.py. This sensor was found to work out of the box once the interface voltages had been understood.
The data sheet for the sensor can be found here [https://www.mouser.com/datasheet/2/758/DHT11-Technical-Data-Sheet-Translated-Version-1143054.pdf](https://www.mouser.com/datasheet/2/758/DHT11-Technical-Data-Sheet-Translated-Version-1143054.pdf)
and [https://components101.com/sensors/dht11-temperature-sensor](https://components101.com/sensors/dht11-temperature-sensor).
#### Voltage supply to the sensors
It had been initially understood from TAs that a drop down ladder of resistors was needed to supply both the HC-SR04 and the DHT11 with 3.3 volts power. This was implemented with one 100k resistor and a 200k resistor. However, this did not work and the ESP32's readings made no sense. Once the sensors were connected to the correct 5 volt bus they worked as expected.
### On board OLED display
The OLED display is used to display connection diagnostic information when the internet is being set up as shown below. When LoRa is enabled it shows the frequency, when WiFi is enabled it shows the SID of the network it is trying to join. A simple counter is at the bottom:

When connected it show the current status of the connections including the LoRa Freuency, the WiFi SID connected to, its IP address, the WiFi channel in use, and the and sensor reading information on the bottom line in a format "T< temperature >|H< Humidity >|L< Distance >" as shown below.

## Breif documentation on the code
|file|directory|purpose|notes|
|-|-|-|-|
|dht.py|lib|Code to use the DHT11 sensor to take readings| Taken from on of the TAs|
|Display_class.py|lib|Contins objectified code to control the OLED screen| used to display status information on the OLED screen|
|hcsr04.py|lib|Code taken from the web and the TAs to control the HC-SR04 sensor to measure distance||
|my_mqtt.py|lib|Object wrapper containing specific subsription details for the account used with Adafruit.|
|my_hcsr04.py|lib|My own objectified interface to hcsr04.py and includes hardware details and specifics of which of the ESP32 pins are used with the HC-SR04.|Change the lines "self.echopin = Pin('P13', mode=Pin.IN)" and "self.triggerpin = Pin('P9', mode=Pin.OUT)" to change the pins used to control the HC-SR04. Replacing 'P9' and 'P13' with the appropriate pin numbers as per the pinout diagram above.|
|my_LED.py|lib|Code to control a LED.|Not used|
|my_mqtt_class.py|lib|An attempt to objectify functions and code in mqtt.py.|Not used at present|
|my_dht11.py|lib|My objectified interface to dht.py and includes hardware details of which of the ESP32 pins are used with the DHT11 sensor. If you want to change the pin used with the DHT11 change the line "self.pin = 'P10'" in the __init__() function||
|mqtt.py|lib|Code taken from the course to send data to Adafruit. ||
|OLEDControl|lib|Base class to control the OLED display, used by Display_class.py||
|ssd1306.py|lib|base class to control the OLED display| user by OLEDControl.py|
|LNU IoT Presentation1.pdf|Presentation|Copy of the presentation given|not part of code|
|boot.py|top|initial file read by ESP32|contans mostly redundent code|
|distance_function.py|top|Not used|used in testing|
|loop.py|top|not used|used for debugging|
|LoRaFunctions|top|Functions to connect to the Helium Network|
|main.py|top|main code file|
|ttn.py|top|not used|initial work on using The Things Network|
|WiFiFunctions.py|top|Contains the WiFi connection function do_connect()|Taken from code supplied by the course and enhanced|
## Choice of platform
The ESP32 was chosen for its connectivity and availability given the main Pycom boards used on the course were not available. LoRaWan was preferred given the potential locations and low amounts of data used in the project. However, the alternative arrived at with a mobile hotspot is a reasonable compromise.
I was new to IoT dashboards and running out of time towards the end of the project. Adafruit worked with the code supplied on the course. Having briefly looked at others there was little difference between them, Adafruit did what was needed and the free tier worked for the project and fitted in with a cheap device. Using Adafruit meant using MQTT so there was no investigation of alternatives. One significant alternative there was not time for investigation of, would be to abandon connectivity at all and simply store the data locally. Again this is possible in simple files and there was no time for investigation of more sophisticated databases. The data is not needed in real time as the intention is to analyse this at a later time. Instead the inbuilt WiFi hotspot functionality of the ESP32 could be used with security settings turned on and data collected by simply visiting the sites of deployed devices and downloading the latest batch of data. As the device could run for quite a few weeks on the powerbank, especially with no connectivity requirement it would be possible to have a round for someone to follow and collect data from a large number of copies of the device in different locations with almost drive-by data collection. Such a solution would also allow a large number of sensors to be deployed. If a crowdsourced data approach was taken though connectivity would be a requirement.
## Testing
Due to the fragility of the prototype, the lack of enclosure, the risk of theft, and lack of permission to attach the device to street furniture in the initial location the device's functionality was tested in an improvised setting. A sink was utilised to play the role of a tidal basin. In the sink was a cleaning cloth and a scrubbing pad. These were placed over the sinkhole. The rising of the tide was simulated by turning on the tap and letting the sink fill. The cleaning cloth and the scrubbing pad inhibit the flow of water out of the sink. Then the tap was turned off and the water gradually drained through the cleaning cloth and scrubbing pad to simulate lowering of the tide. The prototype was mounted above the sink with some clips and a length of bungie cord. It successfully measured the changing height of the water.


You can see the prototype in testing working in the video at this link [https://drive.google.com/file/d/1Zit1lT7qlo-x3II6khKAEShb-44kARmO/view?usp=sharing](https://drive.google.com/file/d/1Zit1lT7qlo-x3II6khKAEShb-44kARmO/view?usp=sharing)
## Functionality of the code
How the ESP32 operates with the Pycom Micropython firmware. The written code provides functionality to take a reading and send this to Adafruit via WiFi.
The code has a list of WiFi Networks, parameters, and WiFi passwords to try so that it is not fixed to one WiFi network. This was written to enable the utilisation of WiFi networks near the location and also the possibility to mount separately the WiFi connectivity. In the code although disabled the code also can try and get a LoRa was connection and will go with whichever works first. However as the LoRa did not work the code to send MQTT over LoRa is not written.
On the Adafruit dashboard there is a STOP button this was implemented to stop the device as problems in the code development were encountered where a "CRTL-C" would not stop. Pressing the Stop button will send a MQTT message to the device which will then within an if clause execute a non-existent instruction and cause the Micropython to return to the ">" prompt.
## Discussion, reflection, and conclusions
### Hardware
Soldering the pins to the ESP32 turned out to be hard and difficult. I was continually afraid of damaging the Oled on the ESP32 when soldering and only in the end soldered enough pins to get the project going. This resulted in dropping the idea of using a LED which was intended to show internet connectivity. A better soldering iron and tip may help, but, ultimately a lesson learned is to purchase a ESP32 or other microcontroller with pre-soldered pins.
The misunderstandings about voltage levels wasted time and were I to do this project again I would start by reading the technical specification sheets more thoroughly.
In the beginning of the project there were many misunderstandings about how the HC-SR04 sensor worked. With the benefit of hindsight these were silly and the way it worked was obvious and would have ruled out some of the very original ideas not discussed here. Again a better understanding of the proposed hardware and not being overwhelmed by details are the learning points here.
On a positive note the use of the cardboard tubes turned out to be a very smart idea and reused some everyday waste in a very creative and useful way.
### Software
It was my first try at some real Object Oriented programming for me, but, coming from a more functional background it was too easy to create code with memory leaks.
The code as it is needs a through tidy. Although functional there is much redundant code and even code to turn a LED on and off which is disabled and not used. This was originally meant to show connection to the internet or LoRaWan network, but the Oled is used. This currently shows the connection status of LoRa and WiFi displaying the SID and the IP address if connected via WiFi and the frequency for LoRa. After connection in addition it displayed the current readings. However, the readings are in small type at the bottom of the screen and more could be done with this perhaps alternating every few seconds between connection information and readings in a larger font. This is why the OLEDControl.py and Display_class.py files were separated out of the main code. This was not finished in time for the project but is far from impossible to achieve given time.
It was originally an ambition to initially store the readings in a table structure and then attempt to forward them to Adafruit with the readings remaining in the table if the connection failed for forwarding in subsequent run which collected readings. However this was not achieved and this would be a significant improvement along with a tidy of the code. Currently the device simply tried to connect and send readings. If the connection fails it reboots and tries the connection again with some readings lost.
The current code only measures distance from sensor (wherever mounted) to the water not the actual tide height. This could be computed knowing the distance from the sensor to the bottom of the water at a location, but, this needs to be calibrated and the data recorded post processed to take account of this. This could easily be achieved in code to provide a actual tide height to Adafruit. Perhaps the relevant informtion could be read from Adafruit to simplify this and ease redeployment.
The code and dashboard also need to be re-designed to take into account there could be more than one such sensor device.
### Taking it forward
As already said the device should be enclosed in a waterproof enclosure such as a watertight food box with some holes drilled so that the tubes can extend out. For real deployment the tubes should be replaced by plastic pipes of the same dimensions.
A useful enhancement would be to add a GY-68 BMP180 Barometer Temperature and Atmosphere Pressure Sensor to measure the atmospheric pressure as this can affect the tides as well, although at this point we are really taking the project to its limits.
It would be useful to have LoRaLan working. This technology would be ideal for this kind of project. It not only uses less power but gives the potential of remote sensing with less concerns for coverage. However, the coverage in more rural parts of Stockholm County is too poor to make this viable at present. One alternative considered but not pursued would be to use the TinyGS satellite network. This consists of a set of Satellites which orbit the Earth in low orbit and can send and receive LoRa transmissions [https://tinygs.com/](https://tinygs.com/). Unfortunately at the time of the project I was advised that the Tiny GS network only broadcast signals. Previously they had carried messages between nodes, but, this was not working in the project duration, but is hopefully something that can be achieved in the future. This would mean a number of devices could be deployed and return data to a central node with a connection to the Internet for forwarding to Adafruit at the expense of a central note.
### What went wrong
Some things that got in the way of the project, namely late decisions about which hardware to purchase, late delivery by PostNord and Bring of parcels containing ordered hardware, lack of clarity at the beginning of the course about which project to try and having sufficient implementation ideas to order hardware early in the course. Lack of an enclosure meant that it was not practical to take the device outside and test in the wild.
Lack of experience coding Objected oriented code also used a fair amount of time.
More time could have been spent for example computing the power consumption of the ESP32 and sensors and how long the powerbank would last. Time was a big factor in this project.
### Conclusions
In conclusion this was an interesting project introducing many aspect of IoT that need to be considered. It was a real baptism of fire and considerable ingenuity and creativity have been used to produce a relatively cheep proof of concept device with a lot of ways of developing it. Overall despite the difficulties it was fun to do this project and even though the final device is still somewhat fragile and the limitations detailed above still present, a sense of achievement and confidence in doing similar projects has been achieved.
(c) 2020