Smart Cities - Tiny House at Home (Alternate way)

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

Required Items

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

from machine import *
from utime import sleep
import json
import socket
import network
import urequests
import onewire, ds18x20
from PiicoDev_RV3028 import PiicoDev_RV3028
from PiicoDev_TMP117 import PiicoDev_TMP117

# Initialize components
led = Pin("LED", Pin.OUT)  # Assign LED pin for output
rtc = PiicoDev_RV3028()  # Initialize Real-Time Clock (RTC) module
tempSensor = PiicoDev_TMP117(asw=[1, 0, 0, 0])  # Initialize Precision Temperature Sensor
onewire_sensor = ds18x20.DS18X20(onewire.OneWire(Pin(28)))  # Initialize first OneWire Temperature Sensor
onewire_sensor2 = ds18x20.DS18X20(onewire.OneWire(Pin(12)))  # Initialize second OneWire Temperature Sensor

# Scan for connected OneWire sensors
onewire_scan = []
onewire_scan.append(onewire_sensor.scan())  # Scan for the first OneWire sensor
onewire_scan.append(onewire_sensor2.scan())  # Scan for the second OneWire sensor
print(onewire_scan)  # Print scanned addresses of OneWire sensors

# Network setup
wlan = network.WLAN(network.STA_IF)  # Create a WLAN object in Station mode
wlan.active(True)  # Activate the WLAN interface
try:
    wlan.connect(ssid, password)  # Connect to the WiFi network
    timeout = 0
    while not wlan.isconnected():  # Wait for the connection to be established
        print('Waiting for connection...')
        sleep(1)  # Pause for a second before checking again
        timeout += 1  # Increment timeout counter
        if timeout > 20:  # Check if timeout limit is reached
            raise Exception("WiFi connection timeout")  # Raise an exception if timeout occurs
    print('Network config:', wlan.ifconfig())  # Print network configuration details
except Exception as e:
    print(f"WiFi connection error: {e}")  # Print any connection errors
    machine.reset()  # Reset the machine in case of failure

# Function to get temperature data based on sensor index
def getData(whichOne):
    if whichOne == 0:
        onewire_sensor.convert_temp()  # Convert temperature for the first sensor
        sleep(1)  # Allow time for temperature conversion
        outdoor_temp = onewire_sensor.read_temp(onewire_scan[0][0])  # Read temperature from the first sensor
        return outdoor_temp
    elif whichOne == 1:
        return tempSensor.readTempC()  # Read temperature from the precision sensor
    elif whichOne == 2:
        onewire_sensor2.convert_temp()  # Convert temperature for the second sensor
        sleep(1)  # Allow time for temperature conversion
        outdoor_temp2 = onewire_sensor2.read_temp(onewire_scan[1][0])  # Read temperature from the second sensor
        return outdoor_temp2
    else:
        print(f'incorrect input: {whichOne}, value should be 0, 1 or 2')  # Print error for invalid input

# Function to post temperature data to a remote server
def postData():
    # Create data dictionary with both temperatures and timestamp
    data = {
        'outdoor_temp': getData(0),  # Get outdoor temperature from the first sensor
        'indoor_temp': tempSensor.readTempC(),  # Get indoor temperature from the precision sensor
        'timestamp': rtc.timestamp(),  # Get the current timestamp from the RTC
        'outdoor_temp2': getData(2)  # Get outdoor temperature from the second sensor
    }
    # Convert data dictionary to JSON format and set headers
    json_data = json.dumps(data)
    headers = {'Content-Type': 'application/json'}  # Specify content type for the request
    # Make the POST request to the server
    response = urequests.post(
        'https://dweet.io/dweet/for/TinyHouse',
        data=json_data,
        headers=headers
    )
    out = response.text  # Get the response text
    response.close()  # Close the response to free resources
    return out  # Return the server response

# Main loop to continuously post data
while True:
    led.on()  # Turn on LED indicator
    print(postData())  # Post data and print server response
    led.off()  # Turn off LED indicator
    sleep(60)  # Wait for 60 seconds before repeating

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. Main Loop:

  • The program runs forever in a loop that:
  • Turns the LED on
  • Sends the temperature data
  • Turns the LED off
  • Waits for 60 seconds (1 minute)
  • Repeats

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 in the Shell

MPY: soft reboot
72
Network config: ('192.168.*.*', '255.255.0.0', '192.168.*.*', '192.168.*.*')
{"this":"succeeded","by":"dweeting","the":"dweet","with":{"thing":"TinyHouse","created":"2024-11-30T05:58:41.887Z","content":{"outdoor_temp":23.5625,"timestamp":"2024-11-30 04:58:33 PM","indoor_temp":24.04688},"transaction":"fe7831d5-2423-4154-a2e8-29480c4130af"}}