# Water temperature monitoring By Pernilla Rydmark (pr222me), in July 2022, during a summer course at Linnaeus University in Sweden, [1DT305 - Introduction to Applied IoT](https://https://lnu-ftk.instructure.com/courses/233). ![](https://i.imgur.com/0C2Y7NI.jpg) **Table of contents** [TOC] --- ## Project overview This project is a prototype of a water monitoring system that uses Pycom’s Fipy development board and PySense V.2.0 expansion board. It measures temperature with a sensor, sends data regularly to the Datacake cloud, and publishes data on the internet. The code is written in [MicroPython](https://micropython.org/). This project could be done within 4-6 hours by following this tutorial, once all the vital components are at hand. ## Objective I live near a lake that for many years have had harmful algae blooms. Every summer there's been a discussion on whether it's safe to take a swim or not. There are expensive sensors to measure harmful algae on the market. My vision was to create a cheap device that reads temperature, turbidity and depth of field, and then publish the data on the Internet. It wouldn't be as accurate as a more expensive sensor but could give vital information. I also got inspiration from this research paper on [IoT Solution for Intelligent Pond Monitoring](https://www.researchgate.net/publication/339914330_IoT_Solution_for_Intelligent_Pond_Monitoring). Primarily this project was to give information to members of the beach and boat club. I intended to both serve residents and also provide data to the municipality, which for many years has collected data on the lake's health. The municipality runs a LoRaWAN network which would be well suited for a similar project. The project vision has unfortunately not been realized. First I could only find one waterproof sensor, the thermometer. Then I looked closer at a turbidity sensor but I couldn't find any code for MicroPhyton to run it. The only communication that I have been able to make work is wifi and therefore I have only an option to test close to my house. This project had a big vision but even with a reduced result it can be useful as a water temperature meter for garden pools and ponds. The insights from this project are limited but important to me so that I can continue to work towards the initial vision. All problems that have arisen have been solved in one way or another. Flexibility in hardware and software has been important and crucial to be able to accomplish something worth presenting in this tutorial. ## Material Starting this project I have purchased the pre-assembled kit as recommended for this course. I added a suitable sensor that fitted my project and supplemented it with a rechargable battery pack . | Material | Webshop | Price | | ----------- | ------------------- | ------- | | Pre-assembled kit for the course (LNU - 1DT305 Tillämpad IoT - FiPy and sensors bundle) | [Electrokit ](https://www.electrokit.com/produkt/lnu-1dt305-tillampad-iot-fipy-and-sensors-bundle/) | 1499.00 SEK || | Li-Po battery with JST-PH connector (Luxorparts Li-Po-batteri 3,7 V med kontakt 1200 mAh) | [Kjell & company](https://www.kjell.com/se/produkter/el-verktyg/arduino/arduino-tillbehor/luxorparts-li-po-batteri-37-v-med-kontakt-1200-mah-p87924) | 99.00 SEK | | Waterproof temperature sensor (Temperatursensor med kabel) | [Kjell & company ](https://www.kjell.com/se/produkter/el-verktyg/arduino/arduino-tillbehor/temperatursensor-med-kabel-for-arduino-p87081) | 149.90 SEK | | | Total | 1747,90 SEK | ### Prototype The material I have used for building the prototype are the following. I recommend that you start by examining your hardware and have a look at the Datasheets for the Pycom devices. That will give you vital information on how the devices look and work. * [Fipy](https://docs.pycom.io/datasheets/development/fipy/): Fipy is a Pycom development board with powerful CPU [(Espressif ESP32 SoC)](https://en.wikipedia.org/wiki/ESP32), five networks (WiFi, BLE, cellular LTE-CAT M1/NB1, LoRa and Sigfox), 1KM WiFi range, MicroPython enabled, fits in a standard breadboard, ultra-low power usage. ![](https://i.imgur.com/8DmePqz.jpg) * [PySense 2.0](https://docs.pycom.io/datasheets/expansionboards/pysense2/): PySense is a Pycom expansion board and sensor shield which can be used with any Pycom modules. It contains sensors such as temperature, accelerometer, ambient light, pressure and humidity. The board features a Li-Ion/Li-Po charger. When the board is being powered via the micro USB connector, it will charge the battery (if connected). ![](https://i.imgur.com/dUlKzaH.jpg) * [Temperature probe DS18B20](https://www.velleman.eu/products/view/?id=459222): This digital thermometer provides temperature readings. It measures temperatures from -55°C to +125°C. The probe is waterproof and contains a stainless steel tube, and a cable of 91 cm. Here you need a screwdriver to assemble the probe and the sensor. ![](https://i.imgur.com/XfC3QDa.jpg) * [Micro USB cord](https://en.wikipedia.org/wiki/USB): USB is a standard for connection, communication and power supply between computers and devices. ![](https://i.imgur.com/MP3kyUT.jpg) * [Breadboard](https://en.wikipedia.org/wiki/Breadboard): Breadboard is a solderless construction base for prototyping of electronics. This makes it easy to use for creating temporary prototypes and experimenting with circuit design. ![](https://i.imgur.com/Cz0FuEQ.jpg) * [Jump wire](https://en.wikipedia.org/wiki/Jump_wire): A jump wire is an electrical wire with a connector or pin at each end , which is used to interconnect the components of a breadboard. ![](https://i.imgur.com/vEaNFSG.jpg) * [Resistor]([https:/](https://en.wikipedia.org/wiki/Resistor)/): A resistor is an electrical component that limits or regulates the flow of electrical current in an electronic circuit.![](https://i.imgur.com/FeJSumO.jpg) * [Batteripack](https://en.wikipedia.org/wiki/Battery_pack): A battery pack is a set of any number of batteries or individual battery cells. The term battery pack is often used in reference to cordless tools, radio-controlled hobby toys, and battery electric vehicles. ![]![](https://i.imgur.com/eXcI1et.jpg) In addition to these parts I also used a slotted screwdriver, a baby pool and a take away lunch box. ![](https://i.imgur.com/wQIIfGk.jpg) ![](https://i.imgur.com/QSVBlyC.jpg) ![](https://i.imgur.com/Sc08rss.jpg) ## Computer setup I have a computer that runs Windows 10, and therefore this tutorial gives guidance according to that. In order to be able to carry out the following instructions, an internet connection is required. I have chosen to use Atom as the IDE ([integrated development environment](https://en.wikipedia.org/wiki/Integrated_development_environment)) for this project. It runs [MicroPython]((https://en.wikipedia.org/wiki/MicroPython)) code that is optimized to run on a [microcontroller](https://en.wikipedia.org/wiki/Microcontroller). If you in the future find this tutorial, Atom might not be available for downloading since [sunsetting has been announced](https://github.blog/2022-06-08-sunsetting-atom/). There are alternative solutions such as [Thonny](https://thonny.org/) and many more. ### Software installation You will now start by installing software so that the computer and the development environment can work together. For this you need to install three software. Firstly Node.js, which is designed to build scalable network applications and can handle connections concurrently. Secondly Atom, which is a text editor designed for editing source code of computer programs. In Atom you also need to add Pymakr which adds a REPL ([read–eval–print loop](https://en.wikipedia.org/wiki/Read%E2%80%93eval%E2%80%93print_loop)) that gives you command lines for typing and executing code. Thirdly Pycom Firmware, which provides the low-level control for Pycom hardware. At this stage only make installation according to this instruction. Read the instructions from the different sources for latest updates and versions of software. Here you go! 1. Install [Node js](https://nodejs.org/en/): Click on the previous link, download file and follow instructions, permit to do changes, finish. Node opens as a command prompt. If needed, here is an [installation guide](https://nodesource.com/blog/installing-nodejs-tutorial-windows/). 1. Install [Atom](https://atom.io/): Click on the previous link, download file and follow instructions, Atom program starts. If needed, here is an [installation guide](https://flight-manual.atom.io/getting-started/sections/installing-atom/). * Pymakr plugin: Check that you have Paymakr installed in Atom. Go to Global settings and look in Packages. In Atom the Settings are under the File menu, or visual in the down right corner of the program interface. If you cannot find Paymakr under Installed Packages go to Install under Settings. Search for it and then Install. 1. Install [PyCom Firmware Updater](https://docs.pycom.io/updatefirmware/device/): Click on the previous link, choose Windows, download file and follow instructions, permit to do changes, install. Pycom update opens as an installer user interface. Before connecting devices to the computer we have to make sure the Pycom devices are set up properly. You need to connect your development and expansion boards. This can be done by just clicking the two boards together or by using a breadboard and jumper wires. My suggestion is to start by clamping the two together. This will be enough to install firmware and test some code. You put the two devices together by fitting the pins of the Fipy with the “holes” of the Pysense. Clamp them together so you cannot see the pins. Make sure to align the two pieces so that the USB slot on the Pysense is in the same direction as the LED on the Fipy. If you are unsure go to the Datasheets of the hardware and have a look. This picture shows the right direction but you need to clamp the pieces together. ![](https://i.imgur.com/SaUaBZJ.jpg) ### Hardware updating Now you can connect your device to the computer. Before anything else is done you have to update the firmware of your Pycom device. Be aware now that this is a crucial step and you should not disconnect, touch or cancel anything while programs are running. Follow these steps for updating your Pycom devices. 1. Connect the Pysense to your computer with a USB cable. Look if the LED on your Fipy starts to blink. 2. Open the program Pycom firmware. Start going through the upgrade process. 3. Under Communication you chose Port to the one assigned. You find this information in the device manager under Ports. At Type you chose Development. Continue. 4. Under Advanced settings you chose Information: Device type: Fipy. At Filesystem: FatFS and mark Erase during update. Continue. 5. If everything went ok you will get to the Result and you are now Done. ### Code testing Now you can try out some commands making sure Atom works, and then some code. Open Atom, then disconnect and reconnect your USB in the computer. It should now automatically recognise a device. You should see a cursor after ">>>" in the REPL prompt. If not you can check the setting of Port and Connect Device in the menu above the REPL. You can read [the Atom flight-manual ]([https://](https://flight-manual.atom.io/))for more information. As to testing code you have to Add a Project Folder. You find commands under the left panel File. Name it and save it. Then create a New File. Save it in the new project folder and name it `main.py`. All MicroPython projects must have `main.py` which is the start point for code execution. A first code to try out can be one to get the LED light blinking in different colors. Copy the following lines and paste it into `main.py`. Save. ``` import pycom # Import pycom to control LED import time # Import time to create delays # We disable LED heartbeat to control it manually pycom.heartbeat(False) # Your board run this section over and over in a loop while True: #colors in hexadecimal (0xRRGGBB) pycom.rgbled(0xFF0000) # Red time.sleep(1) pycom.rgbled(0x00FF00) # Green time.sleep(1) pycom.rgbled(0x0000FF) # Blue time.sleep(1) ``` Now you have to upload your project and the file to your Pycom from the upload project button. You click on the button with an arrow pointing upwards. The LED on your Fipy should automatically start to blink in different colors. The REPL is not accessible anymore because a loop is in the code. To stop blinking press Ctrl+c when in the REPL. If no blinking happens make sure the REPL have your project selected and the right port connected. This is good to check regularly especially if you work with several projects and update code often. It is good to know some basic MicroPython and shortcuts to interact with the REPL. [Pycom has a list]([https://](https://docs.pycom.io/docnotes/repl/#app)) but there are many more resources around if you google it. ## Putting everything together Now you can start building the prototype. First disconnect the power by unplugging the USB. You must then split your Pycom devices so that you can start using the breadboard and add sensors. The breadboard design for this prototype is shown in this diagram: ![](https://i.imgur.com/CyI0bW7.png) In the test phase, you will connect to a USB for power, but when you're finished, you will switch to a battery for mobility. The best way now is to start connecting the Pysense and the Fipy with four jump wires. You can place the Fipy anywhere on the breadboard as long as you put it vertically over the slot. Make sure to put the wires in the right "holes" because there is power feeded. After putting them in place you can make a test by running the code for LED blinking as before. This should work just as if the parts are being clamped together. ### Sensor Next you add the sensor. This temperature sensor comes in two separate parts that you will have to put together. Here is where the screwdriver comes in. This picture shows what pin goes with what cord. It's important not to mix these up or things won't work. ![](https://i.imgur.com/GkEdo3r.jpg) When you put the sensor on the breadboard you have to use a resistor. Without the resistor this setup won't work. ![](https://i.imgur.com/8a4ZN9u.jpg) The sensor itself is placed on the breadboard as shown here: ![](https://i.imgur.com/VpdhGnO.jpg) Now you can connect the jump wires from the sensor to the Fipy according to the diagram shown earlier. This is how it should look: ![](https://i.imgur.com/wogsy1u.jpg) Finally you can reconnect power, see LED blinking, and start Atom for testing code. ### Code Now when the hardware is put together you have to make sure Atom gives instructions. This project only contains code openly available on the internet. You start Atom and add new files to a project as shown in the picture below. The files will be empty but you will soon put code in them. You do not need to have the subfolder `lib` but it's customary, and looks good. ![](https://i.imgur.com/gfCynIQ.png) `Main.py` Copy the code from here and paste into the file. In `main.py` you can set time for how often data should be collected and sent to a broker. This can be changed according to how much data you want to collect. In this project I have set the time to every 1 minute (60 seconds). ``` from machine import Pin from onewire import DS18X20 from onewire import OneWire from mqtt import MQTTClient import time import ujson import machine import config def sub_cb(topic, msg): print(msg) # MQTT Setup client = MQTTClient(config.SERIAL_NUMBER, config.MQTT_BROKER, user=config.TOKEN, password=config.TOKEN, port=config.PORT) client.set_callback(sub_cb) client.connect() print('connected to MQTT broker') # The MQTT topic that we publish data to my_topic = config.TOPIC # DS18B20 data line connected to pin P10 ow = OneWire(Pin('P10')) temp = DS18X20(ow) # temperature data temperature = 0 while True: temperature=temp.read_temp_async() print(temperature) time.sleep(1) temp.start_conversion() time.sleep(1) # Here, we publish the data to the broker, under topic client.publish(topic=my_topic, msg=str(temperature)) client.check_msg() print("Send data to MQTT broker, sleeping for 1 minutes...") time.sleep(60) # Wait 1 minutes (60 seconds) # 30 minutes (1800 seconds), 60 minutes (3600 seconds) ``` `Config.py` Copy the code from here and paste into the file. You need to edit `config.py`, since your `boot.py` is expecting `WIFI_SSID` and `WIFI_PASS`. Simply add your wifi network name and password. You must add a 2,4 GHz network otherwise your device won’t be able to connect. You will later edit Datacake credentials. ``` # WiFi credentials WIFI_SSID = 'WIFI_SSID' WIFI_PASS = 'WIFI_PASS' # Datacake credentials SERIAL_NUMBER = 'DEVICE_SERIAL_NUMBER' MQTT_BROKER = 'mqtt.datacake.co' TOKEN = 'ACCOUNT_TOKEN' PORT = 1883 TOPIC = 'TOPIC_TO_PUBLISH_TO' ``` `Boot.py` Copy the code from here and paste into the file. You need to edit `boot.py` with `WIFI_SSID` and `WIFI_PASS`. Simply add your wifi network name and password. ``` def do_connect(): from network import WLAN import time import pycom import machine pycom.wifi_mode_on_boot(WLAN.STA) # choose station mode on boot wlan = WLAN() # get current object, without changing the mode # Set STA on soft rest if machine.reset_cause() != machine.SOFT_RESET: wlan.init(mode=WLAN.STA) # Put modem on Station mode if not wlan.isconnected(): # Check if already connected print("Connecting to WiFi...") # Connect with your WiFi Credential wlan.connect('WIFI_SSID', auth=(WLAN.WPA2, 'WIFI_PASS')) # Check if it is connected otherwise wait while not wlan.isconnected(): pass print("Connected to Wifi") time.sleep_ms(500) # Print the IP assigned by router print('network config:', wlan.ifconfig(id=0)) # WiFi Connection do_connect() ``` `onewire.py` Copy the code from [Pycom tutorials]([https://](https://docs.pycom.io/tutorials/hardware/owd/)) and paste it in the file. `mqtt.py ` Copy the code from [Pycom github repository](https://raw.githubusercontent.com/pycom/pycom-libraries/master/lib/mqtt/mqtt.py) and paste it in the file. When all these files are saved you should be able to run the code. Connect the device and then upload the project. You should now get confirmation Connected to Wifi in REPL. Since some credentials are missing the Fipy LED should now give a red light. ### Transmission Data retrieved by the sensor is not handled according to many rules. The code is simple and a loop is created where the time for when data is transmitted can be adjusted as needed. There are no triggers built into the code and no external sensors are available as triggers. A thermometer could possibly be trigged by something.The only thing I can come up with is that it's available at daytime, so a sensor for detecting daylight. ### Data visualisation I have chosen [Datacake](https://datacake.co/) as the platform for publishing data on the internet. Datacake is a low code platform where you can create IoT applications in minutes without programming. They provide many different options suitable for a new beginner. Datacake was not my first choice. I tried [Pybytes ](https://pybytes.pycom.io/)which is made by Pycom but couldn't make it work. Datacake proved to be a good tool. As this is only a prototype project it works fine and the free plan is sufficient. You need to start by creating an account on [Datacake](https://app.datacake.de/login). Use [this tutorial](https://hackmd.io/@lnu-iot/r1aui0B59#Datacake-part) to make a correct implementation to make Datacake run with WiFi using MQTT. [MQTT](https://mqtt.org/) is a light protocol designed for low-bandwidth, high latency, unreliable networks. MQTT's features make it an excellent option for sending high volumes of sensor messages to analytics platforms and cloud solutions. Datacake makes use of this protocol for their services. In Datacake you can make a nice looking GUI [(graphical user interface)](https://en.wikipedia.org/wiki/Graphical_user_interface) for public use of your data. I like the Gauge look and here are the settings I made. You need to change settings in Data and Appearance too. Under data you set the Unit "°C" and under Appearance you add the Icon "swim". ![](https://i.imgur.com/49vyZFj.png) The final look for a user GUI is [seen here](https://app.datacake.de/pd/cc6457dd-4163-48b9-a7d1-e0d1708b0bb7) or in the picture below. It works on different smartphones and has a responsive design. A great feature is that Datacake offers public links that allow you to share the GUI with external users that don't need an account. They offer a QR code which can come in handy if you like to disseminate information about the data collected. The URLs are very long so I suggest that you use [URL shortening](https://en.wikipedia.org/wiki/URL_shortening) if you like to send the link to your friends. ![](https://i.imgur.com/TfQYKkg.png) ### Network The Fipy has a lot of different communication options. WiFi is being used in this project due to other options not being available. WiFi does not have long range and has a high power consumption. I wanted to make this project portable with a battery which is a bad idea because of the high power consumption. But it can be used in a test environment. For extra security, you can add new networks to you wifi router. For this projekt I added a guest client, so it's seperated from my other devices. I could then also make sure it delivers 2.4 GHz. ### Electrical calculations This is the power consumption according to the datasheets for the devices used in this prototype. | Device | Current | Active | Idle | |-|-|-|-| | Fipy | mA | 62,7 | 62,7 | | Wifi | mA | 137 | 126 | | Pysense (3.75V, on the JST) | mA | 7 | 0,009 | | DS18B20 | | Parasite Power | | | Total | mA | ≈207 | ≈189 | To know how long the battery life is you can use a mathematical formula or go to an [online tool and get help. ](https://www.omnicalculator.com/other/battery-life?advanced=1&c=SEK&v=discharge_safety:20!perc,awake_time:10!sec,battery_capacity:1200!mAh,consumption_awake:206.7!mA,consumption_sleep:188.709!mA,sleep_time:50!sec) This online calculation shows that the battery life will be only 5 hours. Short battery time is a well known problem when using Wifi so this comes as no surprise. It turned out that power lasted 12 hours, which showed after I let the device run out of battery. Note that electrical calculation is not within my competence. I cannot explain why it turned out this way. ## Final result The final result of the project is far from the vision but works fine in the test environment. This is only a development setup and could not be used in production. Placing all the tech in a lunch box was a great idea since it was a perfect fit, came with a lid and it's waterproof for some time. ![](https://i.imgur.com/xerwIug.jpg) When it was placed in the pool, everything floated and sent thermometer data for several hours even though the box was made of paper. There was wifi, enough power and all the sensors stayed in place. ![](https://i.imgur.com/S01gXfe.jpg) ### Final thoughts My final thoughts on how the project went are mainly that it was hard to be a new beginner. I was often confused about the jargong and all new stuff. I wish there was a common thread to follow for me and other beginners. Much more detailed than today's process. I managed but there were many frustrating moments. I think that LNU could, for example, give tips on good youtube videos to watch before the start of the course, and implement flipped classroom methods. I have already addressed the fact that things won't always turn out as planned. Actually, these things were nothing that I myself could influence or had a deeper knowledge of. The circumstances were such. I made a presentation on July 4 which is recorded. It went well and everything worked. In that presentation I concluded this summer course in the following lessons learned: * Vision is good but reality is better * Hardware brake * The world is full of software * Code is tricky * Communication is not always available * Experience is gold  * Summer courses are not always easy * Bright future for IoT Finally, I really want to thank all the assistants for the time they put into my problems. And the same to all the excellent teachers. Thank YOU!