---
# System prepended metadata

title: "Mini Cereal and Milk Dispenser \U0001F95B\U0001F963"

---

# Mini Cereal and Milk Dispenser 🥛🥣
By May Sunktong (ms227nw)
:computer: Project level: Beginner
:clock10: Approximated time: 5-10 hrs

## Project Overview
The Mini Cereal and Milk Dispenser combines three primary functions: dispensing cereal with a servo motor, pumping milk with a small drinkable pump and measuring current temperature of the milk by a temperature sensor stick. Inspired by the growing popularity of vending machines built with microcontrollers and varieties of sensors, this device reflects the modern world's growing demand for convenience.

By automating the cereal and milk process, the dispenser is an assistant to your morning routine, making breakfast both quick and enjoyable.

## Objective
1. To gain a comprehensive understanding of microcontrollers, specifically the Raspberry Pi Pico W, and its various functionalities.
2. To learn how to operate and integrate different sensors and visualize it
3. To acquire knowledge about power supply management and the flow of circuits
4. To learn how to design a good user experience for all mechanics in the project

## Materials
:::success
:moneybag:Overall budget: 300-500 SEK
:recycle: Re-use materials are wires, buttons, a motor driver, a 6mm plastic pipe and a cardboard box.
:::

|    **Item**       |          **Specification**       |**Source**|
|:-----------------:|:-------------------------:|:-------------------------:|
|Raspberry Pi Pico W||          [link](https://www.electrokit.com/raspberry-pi-pico-wh)|
|Breadboard||          [link](https://www.electrokit.com/kopplingsdack-400-anslutningar)         |
|Freenove Breakout Board for Raspberry Pi Pico|optional|[link](https://www.amazon.se/gp/product/B0BFB53Y2N/ref=ox_sc_act_title_9?smid=A3DM8VCGJL5PKR&psc=1)|
|Universal Power Supply|3V-12V|[link](https://www.electrokit.com/universal-power-supply-3v-till-12v-12w)|
|Small Drinkable Pump|3V|          [link](https://www.electrokit.com/drankbar-pump-3v)|
|Motor driver|5V-35V|[link](https://www.electrokit.com/motordrivare-l298-dubbel-h-brygga-5-35v-2a)|
|Servo motor 360°|4.8V-6.0V|[link](https://www.electrokit.com/servo-stort-360)|
|Clickable button (green)||[link](https://www.electrokit.com/tryckknapp-12.2mm-1-pol-off-ongron)|
|Clickable button (yellow)||[link](https://www.electrokit.com/tryckknapp-12.2mm-1-pol-off-ongul)|
|Wiring loom cables for buttons||[link](https://www.electrokit.com/picade-x-kabelset)|
|LCD OLED 0.91"|128x32px I2C|[link](https://www.electrokit.com/lcd-oled-0.91128x32px-i2c)|
|Temperature sensor for fluid|3V-5.5V|[link](https://www.electrokit.com/temperatursensor-vattentat-metall-ds18b20)|
|LED-module RGB|5V|[link](https://www.electrokit.com/led-modul-rgb)|
|10kohm Resistors|0.25W 10kohm (10k)|[link](https://www.electrokit.com/motstand-kolfilm-0.25w-10kohm-10k)|

:::info
#### :bulb: How to get the right resistors?
For a pull-up or pull-down resistor, a typical current range is between 0.1 mA (100 µA) and 1 mA. This range balances noise immunity and power consumption.
#### R = V/I (Ohm's Law)

Example Calculations:
1. For 1 mA Current
R = 5V / 0.001A = 5000 Ω = 5 kΩ
2. For 0.5 mA Current
R = 5V / 0.0005A = 10000 Ω = 10 kΩ

#### Practical Choice:
10kΩ Resistor :heavy_check_mark: 
- Draws 0.5 mA at 5V.
- Commonly used as it provides a good balance between low power consumption and sufficient noise immunity.
:::

## Computer Setup and IDE
:female-technologist: Flash a firmware onto Pico Pi W
:computer: IDE: Thonny

:book: **File structure shown in Thonny**
![Screenshot 2024-06-30 at 16.54.08](https://hackmd.io/_uploads/HJV0ZeJwC.png)

:bulb: **How to install a driver on Thonny**
![image](https://hackmd.io/_uploads/HkJ4dxkvC.png)
![image](https://hackmd.io/_uploads/Sym8dxJDA.png)


## Building the device 🛠️
### Flow diagram 
![image](https://hackmd.io/_uploads/S1OMDj4vC.png)

### Code snippets 👩🏻‍💻
1. Pump and Motor driver installation
![Screenshot 2024-06-30 at 18.11.22-1](https://hackmd.io/_uploads/Hk4Sj-yPC.jpg)


**pump_controller.py**
```python
from machine import Pin, Timer

LED_Pin_Red = Pin(21, Pin.OUT)
LED_Pin_Green = Pin(20, Pin.OUT)
LED_Pin_Green.value(1)

class PumpController:
    def __init__(self, button_pin_number, in1_pin_number):
        self.button_pin = Pin(button_pin_number, Pin.IN, Pin.PULL_DOWN)
        self.in1_pin = Pin(in1_pin_number, Pin.OUT)
        self.timer = Timer(-1)

        self.button_pin.irq(trigger=Pin.IRQ_RISING, handler=self.button_pressed)

    def turn_off_pump(self, timer):
        self.in1_pin.value(0)
        LED_Pin_Red.value(0)
        LED_Pin_Green.value(1)  

    def button_pressed(self, pin):
        if pin.value() == 1:
            self.in1_pin.value(1)  
            LED_Pin_Green.value(0)
            LED_Pin_Red.value(1)   
            
            self.timer.init(period=1000, mode=Timer.ONE_SHOT, callback=self.turn_off_pump)

    def cleanup(self):
        self.in1_pin.value(0)  
        LED_Pin_Red.value(0)   
        LED_Pin_Green.value(1) 
        self.timer.deinit()    
```

2. Servo motor installation
:::warning
#### Driver needed
:blue_book: micropython-servo
:::
![Screenshot 2024-06-30 at 17.19.05-1](https://hackmd.io/_uploads/S1nroZ1PA.jpg)

**servo_controller.py**
```python
from machine import Pin, PWM
import time

LED_Pin_Red = Pin(21, Pin.OUT)
LED_Pin_Green = Pin(20, Pin.OUT)
LED_Pin_Green.value(1)  

class ServoController:
    def __init__(self, button_pin, servo_pin, run_time=3, speed=20):
        
        self.button_pin = Pin(button_pin, Pin.IN, Pin.PULL_DOWN)
        self.servo_pin = Pin(servo_pin)

        # Initialize PWM for the servo
        self.servo = PWM(self.servo_pin)
        self.servo.freq(50)

        # Set the servo to the neutral position initially to stop it
        self.set_servo_speed(0)
        
        self.button_pressed = False
        self.run_time = run_time 
        self.speed = speed
        self.servo_running = False
        self.last_press_time = 0
        self.start_time = 0

    def set_servo_speed(self, speed):

        neutral_duty = 4915  # Neutral duty cycle (1.5 ms pulse width)
        duty = int(neutral_duty + (speed / 100) * 2621)  
        self.servo.duty_u16(duty)

    def update(self):
        current_time = time.ticks_ms()
        
        if self.button_pin.value() == 1 and not self.button_pressed and (current_time - self.last_press_time) >100:
            self.button_pressed = True
            self.last_press_time = current_time
            self.start_servo()
        
        if self.button_pin.value() == 0 and self.button_pressed:
            # Button is released
            self.button_pressed = False

        if self.servo_running and (current_time - self.start_time) > self.run_time * 1000:
            
            self.stop_servo()
        
        time.sleep(0.01)

    def start_servo(self):
        self.servo_running = True
        self.start_time = time.ticks_ms()
        self.set_servo_speed(self.speed)
        LED_Pin_Green.value(0)
        LED_Pin_Red.value(1)

    def stop_servo(self):
        self.servo_running = False
        self.set_servo_speed(0)
        LED_Pin_Green.value(1)
        LED_Pin_Red.value(0)

    def cleanup(self):
        self.servo.deinit()
        LED_Pin_Red.value(0)
        LED_Pin_Green.value(1)
        print("Program stopped")
```


3. Temperature sensor for fluid and LCD OLED installation
:::warning
#### Driver needed
:blue_book: onewire, ds18x20, micropython-ssd1306 (for OLED)
:::
![Screenshot 2024-06-30 at 18.31.40-1](https://hackmd.io/_uploads/r1I8jbkvR.jpg)

**water_temp_controller.py**
```python
import time
from machine import Pin
import onewire, ds18x20

class WaterTempController:
    def __init__(self, pin):
        self.ds_pin = Pin(pin)
        self.ow = onewire.OneWire(self.ds_pin)
        self.ds = ds18x20.DS18X20(self.ow)
        self.roms = self.ds.scan()
        if not self.roms:
            raise Exception('No DS18B20 devices found on the bus')

    def read_temp(self):
        self.ds.convert_temp()
        time.sleep_ms(750)
        temps = []
        for rom in self.roms:
            temp = self.ds.read_temp(rom)
            temps.append(temp)
        return temps
```

**oled.py**
```python
from machine import SoftI2C, Pin
from ssd1306 import SSD1306_I2C

class Display:
    def __init__(self, sda_pin, scl_pin, width=128, height=32):
        self.i2c = SoftI2C(sda=Pin(sda_pin), scl=Pin(scl_pin))
        self.display = SSD1306_I2C(width, height, self.i2c)
    
    def read_and_display_temp(self, water_temp_controller):
        temps = water_temp_controller.read_temp()
        if isinstance(temps, list) and len(temps) > 0:
            temp = temps[0]
            self.display.fill(0)
            self.display.text('Milk Temp:', 0, 0)
            self.display.text(f'{temp:.2f} C', 0, 16)
            self.display.show()
```

## Transmitting the data/ connectivity
The Mini Cereal and Milk Dispenser transmits data to the internet using **WiFi**, chosen for its widespread availability, high data rates, and ease of integration, making it ideal for home environments where the device operates within a reasonable range of a WiFi router. Unlike LoRa and Helium, which are designed for low-power, long-range applications, WiFi ensures reliable connectivity and supports the higher data rates needed for responsive and interactive user experiences.

The moment the Pico Pi W is started, the below code written in boot.py file is executed automatically.

**boot.py**
```python=
import wifiConnection

def http_get(url = 'http://detectportal.firefox.com/'):
    import socket                           # Used by HTML get request
    import time                             # Used for delay
    _, _, host, path = url.split('/', 3)    # Separate URL request
    addr = socket.getaddrinfo(host, 80)[0][-1]  # Get IP address of host
    s = socket.socket()                     # Initialise the socket
    s.connect(addr)                         # Try connecting to host address
    # Send HTTP request to the host with specific path
    s.send(bytes('GET /%s HTTP/1.0\r\nHost: %s\r\n\r\n' % (path, host), 'utf8'))    
    time.sleep(1)                           # Sleep for a second
    rec_bytes = s.recv(10000)               # Receve response
    print(rec_bytes)                        # Print the response
    s.close()                               # Close connection

# WiFi Connection
try:
    ip = wifiConnection.connect()
except KeyboardInterrupt:
    print("Keyboard interrupt")

# HTTP request
try:
    http_get()
except (Exception, KeyboardInterrupt) as err:
    print("No Internet", err)

# WiFi Disconnect
```

Data is sent using the ***MQTT protocol via Adafruit IO***. MQTT is a lightweight messaging protocol perfect for IoT devices, providing efficient and reliable communication with low bandwidth usage. Adafruit IO simplifies the process with a user-friendly interface, enabling easy setup and management of data streams. This combination of WiFi and MQTT via Adafruit IO ensures that the dispenser delivers timely updates and control commands, balancing ease of use, responsiveness, and reliability, while maintaining efficient power consumption suitable for an always-on device.

**main.py**
```python
import time
from mqtt import MQTTClient
import machine
import micropython
from machine import Pin
import ubinascii
import keys
import wifiConnection

from pump_controller import PumpController
from servo_controller import ServoController
from water_temp_controller import WaterTempController
from oled import Display

# Initialize the controllers 
water_temp_controller = WaterTempController(pin=10)
pump_controller = PumpController(button_pin_number=2, in1_pin_number=3)
servo_controller = ServoController(button_pin=19, servo_pin=17)
display = Display(sda_pin=26, scl_pin=27)

# MQTT client initialization
AIO_CLIENT_ID = ubinascii.hexlify(machine.unique_id()).decode('utf-8')  # Convert bytes to string
mqtt_client = MQTTClient(AIO_CLIENT_ID, keys.AIO_SERVER, keys.AIO_PORT, keys.AIO_USER, keys.AIO_KEY)

# Callback Function to respond to messages from MQTT
def sub_cb(topic, msg):
    print((topic, msg))  # Outputs the message that was received. Debugging use.

# Function to publish temperature to MQTT server
def publish_temperature():
    temps = water_temp_controller.read_temp()
    if isinstance(temps, list) and len(temps) > 0:
        temperature = temps[0]
        temperature_msg = str(temperature)
        print("Publishing: {0} to {1} ... ".format(temperature_msg, keys.AIO_MILK_FEED), end='')
        try:
            mqtt_client.publish(topic=keys.AIO_MILK_FEED, msg=temperature_msg)
            print("DONE")
        except Exception as e:
            print("FAILED: {}".format(e))

# Connect to WiFi
try:
    ip = wifiConnection.connect()
    print("Connected to WiFi, IP: ", ip)
except KeyboardInterrupt:
    print("Keyboard interrupt")

# Use the MQTT protocol to connect to Adafruit IO
mqtt_client.set_callback(sub_cb)
mqtt_client.connect()
mqtt_client.subscribe(keys.AIO_MILK_FEED)
print("Connected to %s, subscribed to %s topic" % (keys.AIO_SERVER, keys.AIO_MILK_FEED))

try:
    while True:
        mqtt_client.check_msg()
        servo_controller.update()
        publish_temperature()
        display.read_and_display_temp(water_temp_controller)   
        time.sleep(3)
        
except KeyboardInterrupt:
    servo_controller.cleanup()
    pump_controller.cleanup()
    mqtt_client.disconnect()
    wifiConnection.disconnect()
    print("Disconnected from MQTT server.")
```


## Data Visualization on Adafruit
:::info
Live data on Adafruit: [click](https://io.adafruit.com/mayiotproject/dashboards/new-dashboard)
:::

![image](https://hackmd.io/_uploads/BkWV5J1vR.png)

## Finalizing the prototype
:::info
Demo video: https://youtu.be/eomfcJ0cdlE
:::

![Compress JPEG Online](https://hackmd.io/_uploads/ByGhckkvR.jpg)

![Online JPEG Compressor-min](https://hackmd.io/_uploads/HkIKs1kDA.jpg)

![Image from Online Converter](https://hackmd.io/_uploads/BJr_XfzDC.jpg)








