From a23bf2ca82b9db3d19a74d443c4944cda7be1d2a Mon Sep 17 00:00:00 2001 From: Edward Bigos Date: Fri, 19 Apr 2024 10:47:24 -0400 Subject: [PATCH] Added Pico W lab code --- CLONE-This-Repo.md | 47 +++++++ Initial-Setup/MacOSX-Setup.txt | 21 +++ README.md | 8 +- picow-lab-code/Lab09Code/blink.py | 13 ++ picow-lab-code/Lab09Code/secrets.py | 4 + picow-lab-code/Lab09Code/settings.toml | 12 ++ picow-lab-code/Lab09Code/test-settings.py | 12 ++ picow-lab-code/Lab09Code/test_secrets.py | 8 ++ picow-lab-code/Lab09Code/wifi_connect.py | 28 ++++ picow-lab-code/Lab09Code/wifi_scan.py | 11 ++ picow-lab-code/Lab10Code/blink.py | 13 ++ picow-lab-code/Lab10Code/blink15.py | 12 ++ picow-lab-code/Lab10Code/pwm_fade.py | 26 ++++ picow-lab-code/Lab10Code/pwm_fade2.py | 26 ++++ picow-lab-code/Lab10Code/pwm_fade3.py | 31 +++++ picow-lab-code/Lab10Code/secrets-stcc.py | 9 ++ picow-lab-code/Lab10Code/secrets.py | 8 ++ picow-lab-code/Lab10Code/webServer1.py | 122 ++++++++++++++++++ picow-lab-code/Lab10Code/wifiConnect1.py | 23 ++++ picow-lab-code/Lab11Code/blink.py | 21 +++ picow-lab-code/Lab11Code/dhtcode.py | 46 +++++++ picow-lab-code/Lab11Code/sensor2cloud.py | 112 ++++++++++++++++ picow-lab-code/Lab11Code/settings.toml | 6 + picow-lab-code/Lab12Code/blink.py | 21 +++ picow-lab-code/Lab12Code/dhtcode.py | 46 +++++++ picow-lab-code/Lab12Code/readAnalog01.py | 40 ++++++ picow-lab-code/Lab12Code/sensors2cloud.py | 104 +++++++++++++++ picow-lab-code/Lab12Code/sensors2cloud2.py | 143 +++++++++++++++++++++ picow-lab-code/Lab12Code/settings.toml | 8 ++ 29 files changed, 974 insertions(+), 7 deletions(-) create mode 100644 CLONE-This-Repo.md create mode 100644 Initial-Setup/MacOSX-Setup.txt create mode 100644 picow-lab-code/Lab09Code/blink.py create mode 100644 picow-lab-code/Lab09Code/secrets.py create mode 100644 picow-lab-code/Lab09Code/settings.toml create mode 100644 picow-lab-code/Lab09Code/test-settings.py create mode 100644 picow-lab-code/Lab09Code/test_secrets.py create mode 100644 picow-lab-code/Lab09Code/wifi_connect.py create mode 100644 picow-lab-code/Lab09Code/wifi_scan.py create mode 100644 picow-lab-code/Lab10Code/blink.py create mode 100644 picow-lab-code/Lab10Code/blink15.py create mode 100644 picow-lab-code/Lab10Code/pwm_fade.py create mode 100644 picow-lab-code/Lab10Code/pwm_fade2.py create mode 100644 picow-lab-code/Lab10Code/pwm_fade3.py create mode 100644 picow-lab-code/Lab10Code/secrets-stcc.py create mode 100644 picow-lab-code/Lab10Code/secrets.py create mode 100644 picow-lab-code/Lab10Code/webServer1.py create mode 100644 picow-lab-code/Lab10Code/wifiConnect1.py create mode 100644 picow-lab-code/Lab11Code/blink.py create mode 100755 picow-lab-code/Lab11Code/dhtcode.py create mode 100755 picow-lab-code/Lab11Code/sensor2cloud.py create mode 100644 picow-lab-code/Lab11Code/settings.toml create mode 100755 picow-lab-code/Lab12Code/blink.py create mode 100755 picow-lab-code/Lab12Code/dhtcode.py create mode 100755 picow-lab-code/Lab12Code/readAnalog01.py create mode 100644 picow-lab-code/Lab12Code/sensors2cloud.py create mode 100644 picow-lab-code/Lab12Code/sensors2cloud2.py create mode 100644 picow-lab-code/Lab12Code/settings.toml diff --git a/CLONE-This-Repo.md b/CLONE-This-Repo.md new file mode 100644 index 0000000..1127e69 --- /dev/null +++ b/CLONE-This-Repo.md @@ -0,0 +1,47 @@ +# 2024SP-ELE128L +## Cloning This Git Repository + +### To clone this directory: +Install git on your system. +Open a command prompt (Windows) or a terminal (Linux, Mac OS) +Run the command below. + +git clone https://cset2.stcc.edu/git/bigos/2024SP-ELE128L.git + +Your working directory is 2024SP/2024SP-ELE128L + +### To pull in new changes: +Open a command prompt (Windows) or a terminal (Linux, Mac OS) +Change your working directory to 2024SP/2024SP-ELE128L +Run the command below. + +git pull https://cset2.stcc.edu/git/bigos/2024SP-ELE128L.git + +Mac OS X Example + +```commandline +cd ~ +mkdir 2024SP +cd ~/2024SP +ls +git clone https://cset2.stcc.edu/git/bigos/2024SP-ELE128L.git +Cloning into '2024SP-ELE128L'... +remote: Enumerating objects: 9, done. +remote: Counting objects: 100% (9/9), done. +remote: Compressing objects: 100% (8/8), done. +remote: Total 9 (delta 1), reused 0 (delta 0), pack-reused 0 +Receiving objects: 100% (9/9), 13.66 KiB | 6.83 MiB/s, done. +Resolving deltas: 100% (1/1), done. +ls +2024SP-ELE128L +ls -l 2024SP-ELE128L +total 80 +-rw-r--r-- 1 edbigos staff 34592 Apr 19 09:07 LICENSE +-rw-r--r-- 1 edbigos staff 569 Apr 19 09:07 README.md +cd 2024SP-ELE128L +ls +LICENSE README.md +``` + + + diff --git a/Initial-Setup/MacOSX-Setup.txt b/Initial-Setup/MacOSX-Setup.txt new file mode 100644 index 0000000..164cc38 --- /dev/null +++ b/Initial-Setup/MacOSX-Setup.txt @@ -0,0 +1,21 @@ +cd ~ +mkdir 2024SP +cd ~/2024SP +ls +git clone https://cset2.stcc.edu/git/bigos/2024SP-ELE128L.git +Cloning into '2024SP-ELE128L'... +remote: Enumerating objects: 9, done. +remote: Counting objects: 100% (9/9), done. +remote: Compressing objects: 100% (8/8), done. +remote: Total 9 (delta 1), reused 0 (delta 0), pack-reused 0 +Receiving objects: 100% (9/9), 13.66 KiB | 6.83 MiB/s, done. +Resolving deltas: 100% (1/1), done. +ls +2024SP-ELE128L +ls -l 2024SP-ELE128L +total 80 +-rw-r--r-- 1 edbigos staff 34592 Apr 19 09:07 LICENSE +-rw-r--r-- 1 edbigos staff 569 Apr 19 09:07 README.md +cd 2024SP-ELE128L +ls +LICENSE README.md diff --git a/README.md b/README.md index 3bdcca0..a081233 100644 --- a/README.md +++ b/README.md @@ -3,13 +3,7 @@ ## Code and Documents for the ELE-128L Lab ### To clone this directory: -Install git on your system. -Open a command prompt (Windows) or a terminal (Linux, Mac OS) -Run the command below. - -git clone https://cset2.stcc.edu/git/bigos/2024SP-ELE128L.git - -Your working directory is 2024SP/2024SP-ELE128L +See the Clone-This-Repo.md file ### To pull in new changes: Open a command prompt (Windows) or a terminal (Linux, Mac OS) diff --git a/picow-lab-code/Lab09Code/blink.py b/picow-lab-code/Lab09Code/blink.py new file mode 100644 index 0000000..097d6d6 --- /dev/null +++ b/picow-lab-code/Lab09Code/blink.py @@ -0,0 +1,13 @@ +import time +import board +import digitalio + +LED_PIN = digitalio.DigitalInOut(board.LED) +LED_PIN.direction = digitalio.Direction.OUTPUT + +while True: + print("Loop") + LED_PIN.value = True + time.sleep(1) + LED_PIN.value = False + time.sleep(1) diff --git a/picow-lab-code/Lab09Code/secrets.py b/picow-lab-code/Lab09Code/secrets.py new file mode 100644 index 0000000..735cac5 --- /dev/null +++ b/picow-lab-code/Lab09Code/secrets.py @@ -0,0 +1,4 @@ +secrets = { + 'ssid': 'cset@stcc', + 'password': 'c1s2e3t4', + } diff --git a/picow-lab-code/Lab09Code/settings.toml b/picow-lab-code/Lab09Code/settings.toml new file mode 100644 index 0000000..d4975a8 --- /dev/null +++ b/picow-lab-code/Lab09Code/settings.toml @@ -0,0 +1,12 @@ +# Comments are supported +# CSET SSID and pass + +LOCATION="STCC" + +CIRCUITPY_WIFI_SSID="cset@stcc" +CIRCUITPY_WIFI_PASSWORD="c1s2e3t4" + +CIRCUITPY_WEB_API_PORT=80 +CIRCUITPY_WEB_API_PASSWORD="passw0rd" +test_variable="this is a test" +thumbs_up="\U0001f44d" diff --git a/picow-lab-code/Lab09Code/test-settings.py b/picow-lab-code/Lab09Code/test-settings.py new file mode 100644 index 0000000..3e0470c --- /dev/null +++ b/picow-lab-code/Lab09Code/test-settings.py @@ -0,0 +1,12 @@ +import os + +print("Location:",os.getenv("LOCATION"),"\n") + +print(os.getenv("CIRCUITPY_WIFI_SSID")) +print(os.getenv("CIRCUITPY_WIFI_PASSWORD")) + +print(os.getenv("CIRCUITPY_WEB_API_PORT")) +print(os.getenv("CIRCUITPY_WEB_API_PASSWORD")) + +print(os.getenv("test_variable")) +print(os.getenv("thumbs_up")) diff --git a/picow-lab-code/Lab09Code/test_secrets.py b/picow-lab-code/Lab09Code/test_secrets.py new file mode 100644 index 0000000..294b870 --- /dev/null +++ b/picow-lab-code/Lab09Code/test_secrets.py @@ -0,0 +1,8 @@ +from secrets import secrets + +# Load login data from different file for safety reasons +WiFiSSID = secrets['ssid'] +WiFiPassword = secrets['password'] + +print(WiFiSSID) +print(WiFiPassword) diff --git a/picow-lab-code/Lab09Code/wifi_connect.py b/picow-lab-code/Lab09Code/wifi_connect.py new file mode 100644 index 0000000..53992c0 --- /dev/null +++ b/picow-lab-code/Lab09Code/wifi_connect.py @@ -0,0 +1,28 @@ +# SPDX-FileCopyrightText: 2022 Liz Clark for Adafruit Industries +# +# SPDX-License-Identifier: MIT + +import os +import ipaddress +import wifi +import socketpool + +print() +print("Connecting to WiFi") + +# connect to your SSID +wifi.radio.connect(os.getenv('CIRCUITPY_WIFI_SSID'), os.getenv('CIRCUITPY_WIFI_PASSWORD')) + +print("Connected to WiFi") + +pool = socketpool.SocketPool(wifi.radio) + +# prints MAC address to REPL +print("My MAC addr:", [hex(i) for i in wifi.radio.mac_address]) + +# prints IP address to REPL +print("My IP address is", wifi.radio.ipv4_address) + +# pings Google +ipv4 = ipaddress.ip_address("8.8.4.4") +print("Ping google.com: %f ms" % (wifi.radio.ping(ipv4)*1000)) diff --git a/picow-lab-code/Lab09Code/wifi_scan.py b/picow-lab-code/Lab09Code/wifi_scan.py new file mode 100644 index 0000000..9681adb --- /dev/null +++ b/picow-lab-code/Lab09Code/wifi_scan.py @@ -0,0 +1,11 @@ +import wifi + +# https://learn.adafruit.com/todbot-circuitpython-tricks/networking + +networks = [] +for network in wifi.radio.start_scanning_networks(): + networks.append(network) +wifi.radio.stop_scanning_networks() +networks = sorted(networks, key=lambda net: net.rssi, reverse=True) +for network in networks: + print("ssid:",network.ssid, "rssi:",network.rssi) diff --git a/picow-lab-code/Lab10Code/blink.py b/picow-lab-code/Lab10Code/blink.py new file mode 100644 index 0000000..c09dd7f --- /dev/null +++ b/picow-lab-code/Lab10Code/blink.py @@ -0,0 +1,13 @@ +import machine + +import time + +led = machine.Pin("LED", machine.Pin.OUT) #configure GPIO-15 Pin as an output pin and create and led object for Pin class + +while True: + led.value(True) #turn on the LED + time.sleep(1) #wait for one second + led.value(False) #turn off the LED + time.sleep(1) #wait for one second + + diff --git a/picow-lab-code/Lab10Code/blink15.py b/picow-lab-code/Lab10Code/blink15.py new file mode 100644 index 0000000..5232266 --- /dev/null +++ b/picow-lab-code/Lab10Code/blink15.py @@ -0,0 +1,12 @@ +import machine + +import time + +led = machine.Pin(15, machine.Pin.OUT) #configure GPIO-15 Pin as an output pin and create and led object for Pin class + +while True: + led.value(True) #turn on the LED + time.sleep(1) #wait for one second + led.value(False) #turn off the LED + time.sleep(1) #wait for one second + diff --git a/picow-lab-code/Lab10Code/pwm_fade.py b/picow-lab-code/Lab10Code/pwm_fade.py new file mode 100644 index 0000000..1d9f61c --- /dev/null +++ b/picow-lab-code/Lab10Code/pwm_fade.py @@ -0,0 +1,26 @@ +# Example using PWM to fade an LED. + +import time +import machine +from machine import Pin, PWM + + +# Construct PWM object, with LED on Pin(25). +pwm = PWM(Pin(15)) + +# Set the PWM frequency. +pwm.freq(1000) + +# Fade the LED in and out a few times. +duty = 0 +direction = 1 +for _ in range(8 * 256): + duty += direction + if duty > 255: + duty = 255 + direction = -1 + elif duty < 0: + duty = 0 + direction = 1 + pwm.duty_u16(duty * duty) + time.sleep(0.001) diff --git a/picow-lab-code/Lab10Code/pwm_fade2.py b/picow-lab-code/Lab10Code/pwm_fade2.py new file mode 100644 index 0000000..54e70bc --- /dev/null +++ b/picow-lab-code/Lab10Code/pwm_fade2.py @@ -0,0 +1,26 @@ +# Example using PWM to fade an LED. + +import time +import machine +from machine import Pin, PWM + + +# Construct PWM object, with LED on Pin(25). +pwm = PWM(Pin(15)) + +# Set the PWM frequency. +pwm.freq(1000) + +# Fade the LED in and out a few times. +duty = 0 +direction = 1 +for _ in range(8 * 256): + duty += direction + if duty > 255: + duty = 255 + direction = -1 + elif duty < 0: + duty = 0 + direction = 1 + pwm.duty_u16(duty * duty) + time.sleep(0.01) diff --git a/picow-lab-code/Lab10Code/pwm_fade3.py b/picow-lab-code/Lab10Code/pwm_fade3.py new file mode 100644 index 0000000..d7a45ec --- /dev/null +++ b/picow-lab-code/Lab10Code/pwm_fade3.py @@ -0,0 +1,31 @@ +# Example using PWM to fade an LED. + +import time +import machine +from machine import Pin, PWM + +def pwmFade(): + # Fade the LED in and out a few times. + duty = 0 + direction = 1 + for _ in range(8 * 256): + duty += direction + if duty > 255: + duty = 255 + direction = -1 + elif duty < 0: + duty = 0 + direction = 1 + pwm.duty_u16(duty * duty) + time.sleep(0.001) + return 0 + + +# Construct PWM object, with LED on Pin(25). +pwm = PWM(Pin(15)) + +# Set the PWM frequency. +pwm.freq(1000) + +# Fade the LED in and out a few times. +pwmFade() diff --git a/picow-lab-code/Lab10Code/secrets-stcc.py b/picow-lab-code/Lab10Code/secrets-stcc.py new file mode 100644 index 0000000..f56c75a --- /dev/null +++ b/picow-lab-code/Lab10Code/secrets-stcc.py @@ -0,0 +1,9 @@ +secrets = { + 'location': 'STCC', + 'ssid': 'cset@stcc', + 'password': 'c1s2e3t4', + } + +SSID = "cset@stcc" +PASSWORD = "c1s2e3t4" + diff --git a/picow-lab-code/Lab10Code/secrets.py b/picow-lab-code/Lab10Code/secrets.py new file mode 100644 index 0000000..d6ac36f --- /dev/null +++ b/picow-lab-code/Lab10Code/secrets.py @@ -0,0 +1,8 @@ +secrets = { + 'location': 'STCC', + 'ssid': 'cset@stcc', + 'password': 'c1s2e3t4', + } + +SSID = "cset@stcc" +PASSWORD = "c1s2e3t4" diff --git a/picow-lab-code/Lab10Code/webServer1.py b/picow-lab-code/Lab10Code/webServer1.py new file mode 100644 index 0000000..bc6af26 --- /dev/null +++ b/picow-lab-code/Lab10Code/webServer1.py @@ -0,0 +1,122 @@ +# Complete project details at https://RandomNerdTutorials.com/raspberry-pi-pico-web-server-micropython/ + +# Import necessary modules +import network +import socket +import time +import random +from machine import Pin +from secrets import secrets + +# Create an LED object on pin 'LED' +led = Pin('LED', Pin.OUT) + +# Wi-Fi credentials +ssid = secrets['ssid'] +password = secrets['password'] + +# HTML template for the webpage +def webpage(random_value, state): + html = f""" + + + + Pico Web Server + + + +

Raspberry Pi Pico Web Server

+

Led Control

+
+ +
+
+
+ +
+

LED state: {state}

+

Fetch New Value

+
+ +
+

Fetched value: {random_value}

+ + + """ + return str(html) + +# Connect to WLAN +wlan = network.WLAN(network.STA_IF) +wlan.active(True) +wlan.connect(ssid, password) + +# Wait for Wi-Fi connection +connection_timeout = 10 +while connection_timeout > 0: + if wlan.status() >= 3: + break + connection_timeout -= 1 + print('Waiting for Wi-Fi connection...') + time.sleep(1) + +# Check if connection is successful +if wlan.status() != 3: + raise RuntimeError('Failed to establish a network connection') +else: + print('Connection successful!') + network_info = wlan.ifconfig() + print('IP address:', network_info[0]) + +# Set up socket and start listening +addr = socket.getaddrinfo('0.0.0.0', 80)[0][-1] +s = socket.socket() +s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) +s.bind(addr) +s.listen() + +print('Listening on', addr) + +# Initialize variables +state = "OFF" +random_value = 0 + +# Main loop to listen for connections +while True: + try: + conn, addr = s.accept() + print('Got a connection from', addr) + + # Receive and parse the request + request = conn.recv(1024) + request = str(request) + print('Request content = %s' % request) + + try: + request = request.split()[1] + print('Request:', request) + except IndexError: + pass + + # Process the request and update variables + if request == '/lighton?': + print("LED on") + led.value(1) + state = "ON" + elif request == '/lightoff?': + led.value(0) + state = 'OFF' + elif request == '/value?': + random_value = random.randint(0, 20) + + # Generate HTML response + response = webpage(random_value, state) + + # Send the HTTP response and close the connection + conn.send('HTTP/1.0 200 OK\r\nContent-type: text/html\r\n\r\n') + conn.send(response) + conn.close() + + except OSError as e: + conn.close() + print('Connection closed') + \ No newline at end of file diff --git a/picow-lab-code/Lab10Code/wifiConnect1.py b/picow-lab-code/Lab10Code/wifiConnect1.py new file mode 100644 index 0000000..d99f4a2 --- /dev/null +++ b/picow-lab-code/Lab10Code/wifiConnect1.py @@ -0,0 +1,23 @@ +import network +import secrets +from utime import sleep, ticks_ms, ticks_diff +from secrets import secrets + +print('Connecting to WiFi Network Name:', secrets['ssid']) +wlan = network.WLAN(network.STA_IF) +wlan.active(True) + +start = ticks_ms() # start a millisecond counter + +if not wlan.isconnected(): + wlan.connect(secrets['ssid'], secrets['password']) + print("Waiting for connection...") + counter = 0 + while not wlan.isconnected(): + sleep(1) + print(counter, '.', sep='', end='', ) + counter += 1 + +delta = ticks_diff(ticks_ms(), start) +print("Connect Time:", delta, 'milliseconds') +print('IP Address:', wlan.ifconfig()[0]) diff --git a/picow-lab-code/Lab11Code/blink.py b/picow-lab-code/Lab11Code/blink.py new file mode 100644 index 0000000..ede9faa --- /dev/null +++ b/picow-lab-code/Lab11Code/blink.py @@ -0,0 +1,21 @@ +# SPDX-FileCopyrightText: 2021 Kattni Rembor for Adafruit Industries +# +# SPDX-License-Identifier: MIT + +"""Example for Pico. Turns the built-in LED on and off with no delay.""" +import board +import digitalio +import time + +led = digitalio.DigitalInOut(board.LED) +led.direction = digitalio.Direction.OUTPUT + +while True: + led.value = True + print("LED On") + time.sleep(1) + led.value = False + print("LED Off") + time.sleep(1) + + diff --git a/picow-lab-code/Lab11Code/dhtcode.py b/picow-lab-code/Lab11Code/dhtcode.py new file mode 100755 index 0000000..5745f47 --- /dev/null +++ b/picow-lab-code/Lab11Code/dhtcode.py @@ -0,0 +1,46 @@ +# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries +# SPDX-License-Identifier: MIT + +import time +import board +import adafruit_dht + +def readDHTSensor(): + runFlag = True + while runFlag: + try: + # Print the values to the serial port + temperature_c = dhtDevice.temperature + temperature_f = temperature_c * (9 / 5) + 32 + humidity = dhtDevice.humidity + print( + "Temp: {:.1f} F / {:.1f} C Humidity: {}% ".format( + temperature_f, temperature_c, humidity + ) + ) + runFlag = False + + except RuntimeError as error: + # Errors happen fairly often, DHT's are hard to read, just keep going + print(error.args[0]) + time.sleep(2.0) + continue + except Exception as error: + dhtDevice.exit() + raise error + + return [temperature_f, temperature_c, humidity] + +# Initial the dht device, with data pin connected to: +dhtDevice = adafruit_dht.DHT11(board.GP4) + +# you can pass DHT22 use_pulseio=False if you wouldn't like to use pulseio. +# This may be necessary on a Linux single board computer like the Raspberry Pi, +# but it will not work in CircuitPython. +# dhtDevice = adafruit_dht.DHT22(board.D18, use_pulseio=False) + +while True: + sensorReadings = readDHTSensor() + print(sensorReadings) + time.sleep(2.0) + diff --git a/picow-lab-code/Lab11Code/sensor2cloud.py b/picow-lab-code/Lab11Code/sensor2cloud.py new file mode 100755 index 0000000..3ffaa41 --- /dev/null +++ b/picow-lab-code/Lab11Code/sensor2cloud.py @@ -0,0 +1,112 @@ +# SPDX-FileCopyrightText: 2022 Liz Clark for Adafruit Industries +# SPDX-License-Identifier: MIT + +import os +import sys +import time +import ssl +import wifi +import socketpool +import microcontroller +import board +import busio +import adafruit_requests +import adafruit_ahtx0 +import adafruit_dht +from adafruit_io.adafruit_io import IO_HTTP, AdafruitIO_RequestError +from microcontroller import cpu + +def readDHTSensor(): + runFlag = True + while runFlag: + try: + # Print the values to the serial port + temperature_c = dhtDevice.temperature + temperature_f = temperature_c * (9 / 5) + 32 + humidity = dhtDevice.humidity + print( + "Temp: {:.1f} F / {:.1f} C Humidity: {}% ".format( + temperature_f, temperature_c, humidity + ) + ) + runFlag = False + + except RuntimeError as error: + # Errors happen fairly often, DHT's are hard to read, just keep going + print(error.args[0]) + time.sleep(2.0) + continue + except Exception as error: + dhtDevice.exit() + raise error + + return [temperature_f, humidity, temperature_c] + +# Initial the dht device, with data pin connected to: +dhtDevice = adafruit_dht.DHT11(board.GP4) + + + +wifi.radio.connect(os.getenv('CIRCUITPY_WIFI_SSID'), os.getenv('CIRCUITPY_WIFI_PASSWORD')) + +aio_username = os.getenv('aio_username') +aio_key = os.getenv('aio_key') + +pool = socketpool.SocketPool(wifi.radio) +requests = adafruit_requests.Session(pool, ssl.create_default_context()) +# Initialize an Adafruit IO HTTP API object +io = IO_HTTP(aio_username, aio_key, requests) +print("connected to io") + +# use Pico W's GP0 for SDA and GP1 for SCL +#i2c = busio.I2C(board.GP1, board.GP0) +#aht20 = adafruit_ahtx0.AHTx0(i2c) + +try: +# get feed + picowTemp_feed = io.get_feed("mytemperature") + picowHumid_feed = io.get_feed("myhumidity") +except AdafruitIO_RequestError: +# if no feed exists, create one + print("Feed error") + sys.exit(-1) + +# pack feed names into an array for the loop +feed_names = [picowTemp_feed, picowHumid_feed] +print("feeds created") + +clock = 300 + + +while True: + try: + # when the clock runs out.. + if clock > 50: + # read sensor + dhtData = readDHTSensor() + data = [dhtData[0], dhtData[1]] + # send sensor data to respective feeds + for z in range(2): + io.send_data(feed_names[z]["key"], data[z]) + print("sent %0.1f" % data[z]) + time.sleep(1) + # print sensor data to the REPL + print("\nTemperature: %0.1f C" % data[0]) + print("Humidity: %0.1f %%" % data[1]) + print() + + time.sleep(1) + # reset clock + clock = 0 + else: + clock += 1 + # pylint: disable=broad-except + # any errors, reset Pico W + except Exception as e: + print("Error:\n", str(e)) +# print("Resetting microcontroller in 10 seconds") + time.sleep(3) +# microcontroller.reset() + # delay + time.sleep(1) + print(clock) diff --git a/picow-lab-code/Lab11Code/settings.toml b/picow-lab-code/Lab11Code/settings.toml new file mode 100644 index 0000000..3677fab --- /dev/null +++ b/picow-lab-code/Lab11Code/settings.toml @@ -0,0 +1,6 @@ +CIRCUITPY_WIFI_SSID = "cset@stcc" +CIRCUITPY_WIFI_PASSWORD = "c1s2e3t4" + +# Replace the next two lines with your Adafruit username and key. +aio_username = "csetuser" +aio_key = "aio_MoIy372savdsgdasgasgasgd" \ No newline at end of file diff --git a/picow-lab-code/Lab12Code/blink.py b/picow-lab-code/Lab12Code/blink.py new file mode 100755 index 0000000..ede9faa --- /dev/null +++ b/picow-lab-code/Lab12Code/blink.py @@ -0,0 +1,21 @@ +# SPDX-FileCopyrightText: 2021 Kattni Rembor for Adafruit Industries +# +# SPDX-License-Identifier: MIT + +"""Example for Pico. Turns the built-in LED on and off with no delay.""" +import board +import digitalio +import time + +led = digitalio.DigitalInOut(board.LED) +led.direction = digitalio.Direction.OUTPUT + +while True: + led.value = True + print("LED On") + time.sleep(1) + led.value = False + print("LED Off") + time.sleep(1) + + diff --git a/picow-lab-code/Lab12Code/dhtcode.py b/picow-lab-code/Lab12Code/dhtcode.py new file mode 100755 index 0000000..5745f47 --- /dev/null +++ b/picow-lab-code/Lab12Code/dhtcode.py @@ -0,0 +1,46 @@ +# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries +# SPDX-License-Identifier: MIT + +import time +import board +import adafruit_dht + +def readDHTSensor(): + runFlag = True + while runFlag: + try: + # Print the values to the serial port + temperature_c = dhtDevice.temperature + temperature_f = temperature_c * (9 / 5) + 32 + humidity = dhtDevice.humidity + print( + "Temp: {:.1f} F / {:.1f} C Humidity: {}% ".format( + temperature_f, temperature_c, humidity + ) + ) + runFlag = False + + except RuntimeError as error: + # Errors happen fairly often, DHT's are hard to read, just keep going + print(error.args[0]) + time.sleep(2.0) + continue + except Exception as error: + dhtDevice.exit() + raise error + + return [temperature_f, temperature_c, humidity] + +# Initial the dht device, with data pin connected to: +dhtDevice = adafruit_dht.DHT11(board.GP4) + +# you can pass DHT22 use_pulseio=False if you wouldn't like to use pulseio. +# This may be necessary on a Linux single board computer like the Raspberry Pi, +# but it will not work in CircuitPython. +# dhtDevice = adafruit_dht.DHT22(board.D18, use_pulseio=False) + +while True: + sensorReadings = readDHTSensor() + print(sensorReadings) + time.sleep(2.0) + diff --git a/picow-lab-code/Lab12Code/readAnalog01.py b/picow-lab-code/Lab12Code/readAnalog01.py new file mode 100755 index 0000000..c7be2dc --- /dev/null +++ b/picow-lab-code/Lab12Code/readAnalog01.py @@ -0,0 +1,40 @@ +# SPDX-FileCopyrightText: 2018 Kattni Rembor for Adafruit Industries +# +# SPDX-License-Identifier: MIT + +"""CircuitPython Essentials Analog In example""" +import time +import board +from analogio import AnalogIn + +analog_in0 = AnalogIn(board.A0) +analog_in1 = AnalogIn(board.A1) + +minLightValue = .1 +maxLightValue = 2.8 + +minLightValue = .01 +maxPotValue = 3.28 + +def getAnalogValue(pin): + return [pin.value,(pin.value * 3.3) / 65536] + +def get_voltage(pin): + return (pin.value * 3.3) / 65536 + + + +while True: +# print((get_voltage(analog_in0),)) +# print(get_voltage(analog_in0)," ",get_voltage(analog_in1)) + pinValue0 = getAnalogValue(analog_in0) + pinValue1 = getAnalogValue(analog_in1) + + scaledLightValue = pinValue0[1]/maxLightValue * 100 + scaledPotValue = pinValue1[1]/maxPotValue * 100 + + print(getAnalogValue(analog_in0),"\t",getAnalogValue(analog_in1)) + print("\tScaled Light Value = ",scaledLightValue,"\tScaled Pot Value = ",scaledPotValue) + print() + + time.sleep(1.0) diff --git a/picow-lab-code/Lab12Code/sensors2cloud.py b/picow-lab-code/Lab12Code/sensors2cloud.py new file mode 100644 index 0000000..9bdd3ef --- /dev/null +++ b/picow-lab-code/Lab12Code/sensors2cloud.py @@ -0,0 +1,104 @@ +# SPDX-FileCopyrightText: 2022 Liz Clark for Adafruit Industries +# SPDX-License-Identifier: MIT + +import os +import time +import ssl +import wifi +import socketpool +import microcontroller +import board +import busio +import adafruit_requests +import adafruit_ahtx0 +import adafruit_dht +from adafruit_io.adafruit_io import IO_HTTP, AdafruitIO_RequestError +from microcontroller import cpu + +def readDHTSensor(): + runFlag = True + while runFlag: + try: + # Print the values to the serial port + temperature_c = dhtDevice.temperature + temperature_f = temperature_c * (9 / 5) + 32 + humidity = dhtDevice.humidity + print("Temp: {:.1f} F / {:.1f} C Humidity: {}% ".format(temperature_f, temperature_c, humidity)) + runFlag = False + + except RuntimeError as error: + # Errors happen fairly often, DHT's are hard to read, just keep going + print(error.args[0]) + time.sleep(2.0) + continue + except Exception as error: + dhtDevice.exit() + raise error + + return [temperature_f, humidity, temperature_c] + +# Initial the dht device, with data pin connected to: +dhtDevice = adafruit_dht.DHT11(board.GP4) + + + +wifi.radio.connect(os.getenv('CIRCUITPY_WIFI_SSID'), os.getenv('CIRCUITPY_WIFI_PASSWORD')) + +aio_username = os.getenv('aio_username') +aio_key = os.getenv('aio_key') + +pool = socketpool.SocketPool(wifi.radio) +requests = adafruit_requests.Session(pool, ssl.create_default_context()) +# Initialize an Adafruit IO HTTP API object +io = IO_HTTP(aio_username, aio_key, requests) +print("connected to io") + +# use Pico W's GP0 for SDA and GP1 for SCL +#i2c = busio.I2C(board.GP1, board.GP0) +#aht20 = adafruit_ahtx0.AHTx0(i2c) + +try: +# get feed + picowTemp_feed = io.get_feed("mytemperature") + picowHumid_feed = io.get_feed("myhumidity") +except AdafruitIO_RequestError: + print("Feed error") + sys.exit(-1) + +# pack feed names into an array for the loop +feed_names = [picowTemp_feed, picowHumid_feed] +print("feeds created") + +clock = 300 + + +while True: + try: + # when the clock runs out.. + if clock >= 10: + # read sensors + dhtData = readDHTSensor() + + data = [dhtData[0], dhtData[1]] + # send sensor data to respective feeds + for z in range(2): + io.send_data(feed_names[z]["key"], data[z]) +# print("sent %0.1f" % data[z]) + time.sleep(1) + # print sensor data to the REPL +# print(f"{data[0]:.1f}F {data[1]:.1f}% Humidity") + + time.sleep(1) + # reset clock + clock = 0 + else: + clock += 1 + # pylint: disable=broad-except + # any errors, reset Pico W + except Exception as e: + print("Error:\n", str(e)) + time.sleep(3) +# microcontroller.reset() + # delay + time.sleep(1) + print(clock) diff --git a/picow-lab-code/Lab12Code/sensors2cloud2.py b/picow-lab-code/Lab12Code/sensors2cloud2.py new file mode 100644 index 0000000..73ed31c --- /dev/null +++ b/picow-lab-code/Lab12Code/sensors2cloud2.py @@ -0,0 +1,143 @@ +# SPDX-FileCopyrightText: 2022 Liz Clark for Adafruit Industries +# SPDX-License-Identifier: MIT + +import os +import time +import ssl +import sys +import wifi +import socketpool +import microcontroller +import board +import busio +import adafruit_requests +import adafruit_ahtx0 +import adafruit_dht +from adafruit_io.adafruit_io import IO_HTTP, AdafruitIO_RequestError +from microcontroller import cpu +from analogio import AnalogIn + +analog_in0 = AnalogIn(board.A0) # Pin 31 (Right side, 10 down from top) +analog_in1 = AnalogIn(board.A1) # Pin 32 (Right side, 9 down from top) + + +minLightValue = .1 +maxLightValue = 2.8 + +minPotValue = .1 +maxPotValue = 3.3 + + +def getAnalogValue(pin): + return [pin.value,(pin.value * 3.3) / 65536] + +def readDHTSensor(): + runFlag = True + while runFlag: + try: + # Print the values to the serial port + temperature_c = dhtDevice.temperature + temperature_f = temperature_c * (9 / 5) + 32 + humidity = dhtDevice.humidity + print( + "Temp: {:.1f} F / {:.1f} C Humidity: {}% ".format( + temperature_f, temperature_c, humidity + ) + ) + runFlag = False + + except RuntimeError as error: + # Errors happen fairly often, DHT's are hard to read, just keep going + print(error.args[0]) + time.sleep(2.0) + continue + except Exception as error: + dhtDevice.exit() + raise error + + return [temperature_f, humidity, temperature_c] + +# Initial the dht device, with data pin connected to: +dhtDevice = adafruit_dht.DHT11(board.GP4) + + + +wifi.radio.connect(os.getenv('CIRCUITPY_WIFI_SSID'), os.getenv('CIRCUITPY_WIFI_PASSWORD')) + +aio_username = os.getenv('aio_username') +aio_key = os.getenv('aio_key') + +pool = socketpool.SocketPool(wifi.radio) +requests = adafruit_requests.Session(pool, ssl.create_default_context()) +# Initialize an Adafruit IO HTTP API object +io = IO_HTTP(aio_username, aio_key, requests) +print("connected to io") + +# use Pico W's GP0 for SDA and GP1 for SCL +#i2c = busio.I2C(board.GP1, board.GP0) +#aht20 = adafruit_ahtx0.AHTx0(i2c) + +try: +# get feed + picowTemp_feed = io.get_feed("mytemperature") + picowHumid_feed = io.get_feed("myhumidity") + picowLight_feed = io.get_feed("mylightlevel") + picowPot_feed = io.get_feed("mypotlevel") +except AdafruitIO_RequestError: +# if no feed exists, create one + print("Feed error") + sys.exit(-1) + +# pack feed names into an array for the loop +feed_names = [picowTemp_feed, picowHumid_feed,picowLight_feed,picowPot_feed] +print("feeds created") + +clock = 300 + + +while True: + try: + # when the clock runs out.. + if clock > 10: + # read sensors + lightLevel = getAnalogValue(analog_in0) + scaledLightValue = lightLevel[1]/maxLightValue * 100 + potLevel = getAnalogValue(analog_in1) + scaledPotValue = potLevel[1]/maxPotValue * 100 + print("Scaled Light Value = ",scaledLightValue) + print("Scaled Pot Value = ",scaledPotValue) + +# print("light level: ",lightLevel) +# lightPerCent = lightLevel[1] /3 + + dhtData = readDHTSensor() + + data = [dhtData[0], dhtData[1], scaledLightValue,scaledPotValue] + # send sensor data to respective feeds + for z in range(4): + io.send_data(feed_names[z]["key"], data[z]) +# print("sent %0.1f" % data[z]) + time.sleep(1) + # print sensor data to the REPL +# print(type(data[0]), type(data[1]), type(data[2])) + print(f"{data[0]:.1f}F {data[1]:.1f}% Humidity {data[2]:.1f}% Light Level {data[3]:.1f}% Pot Level") +# print("\nTemperature: %0.1f C" % data[0]) +# print("Humidity: %0.1f %%" % data[1]) +# print("\nLight percent: %0.1f " % data[2]) +# print() + + time.sleep(1) + # reset clock + clock = 0 + else: + clock += 1 + # pylint: disable=broad-except + # any errors, reset Pico W + except Exception as e: + print("Error:\n", str(e)) +# print("Resetting microcontroller in 10 seconds") + time.sleep(3) +# microcontroller.reset() + # delay + time.sleep(1) + print(clock) diff --git a/picow-lab-code/Lab12Code/settings.toml b/picow-lab-code/Lab12Code/settings.toml new file mode 100644 index 0000000..9380266 --- /dev/null +++ b/picow-lab-code/Lab12Code/settings.toml @@ -0,0 +1,8 @@ +CIRCUITPY_WIFI_SSID = "cset@stcc" +CIRCUITPY_WIFI_PASSWORD = "c1s2e3t4" + +# Replace the next two lines with your Adafruit username and key. +aio_username = "csetuser" +aio_key = "aio_MoIy372savdsgdasgasgasgd" + +