owned this note
owned this note
Published
Linked with GitHub
# Bubble count in beer fermantiation station.
###### tags: `fermentation` `beer` `examination` `tutorials` `Hall effect` `Magnets` `Wifi`
This report outlines the steps to making a wifi connected co2 monitoring device, using a Hall effect sensor, a magnet, and a waterlock. The idee being that you can monitor the fermentation process in in fermentation chamber while breewing beer. As yeast eat the sugers alcohol is created and co2 is produced in the chamber. This creates bubbles that eventually go in the waterlock, making bubbles, that moves the floatation device with the magnet atop, closer to the hall effect sensor, regisering a "bubble". Eventually the yeast has consumed the sugers and the process slows down. Once this happens you can move on to the next step in the brewing process.
---
*Oscar Johansson | oj222iq | Summer of 2023*
---
**Table of Contents**
[TOC]
---
## Objective
I chose this project becouse i wanted to brew beer, but am to lazy to monitor the fermentation myself, so i want to have a website that can tell me approximatly how long time it is left. Using solely a hall effect sensor might indicate a few days ahead of time that the fermentation is comming to an end, giving me ample time to prepare and plan for the next stage in the brewing process. Adding sensors such as humidity, temperature, and more might give indications as to the effects these have on the fermantation, such as speed, taste, developement.
From start to finish this project might take you 3-4 days of constant work. Ofcource depending on your skill level. If you are a PRO iot guy/garl it will be done in an afternoon.
---
## Material
All components without a * was accuired on https://www.electrokit.com using the "**Type designation**" in Bill of materials to make sure you have the exact same item.
For any items with a *, the place of purchase is stated in the "**Type designation**"
TODO PICS
> Bill of material:
>| Name | Type designation | Price(sek) |
>| --------- | ---------------- | --------|
>| Rasberry Pi Pico W | 41019114 | 109 |
>| Binary Hall effect sensor | 41015964 | 18 |
>| Charging cable 30cm male/male | 41003290 | 39 |
>| USB-cable A-male – micro B 5p male 1.8m | 41012684 | 49 |
>| Resistor carbonfilm 0.25W 330ohm (330R) | 40810233 | 1 |
>| Magnet Neo35 Ø5mm x 5mm| 41011480 | 11|
>|Fermentationpipe/waterlock*| (https://www.pgw.se/jasror-3-delat.html) | 34|
>|Fermentationbucket 30l* |https://www.pgw.se/jashink-30-liter-med-tappkran.html | 149|
>|Breadboard |10160840 | 69 |
>
In this project i have chosen to work with the Rasberry Pi Pico W, it will act as the microcontroller, and take sensor data, and relay the collected data via Wifi to the internet.
The binary hall effect sensor will read magnetic fluctuations in the fermentationpipe, as the magnet moves up and down inside the fermentationpipe.
The Usb cable is for powering the Pico. Charging cables, and the breadboard in not mandatory but helps as you dont have to solder any components togheter.
The resistor is for creating the correct resistanc between the output and the power input on the sensor. The Fermentationpipe and FermentationBucket is also tecnically not mandatory, as yuou could for example use a carbonated bewrage for testing, but will be mandatory if brweing beer is your goal reading this.
---
## Computer setup
Here i outline the setup you will need to program your microcontroller.
1. Install Thony
2. Go to Tools->Options->Interpretor-> Set Interpreter to "Micropython (Rasberry Pi Pico)" If this option does not exist download the latest version of Thony here https://thonny.org/ and try again!
3. Flash micropython onto you device by pressing the small white button on the microcontroller as you put the usb cable into it. An option should pop up promting to install Micropython onto the device.
4. You can now test your connection by running a simple test script such as
```python=
from machine import Pin
led = Pin(25, Pin.OUT)
led.toggle()
```
5. Now you can write your code in the window in Thony and press run or F5 to execute it, you can also save it on your computer or on the Pi itself by pressing Ctrl, S.
6. Other tools involve an IDE of your choice,, aswell as a couple of other tools, such as Node Red, javascript and a couple of different librarys and dependancys. Refere to the "Platform, Code, and Connectivity" parts for f.
---
## Putting everything together
1. Connect the Raspberry Pi Pico W to your computer using the USB cable.
2. Connect the binary Hall effect sensor to the Raspberry Pi Pico's GPIO pins. Refer to the pinout diagram of the Raspberry Pi Pico and the sensor's datasheet to identify the appropriate pins for power, ground, and signal.
3. Place the magnet (Neo35 Ø5mm x 5mm) inside the fermentation pipe/waterlock ontop the top part of the part floating in the water. Ensure that the magnet is securely positioned and can move freely up and down as bubbles are produced. Make sure that the sensor is approprietly far away from the magnet that it activates as CO2 is pushed out of the water lock.
4. Connect the fermentation pipe/waterlock to the fermentation bucket or chamber. This allows the CO2 bubbles to pass through the waterlock, causing the floatation device to move, and the sensor to activate.
5. If necessary, mount the Raspberry Pi Pico and the sensor in a suitable enclosure or mounting platform to ensure stability and protection.
6. Double-check all the connections and ensure that there are no loose wires or components.
7. Power up the Raspberry Pi Pico by connecting the USB cable to a power source.
8. Verify that the Raspberry Pi Pico is functioning properly and can communicate with the sensor by running a test script. For example, you can write a script that reads the sensor output and prints the result to the console.
9. Once the hardware is set up and tested successfully, you can move on to writing the firmware code that reads the sensor data, sends it via Wi-Fi to the internet, and performs any additional data processing or analysis required.
10. Deploy the firmware code to the Raspberry Pi Pico and verify that it can connect to your Wi-Fi network and transmit the data to the desired endpoint.
11. Monitor the CO2 bubble count and track the fermentation process using the dashboard or interface you have set up.


---
## Platform
While this guide is primarily written for Windows users, the software components and programming techniques can be adapted for other operating systems:
* Linux: Linux users can follow similar steps as Windows users for installing and using Thonny. The key difference may be in configuring the system's USB settings and permissions to access the Raspberry Pi Pico W.
* macOS: macOS users can also use Thonny for programming the Raspberry Pi Pico W. However, they may need to install additional drivers or configure the USB settings to establish a connection with the microcontroller.
Regardless of the operating system, the core functionalities and concepts remain the same. Adjustments may be needed based on the specific requirements and configurations of your operating system.
---
## The code
### Microcontroller code:
1. Set up Variables
```python=
wifi_ssid = "xxx"
wifi_password = "xxx"
server_ip = "xxx"
server_port = 8080
server_path = "/yourpath"
adc_pin = machine.ADC(2)
change_threshold = 5000
previous_value = adc_pin.read_u16()
counter = 0
```
2. Activate Wi-Fi using the defined credentials. Wait until the connection is established.
```python=
# Connect to Wi-Fi
wifi = network.WLAN(network.STA_IF)
wifi.active(True)
wifi.connect(wifi_ssid, wifi_password)
while not wifi.isconnected():
pass
print("Connected to Wi-Fi:", wifi_ssid)
status = wifi.ifconfig()
print('ip = ' + status[0])
```
4. Main loop
* Continuously read the analog value from the sensor. Calculate the difference between the current and previous readings.
* If the difference exceeds the change threshold, increment the bubble counter by 0.5.
* If the counter is an integer, print the counter, assemble the server URL, and send a POST request to the server with the counter as JSON data.
```python=
while True:
analog_value = adc_pin.read_u16()
difference = abs(analog_value - previous_value)
if difference > change_threshold:
counter += 0.5
if counter % 1 == 0:
url = "http://" + server_ip + ":" + str(server_port) + server_path
data = {"counter": counter}
try:
response = urequests.post(url, json=data)
print("Published:", counter)
print("Server response:", response.text)
response.close()
except OSError as e:
print("Failed to send POST request. Error:", e)
previous_value = analog_value
utime.sleep_ms(30)
```
5. Profit?!
The script maintains a connection with the Wi-Fi network, reads sensor data, detects changes exceeding a certain threshold, and then sends these changes to a server.
### Locally hosted server
This tutorial walks you through building a simple Express.js app connected to a MySQL database to track sensor data.
Theses are the dependancys and what we use in the server.
1. Import Modules
```python=
const express = require("express");
const app = express();
const mysql = require("mysql2");
const { sub } = require("date-fns");
```
2. Set Up Database Connection
```python=
const connection = mysql.createConnection({
host: "localhost",
user: "IOT m",
password: "abc123",
database: "sensor_data",
port: 3306,
});
```
3. Express Middleware and create
```python=
app.use(express.json());
```
4. Create async functions to calculate the count of bubbles per minute and hours:
```python=
#Similar for hours/minutes
async function bubblesPerMinute() {
return new Promise((resolve, reject) => {
const result = connection.execute(
"SELECT COUNT(*) as bubbles FROM data WHERE timestamp >= ?",
[sub(new Date(), { minutes: 1 })],
(err, results, fields) => {
if (err) console.error(err);
else resolve(...results);
}
);
});
}
}
```
5. POST route
```python=
app.post("/sensor", async (req, res) => {
const bubblesMinute = await bubblesPerMinute();
const bubblesHour = await bubblesPerHour();
const sensorID = req.body.sensor_id || 1;
connection.execute(
"INSERT INTO data (sensor_id, counts_per_minute, counts_per_hour) VALUES (?, ?, ?)",
[sensorID, bubblesMinute.bubbles + 1, bubblesHour.bubbles + 1],
(err, results, fields) => {
if (err) console.error(err);
else return res.send({ ok: true });
}
);
});
```
6. Start the Server!
```python=
app.listen(8080, () => console.log("Server started"));
```
7. Profit!?
---
## Transmitting the data / connectivity
#### How often is the data sent?
Data is sent every time the counter registers a whole number increment, which occurs whenever a significant change (a 'bubble') is detected by the sensor. The exact frequency depends on the sensor data and the defined threshold. The sensor readings and comparisons are performed approximately every 30 milliseconds, as specified by the `utime.sleep_ms(30)` command.
#### Which wireless protocols did you use (WiFi, LoRa, etc ...)?
The device uses Wi-Fi for wireless communication. This is established using the `network` module in the MicroPython library, specifically the `network.WLAN(network.STA_IF)` class, which implements a Wi-Fi station interface.
#### Which transport protocols were used (MQTT, webhook, etc ...)
HTTP is the transport protocol used in this system. Data is sent to the server using HTTP POST requests via the `urequests.post(url, json=data)` command. This data is then processed and visualized using Node-RED, a flow-based programming tool for wiring together hardware devices, APIs, and online services.
#### Elaborate on the design choices regarding data transmission and wireless protocols. That is how your choices affect the device range and battery consumption.
The use of Wi-Fi as a wireless protocol offers a good balance between range, data transmission rate, and energy consumption. It is widely supported and easy to set up. However, it does consume more power than some low-power alternatives like LoRa or Zigbee, which could lead to higher battery usage.
HTTP was chosen as the transport protocol due to its simplicity and broad support. It's stateless and connectionless, which simplifies the process of sending data to the server. Although MQTT might be a more power-efficient choice for some applications, the use of HTTP in this case may have been influenced by its compatibility with Node-RED.
The use of Node-RED allows for easy data visualization and analysis without writing extensive code. It's a versatile tool that can receive HTTP POST requests and visually present the incoming sensor data.
Note that the design choices were likely influenced by the specific requirements of the project, such as the sensor data rate, the need for real-time data, the power supply available, and the ease of integration with Node-RED.
---
## Presenting the data
#### Describe the presentation part. How is the dashboard built? How long is the data preserved in the database?
The data presentation and visualization are managed using Node-RED's built-in dashboard capabilities. It provides a flow-based programming interface where users can wire together API endpoints, databases, and other services to construct a complete data pipeline. Data received from the sensor device is pushed into the Node-RED flows, processed, and then visualized in real-time on the dashboard.
Data is preserved in the MySQL database indefinitely until manually deleted. The retention duration can be adjusted according to storage limitations or data relevance over time.
#### Visual examples on how the dashboard looks.

_**Fig 1:** Database setup._

_**Fig 2:** Database types._

_**Fig 3:** Node-Red setup._

_**Fig 4:** Dashboard output._
#### How often is data saved in the database?
Data is saved in the MySQL database every time a significant change (a 'bubble') is detected by the sensor and the counter registers a whole number increment. This frequency is dependent on the sensor data and the defined threshold.
#### Explain your choice of database.
MySQL was chosen as the database for this system due to its widespread usage, reliability, and compatibility with various platforms and languages, including Node.js and Node-RED. MySQL is an SQL-based database, which makes data manipulation and querying straightforward. It's also capable of handling a significant amount of data, suitable for sensor-based systems generating large volumes of data over time.
#### Automation/triggers of the data.
In this system, data is automatically inserted into the database every time a bubble is detected. This action is triggered by the change in sensor readings exceeding a defined threshold. The automated nature of this process ensures real-time data collection and representation, with no manual intervention required.
### Summary and Shortcomings.
The report illustrates the construction of a Wi-Fi-connected CO2 monitoring device for beer brewing using a Hall effect sensor, a magnet, and a waterlock. The device allows brewers to track the fermentation process remotely, with alerts indicating when the yeast has consumed all sugars. The information can aid brewers in preparing for the next brewing stage in advance. The mechanism is powered by a Raspberry Pi Pico W, which collects sensor data and relays it online. The report provides a comprehensive guide for building the device, coding it, and even creating a dashboard for visualizing the data. This innovative IoT solution not only simplifies the brewing process but also paves the way for further enhancements like tracking the effects of temperature and humidity on fermentation. Regarding some of the shortcomings the visualization could be better, for example as can bee seen in figure 4 some of the bars are colured differently, also the bar charts could use labels for the time in the x axis, aswell as a rewamp of what a bar referes to as that is rather unclear for the unknowing.