Voltage Sensor – with pico w 2

  • R1 – 7.5K
    R2 – 30K
from machine import ADC
from time import sleep

# Use ADC0 (GPIO26)
adc = ADC(26)

# Constants
VREF = 3.3              # Pico ADC reference voltage
ADC_RESOLUTION = 65535  # For read_u16() scale
DIVIDER_RATIO = 5       # Because 7.5k / (30k + 7.5k) = 0.2 → inverse is 5

def read_input_voltage():
    raw = adc.read_u16()
    v_out = (raw / ADC_RESOLUTION) * VREF
    v_in = v_out * DIVIDER_RATIO
    return round(v_in, 3)

# Main loop
while True:
    voltage = read_input_voltage()
    print("Measured Voltage:", voltage, "V")
    sleep(1)

Since the Pico ADC max is 3.3V and you’re dividing by 5: Vin max=3.3V×5=16.5VV = 3.3V \times 5 = 16.5V

Vin max​=3.3V×5=16.5V

So you can safely measure up to about 16.5 volts.

Pico 2 w – HC-SR04 ultrasonic distance sensor

Pins:

from machine import Pin, time_pulse_us
from time import sleep

# Define GPIO pins
TRIG = Pin(3, Pin.OUT)
ECHO = Pin(2, Pin.IN)

def get_distance():
    # Ensure trigger is low
    TRIG.low()
    sleep(0.002)  # Let sensor settle
    
    # Send a 10µs pulse to trigger
    TRIG.high()
    sleep(0.00001)
    TRIG.low()

    # Measure time for echo
    try:
        duration = time_pulse_us(ECHO, 1, 30000)  # 30ms timeout
    except OSError as ex:
        print("Pulse timed out")
        return None

    # Distance calculation: time (us) × speed of sound (cm/us) / 2
    distance_cm = (duration * 0.0343) / 2
    return round(distance_cm, 2)

# Main loop
while True:
    dist = get_distance()
    if dist:
        print("Distance:", dist, "cm")
    else:
        print("No distance measured.")
    sleep(1)

Pi Pico 2 W – UF2 flash – install

  • While connect to your PC first press the BOOTSEL cutton on the pico 2 w and then connect the USB
  • It will be connected as new drive(FS mode). you can view in “files”

Pico W with MQ-135 air quality sensor – Prometheus pushgateway

If you want to make portable Air quality sensor this is very easy setup. Make sure to include you mobile hostspot wifi ssid so that you can easily collect data from anywhere on the go.

Gas sensor normal takes 2-3 min to normalized it’s output vaules.

  • Pins
VCC = 3v3(OUT) - GP36
GND = GND -GP38
Input = ADC0 - GP26
  • Code
import network
import urequests
import machine
import time
import ubinascii

#only needed if sending over public ip with https.
USERNAME_P = "basic-auth-username"
PASSWORD_P = 'basic-auth-pass'

# WiFi Credentials
SSID = 'WIFI-SSID'
PASSWORD = 'WIFI-PASSWORD'

# PushGateway Configuration
PUSHGATEWAY_URL = 'https://pushgateway.example.com/metrics/job/gas_sensor/instance/pico-1/sensor/mq135'

# ADC Setup for MQ-135 on GP26 (ADC0)
adc = machine.ADC(26)

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():
            time.sleep(0.5)
    print('Connected, IP:', wlan.ifconfig()[0])

def read_gas_sensor():
    raw_value = adc.read_u16()  # 0–65535
    voltage = raw_value * 3.3 / 65535  # Convert to voltage if needed
    return raw_value, voltage

def send_to_pushgateway(value):
    # Prometheus format (you can include labels if you want)
    payload = f"gas_sensor_value {value}\n"
    auth_string = "{}:{}".format(USERNAME_P, PASSWORD_P)
    auth_encoded = ubinascii.b2a_base64(auth_string.encode()).decode().strip()
    
    headers = {
        "Content-Type": "text/plain",
        "Authorization": "Basic " + auth_encoded
    }
    try:
        res = urequests.post(PUSHGATEWAY_URL, data=payload, headers=headers, timeout=5)
        print("Pushed to gateway:", res.status_code)
        res.close()
    except Exception as e:
        print("Push failed:", e)

def main():
    connect_wifi()
    while True:
        raw, voltage = read_gas_sensor()
        print(f"Gas Sensor Raw: {raw} | Voltage: {voltage:.3f}V")
        send_to_pushgateway(raw)
        time.sleep(1)  # Push every 10 seconds

main()

  • timeout=5 is to fix the error code -110, [Errno 110] , ETIMEDOUT, [Errno 115] EINPROGRESS
  • Read data from pico over USB tty
#find device
dmesg | grep tty

$ read X < /dev/ttyACM0
hello
$ echo $X
Gas Sensor Raw: 2496 | Voltage: 0.126V
  • Read using screen command
screen /dev/ttyACM0

#with Baud rate

screen /dev/ttyACM0 9600

Adafruit_DHT22 python3 issue fixed – RuntimeError: Unknown platform

git clone https://github.com/adafruit/Adafruit_Python_DHT.git

cd Adafruit_Python_DHT


if [ $(cat /proc/cpuinfo | grep Hardware | wc -l) != "1" ] ; then
  cat /proc/cpuinfo > /etc/cpuinfo 
  echo -e "\nHardware       : BCM2709" >> /etc/cpuinfo 
  mount --bind /etc/cpuinfo /proc/cpuinfo
  echo "Mounted cpuinfo with Hardware info"
fi

python3 setup.py install

https://stackoverflow.com/questions/72554099/error-installing-adafruit-dht-for-python-on-raspberry-pi-400

camera raspberry pi

raspistill -o image_$(date +%s).jpg -w 480 -h 360
root@lp-arm-4:~# raspistill -o image_$(date +%s).jpg -w 480 -h 360
mmal: Cannot read camera info, keeping the defaults for OV5647
mmal: mmal_vc_component_create: failed to create component 'vc.ril.camera' (1:ENOMEM)
mmal: mmal_component_create_core: could not create component 'vc.ril.camera' (1)
mmal: Failed to create camera component
mmal: main: Failed to create camera component
mmal: Only 76M of gpu_mem is configured. Try running "sudo raspi-config" and ensure that "memory_split" has a value of 128 or greater

/boot/firmware/config.txt add gpu_mem=128

Switch relay with Raspberry pi + Arduino Uno

The 5V Relay switch require that i have require around 52mA current to work properly.

  • Raspberry pi max GPIO current with 5v Relay = ?
  • Arduino pin 13 current with 5v Relay = 38.5mA
  • Arduino pin 13 + 12 current with 5v Relay = 45 mA
  • Arduino pin 13 + 12 + 2 current with 5v Relay = 47.3 mA ( This worked )

So Now i can use Arduino as a switch on/off. Also I needed this switching to be based on some external events. So I used Aurdino Pin 2 as INPUT pin and added one 2.7K ohm resistor to from pin2 to Ground.

int status = 0;

void setup() {
  pinMode(13, OUTPUT);
  pinMode(12, OUTPUT);
  pinMode(2, INPUT);
}

void loop() {
  status = digitalRead(2);
  if (status == HIGH) {
    digitalWrite(13, HIGH);
    digitalWrite(12, HIGH);
    digitalWrite(8, HIGH);
  }
  else {
    digitalWrite(13, LOW);
    digitalWrite(12, L0W);
    digitalWrite(8, LOW);
  }
}

Switch ON = 7PM
Switch OFF = 12AM

  • added Cronjob on Raspberry Pi 4
0 19 * * * /usr/bin/python3.8 /opt/led.py on
0 0 * * * /usr/bin/python3.8 /opt/led.py on

led.py

import RPi.GPIO as GPIO
from time import sleep 
import sys

GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(21, GPIO.OUT, initial=GPIO.LOW)

if sys.argv[1] == "on":
    GPIO.output(21, GPIO.HIGH)
    #print("on")
    exit()
elif sys.argv[1] == "off":
    GPIO.output(21, GPIO.LOW)
    #print("off")
    exit()

Raspberry Pi Max current with GPIO for LED

Note: withdrawing more current(~15mA) from GPIO can affect the Rpi
https://raspberrypi.stackexchange.com/questions/9298/what-is-the-maximum-current-the-gpio-pins-can-output

  • Use 5V Pin (2,4)
  • Use GPIO as Negative volt
  • Max current withdrawn was 23mA for my use case
import RPi.GPIO as GPIO
from time import sleep 
import sys

GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(21, GPIO.OUT, initial=GPIO.HIGH)

if sys.argv[1] == "on":
    GPIO.output(21, GPIO.LOW)
    #print("on")
    exit()

Fore More brightness:

  • Add multiple GPIO as GROUND
  • After adding GPIO20 as ground it was taking ~18mA from GPIO20
  • And Overall of ~36mA from both GPIO 20 and 21

Raspberry pi 4 to measure temperature and humidity with DHT11/DHT22 sensor

pip3 install adafruit-circuitpython-dht
apt-get install libgpiod2

temp.py

import Adafruit_DHT
import time
 
DHT_SENSOR = Adafruit_DHT.DHT11
DHT_PIN = 4

#while loop is there because sometime it does not get the temp.
while True:
    humidity, temperature = Adafruit_DHT.read(DHT_SENSOR, DHT_PIN)
    if humidity is not None and temperature is not None:
        print("Temp={0:0.1f}C Humidity={1:0.1f}%".format(temperature, humidity))
    else:
        print("Sensor failure. Check wiring.");
    time.sleep(1);

run:

python3 temp.py

For DHT22 sensor:

temp-dht22.py

import Adafruit_DHT
import time

DHT_SENSOR = Adafruit_DHT.DHT22
DHT_PIN = 4

humidity, temperature = Adafruit_DHT.read(DHT_SENSOR, DHT_PIN)
if humidity is not None and temperature is not None:
    #print("Temp={0:0.1f}C Humidity={1:0.1f}%".format(temperature, humidity))
    print("{0},{1}".format(temperature, humidity))
  • shell script to send over pushgateway
root@lp-arm-1:~# cat /opt/cron/get_temp_dht22.sh
#!/bin/bash

t_and_h=$(python3 /opt/cron/get_temp_dht22.py)

temprerature=$(echo $t_and_h | awk -F ',' '{print $1}')
humidity=$(echo $t_and_h | awk -F ',' '{print $2}')
echo "room_temp $temprerature" | curl --data-binary @- http://192.168.0.183:30008/metrics/job/room_temp/instance/lp-arm-1
echo "room_humidity $humidity" | curl --data-binary @- http://192.168.0.183:30008/metrics/job/room_humidity/instance/lp-arm-1