Smart Cities - Tiny House at Home (Alternate way)
Required Items
- Raspberry pi pico wh (wireless with headers)
- OneWire temperature sensor (x2)
- Plugable Terminal V2 (x2)
- Power timer for Pico
- High quality breadboard
- Precision temperature sensor
- RTC - Real Time Clock
- Breadboard to join sensors + required cables/jumper wires
- Optional:
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
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)
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
DONE = Pin(22, Pin.OUT) # setting this pin High will remove power, and wait for the next interval
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
# 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:
f = open("errors.txt", "a")
f.write(f'(LN:40) Wifi Error at time: {rtc.timestamp()}. Containing: {e}')
f.close
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
try:
led.on()
print(postData())
led.off()
except Exception as e:
f = open("errors.txt", "a")
f.write(f'(LN:88) Posting Error at time: {rtc.timestamp()}. Containing: {e}')
f.close
led.off()
DONE.on()
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
Fix When Next data comes through




