Smart Cities - Tiny House at Home (Alternate way)

From Sensors in Schools
Revision as of 04:09, 18 December 2024 by Jeremy (talk | contribs) (→‎main.py)
Jump to navigation Jump to search

Required Items

+ Any other USB cables, screws/standoffs, jumper wires etc.

Installing Thonny IDE

Follow installation steps for your os

For Windows/Mac

visit the thonny website and download the latest windows installer https://thonny.org/

For Linux

Installer (installs private Python 3.10 on x86_64, uses existing python3 elsewhere)

bash <(wget -O - https://thonny.org/installer-for-linux)

Re-using an existing Python installation

pip3 install thonny

Connect Sensors To Pico W

The final assembly should look something like this:

Daisy chain the piicodev modules together then plug into 3V3, SDA/SCL and GND

Temp Sensor

RTC

Connect the onewire temperature sensor into the raspberry pi pico (GND, PWR and SIG (I chose pin 28 for my SIG pin and for my second OneWire sensor I chose pin 12))

OneWire adapter boards (there are two)

OneWire to Pico (GP28)

Thonny IDE Setup

Steps to setup Thonny for use with pico w

Connect Raspberry Pi Pico

Connect the pico to your computer using a micro-USB to USB-A cable

Open Thonny IDE

Click 'Configure Interpreter' or the hamburger menu on the bottom right

Select 'MicroPython (Raspberry Pi Pico)'

Install Required Packages

Ensure Raspberry pi pico is connected

Select 'Tools' -> 'Manage packages...'

Search for and install 'network' 'onewire' 'piicodev' 'smbus2'

This should install the required libraries and put them in a folder called 'lib'

Programming The Pico W

Code and explanation of some sections of the code

main.py

import json, onewire, ds18x20
from os import stat
from utime import sleep
from machine import Pin, reset
from urequests import get, post
from network import WLAN, STA_IF
from PiicoDev_RV3028 import PiicoDev_RV3028
from PiicoDev_TMP117 import PiicoDev_TMP117

# Initialize pins for controlling power and the on-board LED
DONE = Pin(22, Pin.OUT)
LED = Pin("LED", Pin.OUT); LED.off()

# Initialize RTC and temperature sensors
RTC = PiicoDev_RV3028()
tempSensor = PiicoDev_TMP117(asw=[1, 0, 0, 0])
onewire_sensor = ds18x20.DS18X20(onewire.OneWire(Pin(28)))
onewire_sensor2 = ds18x20.DS18X20(onewire.OneWire(Pin(12)))
onewire_scan = [onewire_sensor.scan(), onewire_sensor2.scan()]

# Setup WLAN
wlan = WLAN(STA_IF)
wlan.active(True)

# Function to set RTC time from an online API
def fixtime():
    data = get("https://worldtimeapi.org/api/timezone/Australia/Melbourne").json()["datetime"]
    RTC.year, RTC.month, RTC.day = int(data[:4]), int(data[5:7]), int(data[8:10])
    hour = int(data[11:13])
    RTC.hour, RTC.ampm = (hour-12, "PM") if hour > 12 else (hour, "AM")
    RTC.minute, RTC.second = int(data[14:16]), int(data[17:19])
    RTC.setDateTime()

# Function to read the file content, optionally returning the last line
def getFileContent(filename, last_line=False):
    try:
        file_size = stat(filename)[6]
        if file_size == 0:
            return None
        with open(filename) as f:
            return f.readlines()[-1].strip() if last_line else f.read()
    except OSError:
        return False

# Function to connect to WiFi network
def connect_to_wifi():
    wlan.connect("YourSSID", "YourPASSWD")
    for _ in range(21):
        if wlan.isconnected():
            print('Network config:', wlan.ifconfig())
            return
        print('Waiting for connection...')
        sleep(1)
    log_error("WiFi Connection Error", "Timeout")
    DONE.on()
    reset()

# Function to log errors with a timestamp
def log_error(context, exception):
    error_time = RTC.timestamp()
    with open("time.txt", "w") as t, open("errors.txt", "a") as f:
        t.write(error_time)
        f.write(f'({context} at time: {error_time}) Containing: {exception}\n')

# Function to get temperature data based on sensor index
def getData(whichOne):
    if whichOne == 0:
        onewire_sensor.convert_temp()
        sleep(1)
        return onewire_sensor.read_temp(onewire_scan[0][0])
    elif whichOne == 1:
        return tempSensor.readTempC()
    elif whichOne == 2:
        onewire_sensor2.convert_temp()
        sleep(1)
        return onewire_sensor2.read_temp(onewire_scan[1][0])
    else:
        log_error("getData Error", f"incorrect input: {whichOne}")
        return None

# Function to post data to a remote server
def postData():
    data = {
        'outdoor_temp': getData(0),
        'in_house_temp': getData(2),
        'cont_box_temp': tempSensor.readTempC(),
        'timestamp': RTC.timestamp(),
        'last_error_time': getFileContent("time.txt"),
        'last_error': getFileContent("errors.txt", last_line=True)
    }
    headers = {'Content-Type': 'application/json'}
    try:
        response = post('https://dweet.io/dweet/for/TinyHouse', data=json.dumps(data), headers=headers)
        out = response.text
        response.close()
        return out
    except Exception as e:
        log_error("Posting Error", e)
        return None

# Main execution block
try:
    connect_to_wifi()  # Connect to WiFi
    LED.on()  # Turn on the LED to indicate activity
    print('Starting data posting...')
    fixtime()  # Sync RTC with online time
    print(postData())  # Post temperature data
    LED.off()  # Turn off the LED after completing data posting
except Exception as e:
    log_error("Main Execution Error", e)
    LED.off()
    DONE.on()  # Set DONE pin high to remove power

Explanations

1. Initial Setup:

  • The code starts by setting up four sensors:
    • An LED light that can be turned on and off
    • A real-time clock (RTC) to keep track of time
    • Two temperature sensors: one precision sensor inside (TMP117) and one waterproof sensor outside (DS18X20)

2. WiFi Connection:

  • The code tries to connect to WiFi using a username (ssid) and password
  • If it can't connect within 20 seconds, it will restart the device
  • Once connected, it shows the network information

3. getData Function:

  • This function can read from either temperature sensor
  • If you call it with 0, it reads the outdoor temperature
  • If you call it with 1, it reads the indoor temperature
  • If you call it with 2, it reads the second outdoor temperature sensor
  • If you use any other number, it gives an error message

4. postData Function:

  • This function collects four pieces of information:
    • The outdoor temperature
    • The indoor temperature
    • The second outdoor temperature
    • The current time from the clock
  • It packages this information together
  • It sends this data to a website called "dweet.io" where it can be stored and viewed
  • The data is sent to a specific channel called "TinyHouse"

5. Try/Except:

  • The program runs the Trys to:
  • Turns the LED on
  • Sends the temperature data
  • Turns the LED off
  • Turns the Pico off for 1-hour
  • Repeats
    • If it can't do any of these it will log the error to a file

Think of it like a weather station that:

  • Takes temperature readings from inside and outside your house
  • Adds a timestamp to know when the readings were taken
  • Sends this information to the internet every minute
  • Turns an LED on when it is sending data, so you know it's working
  • Turns the LED off when it has finished sending data

Testing

If everything is setup correctly you should se a similar output at https://dweet.io/follow/TinyHouse in the 'RAW' tab

{
  "outdoor_temp2": 25.3125,
  "timestamp": "2024-12-07 01:05:57 PM",
  "outdoor_temp": 25.5,
  "indoor_temp": 25.97656
}