Internet connection matrixportal M4 -CO2

Moderators: adafruit_support_bill, adafruit

Forum rules
If you're posting code, please make sure your code does not include your Adafruit IO Active Key or WiFi network credentials.
Locked
User avatar
richardorluk
 
Posts: 4
Joined: Thu Dec 02, 2021 8:44 am

Internet connection matrixportal M4 -CO2

Post by richardorluk »

Hello all,
New to this.
I have a matrix portal M4 with Sensorian SCD 30 sensor for CO2/temp/humidity monitoring which is doing a great job of logging data to Adafruit.IO. Though I am curious as to a better way to connect to wifi, maintain connection to wifi, as well as search several SSIDs. As you will see in the code, I used some of the Adafruit examples for connecting to wifi.

I can leave the board on for about 8 hrs before it will disconnect from the internet and need a reset. (perhaps router is reassigning IP and board not automatically trying again? as it's stuck in the while true loop). How do I ensure it stays connected? Though the board is sitting right next to the router, so no reason for connection to get dropped from a physical standpoint.

FYI (For anyone using the SCD30 I did have to calibrate manually to outside air, CO2 ~400, and make the auto calibrate FALSE, as the auto calibrate needs to be placed outside 1 hr a day for the first 7 days you use it, and cannot be shut off. So I was getting some pretty high readings with the sensor after the first week out of the box.)

Code: Select all

 import time
import board
import displayio
import adafruit_imageload
from adafruit_matrixportal.matrix import Matrix
import adafruit_scd30
import busio
from digitalio import DigitalInOut
import adafruit_esp32spi.adafruit_esp32spi_socket as socket
from adafruit_esp32spi import adafruit_esp32spi
import adafruit_requests as requests
from adafruit_io.adafruit_io import IO_HTTP, AdafruitIO_RequestError

# Get wifi details and more from a secrets.py file
try:
    from secrets import secrets
except ImportError:
    print("WiFi secrets are kept in secrets.py, please add them there!")
    raise

esp32_cs = DigitalInOut(board.ESP_CS)
esp32_ready = DigitalInOut(board.ESP_BUSY)
esp32_reset = DigitalInOut(board.ESP_RESET)
spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)
print("Connecting to SSID 1...")
while not esp.is_connected:
    try:
        esp.connect_AP(secrets["ssid1"], secrets["password1"])
    except RuntimeError as e:
        print("Trying AP 2...")
        esp.connect_AP(secrets["ssid2"], secrets["password2"])
        print("could not connect to AP, retrying: ", e)
        continue
print("Connected to", str(esp.ssid, "utf-8"), "\tRSSI:", esp.rssi)
print("My IP address is", esp.pretty_ip(esp.ip_address))
print(
    "IP lookup adafruit.com: %s" % esp.pretty_ip(esp.get_host_by_name("adafruit.com")))
print("Ping google.com: %d ms" % esp.ping("google.com"))

socket.set_interface(esp)
requests.set_socket(socket, esp)

# Set your Adafruit IO Username and Key in secrets.py
# (visit io.adafruit.com if you need to create an account,
# or if you need your Adafruit IO key.)
aio_username = secrets["aio_username"]
aio_key = secrets["aio_key"]

# Initialize an Adafruit IO HTTP API object
io = IO_HTTP(aio_username, aio_key, requests)

try:
    # Get the 'temperature' feed from Adafruit IO
    co2_feed = io.get_feed("co2")
    print("CO2 Feed Loaded")
except AdafruitIO_RequestError:
    # If no 'temperature' feed exists, create one
    print("error unable to find feed")
    co2_feed = io.create_new_feed("co2")
    print("CO2 Feed Created")
try:
    tempFeed = io.get_feed("temperature")
    print("Temp Feed Loaded")
except AdafruitIO_RequestError:
    tempFeed = io.create_new_feed("temperature")
    print("Temp Feed Created")
try:
    humidityFeed = io.get_feed("humidity")
    print("Humidity Feed Loaded")
except AdafruitIO_RequestError:
    tempFeed = io.create_new_feed("humidity")
    print("Humidity Feed Created")


"""
try:
    tempFeed = io.get_feed("Temperature")
except AdafruitIO_RequestError:
    tempFeed = io.create_new_feed("Temperature")
try:
    humidityFeed = io.get_feed("Humidity")
except AdafruitIO_RequestError:
    humidityFeed = io.create_new_feed("Humidity")
   """
# --| User Config |----
CO2_CUTOFFS = (1000, 2000, 5000)
UPDATE_RATE = 1
# ---------------------

# the sensor
scd30 = adafruit_scd30.SCD30(board.I2C())
scd30.self_calibration_enabled = False

# optional if known (pick one)
# scd30.ambient_pressure = 1013.25
# scd30.altitude = 0

# the display
matrix = Matrix(width=64, height=32, bit_depth=6)
display = matrix.display
display.rotation = 90  # matrixportal up
# display.rotation = 270 # matrixportal down

# current condition smiley face
smileys_bmp, smileys_pal = adafruit_imageload.load("/bmps/smileys.bmp")
smiley = displayio.TileGrid(
    smileys_bmp,
    pixel_shader=smileys_pal,
    x=0,
    y=0,
    width=1,
    height=1,
    tile_width=32,
    tile_height=32,
)

# current condition label
tags_bmp, tags_pal = adafruit_imageload.load("/bmps/tags.bmp")
label = displayio.TileGrid(
    tags_bmp,
    pixel_shader=tags_pal,
    x=0,
    y=32,
    width=1,
    height=1,
    tile_width=32,
    tile_height=16,
)

# current CO2 value
digits_bmp, digits_pal = adafruit_imageload.load("/bmps/digits.bmp")
co2_value = displayio.TileGrid(
    digits_bmp,
    pixel_shader=digits_pal,
    x=0,
    y=51,
    width=4,
    height=1,
    tile_width=8,
    tile_height=10,
)

# put em all together
splash = displayio.Group()
splash.append(smiley)
splash.append(label)
splash.append(co2_value)

# and show em
display.show(splash)


def update_display(value):
    value = abs(round(value))
    # smiley and label
    if value < CO2_CUTOFFS[0]:
        smiley[0] = label[0] = 0
    elif value < CO2_CUTOFFS[1]:
        smiley[0] = label[0] = 1
    elif value < CO2_CUTOFFS[2]:
        smiley[0] = label[0] = 2
    else:
        smiley[0] = label[0] = 3

    # CO2 value
    # clear it
    for i in range(4):
        co2_value[i] = 10
    # update it
    i = 3
    while value:
        co2_value[i] = value % 10
        value = int(value / 10)
        i -= 1

x = 0
while True:
    # protect against NaNs and Nones
    try:

        update_display(scd30.CO2 + 400)
        print("CO2: ", round(scd30.CO2 + 400))
        newco2 = round(scd30.CO2 + 400)
        #print(round(scd30.CO2), ",")
        print("Temp: ", (round(((scd30.temperature) * 9/5 + 32 ), 1 )))
        newtemp = round((scd30.temperature) * 9/5 + 32, 1)
# print(round((scd30.temperature) * 9/5 + 32))
        print("Humidity: ", (round(scd30.relative_humidity, 1)))
        newhumidity = round(scd30.relative_humidity, 1)
        io.send_data(co2_feed["key"], newco2)
        io.send_data(tempFeed["key"], newtemp)
        io.send_data(humidityFeed["key"], newhumidity)
        print("hello world", newco2, newtemp, newhumidity)
        time.sleep(5)
    except:
        pass
    time.sleep(UPDATE_RATE)
  

User avatar
jwcooper
 
Posts: 1004
Joined: Tue May 01, 2012 9:08 pm

Re: Internet connection matrixportal M4 -CO2

Post by jwcooper »

I'm not 100% on this without testing, but one suggestion is in your while true loop, you can check if your wifi is connected using the `esp.is_connected` call.

If it is not connected, re-run the setup to connect to wifi. You could put that all in a method, so it's easier to call. Something like:

Code: Select all

def connect_wifi:
    print("Connecting to SSID 1...")
    while not esp.is_connected:
        try:
            esp.connect_AP(secrets["ssid1"], secrets["password1"])
        except RuntimeError as e:
            print("Trying AP 2...")
            esp.connect_AP(secrets["ssid2"], secrets["password2"])
            print("could not connect to AP, retrying: ", e)
            continue

Locked
Forum rules
If you're posting code, please make sure your code does not include your Adafruit IO Active Key or WiFi network credentials.

Return to “Internet of Things: Adafruit IO and Wippersnapper”