Setting Up a Raspberry Pi Pico W with Sensors and WIFI

Protonest IoT
4 min readMay 9, 2024

--

This guide will walk you through the steps to connect multiple sensors to a Raspberry Pi Pico W and run MicroPython scripts to interact with the sensors.

We’ll start with the hardware setup and then move on to software installation and code execution.

Hardware Setup

1. Raspberry Pi Pico W

2. BME280 Sensor

3. Capacitive Soil Moisture Sensor

4. Photoresistor Sensor Module

5. Breadboard (optional, for easier prototyping)

6. Jumper wires

Connection Diagram

Software Setup and Code Upload

Download and Install Thonny IDE

  • Visit the Thonny website and download the installer for your operating system(https://thonny.org/)
  • Follow the installation instructions to install Thonny on your computer.

Prepare the Raspberry Pi Pico W

  • Plug your Raspberry Pi Pico W into your computer using a microUSB cable.
  • Hold the BOOTSEL button if it’s the first time or if you need to reinstall MicroPython.
  • Release the BOOTSEL button after the Pico appears as a removable drive on your computer.

Install MicroPython on the Pico W

Open Thonny and Configure for MicroPython

  • Open Thonny IDE.
  • Go to Tools > Options and select the Interpreter tab
  • Choose MicroPython (Raspberry Pi Pico) as the interpreter.
  • Check the option “Try to detect port automatically”

Download the BME280 Library

  • Go to Tools > Manage packages and enter ‘micropython-bme280’
  • Install the library

Upload Your Script

  • Open a script and paste the below code on Thorny.

The code is set to send data to the cloud by calling an API.

The sensor is set to send once per hour.

import machine
import utime
import network
import urequests
from machine import Pin, I2C
from time import sleep
import BME280

# Initialize I2C for BME280
i2c=I2C(id=0,scl=Pin(0), sda=Pin(1), freq=10000) #initializing the I2C method


# Initialize the ADC for the sensors
adc_moisture = machine.ADC(26)
adc_light = machine.ADC(27)

# WiFi details
ssid = '<Your SSID>' #Replace with your Wifi SSID
password = '<Your Password>' #Replace with your Wifi Password

def connect_wifi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
print("Connecting to WiFi...")
wlan.connect(ssid, password)
while not wlan.isconnected():
pass
print('Connected to WiFi!')

def read_sensors():
# Reading from BME280 for humidity
try:
# Initialize BME280 sensor
bme = BME280.BME280(i2c=i2c)
# Read sensor data
temperature = bme.temperature
humidity = bme.humidity

# Print sensor readings
print('Temperature: ', temperature)
print('Humidity: ', humidity)

except Exception as e:
# Handle any exceptions during sensor reading
print('An error occurred:', e)
temperature = 0
humidity = 0

# Reading from soil moisture sensor and converting to percentage
raw_moisture = adc_moisture.read_u16()
moisture_percentage = (raw_moisture / 65535) * 100
print('Moisture: ', moisture_percentage)

# Reading from light sensor and converting to percentage
raw_light = adc_light.read_u16()
light_percentage = 100 - (raw_light / 65535) * 100
print('Light Intensity: ', light_percentage)
return humidity, moisture_percentage, light_percentage, temperature

def send_data():
humidity, moisture_percentage, light_percentage, tempC = read_sensors()
print("All good")
tempC = clean_and_convert(tempC)
humidity = clean_and_convert(humidity)

api_url = '<Add the URL for the API>'
data = {
"temperature":float(tempC),
"humidity":float(humidity),
"moisture":float(moisture_percentage),
"light":float(light_percentage)
}
try:
response = urequests.post(api_url, json=data)
print(response.text)
response.close()
except Exception as e:
# Handle any exceptions during sensor reading
print('An error occurred:', e)

def clean_and_convert(value):
value = value.replace('C', '').replace('%', '').strip()
value = value.replace(',', '.')
try:
return float(value)
except ValueError:
print("Failed to convert:", value)
return None

connect_wifi()

# Main loop
while True:
send_data()
utime.sleep(3600) # Sleep for 1 hour

  • With the Pico connected and selected in Thonny, go to File > Save As.
  • Save the script as main.py inside the Rasp Pi Pico W.
  • Run the script.
  • Now the script should work.

Contact us for any consultations or projects related to Raspberry Pi Pico.

Email: udara@protonest.co

Protonest for more details.

Protonest specializes in transforming IoT ideas into reality. We offer prototyping services from concept to completion. Our commitment ensures that your visionary IoT concepts become tangible, innovative, and advanced prototypes.

Our Website: https://www.protonest.co/

If you enjoyed this article and would like to show some support, consider buying me a coffee on Ko-Fi.

Your support not only helps me keep creating content like this but also fuels me! ☕️📚

Thank you for being an amazing reader!

Here’s my Ko-Fi link: https://ko-fi.com/udarakumarasena

Cheers!

--

--

Protonest IoT
Protonest IoT

Written by Protonest IoT

We make your IoT ideas a reality

No responses yet