Combining Sensors and Recording#
We can now combine different sensors to take multiple readings. It would be useful to also save/log multiple readings.
In this section we will cover how
Combining with SD cards#
We will take the code we developed to measure both VOCs and temperature and humidity and record those values to a SD card.
We will assume you have followed the guide on how to wire up a SD card
import board
import busio
import sdcardio
import storage
import time
import microcontroller
import digitalio
#Add imports for your sensor(s)
spi = busio.SPI(board.GP2, MOSI = board.GP3, MISO = board.GP4) #Assign the SPI pins
cs = board.GP0
led = digitalio.DigitalInOut(board.LED)
led.direction = digitalio.Direction.OUTPUT
sdcard = sdcardio.SDCard(spi, cs) #Create an object for the SD card
vfs = storage.VfsFat(sdcard) #Create an object for the SD card's filesystem
storage.mount(vfs, "/sd") #Represent the filesystem with an "sd" folder
filepath = "/sd/temperature.txt" #Create a variable to hold the filepath
with open(filepath, "a") as f:
f.write('Starting new set of measurements\n')
f.write('')
print('Writing to SD card\n')
#Add set up code for your sensors
while True:
try:
#Acquire code goes here
with open(filepath, "a") as f:
f.write(f"Results: {Results}\n")
print(f"Results: {Results}\n")
except OSError as e:
led.value = False
time.sleep(0.5)
led.value = True
print(e)
time.sleep(5)
Here we have taken the existing SD code and added comments where the sensor codes need to be added
import board
import busio
import sdcardio
import storage
import time
import microcontroller
import digitalio
#Add imports for your sensor(s)
import adafruit_dht
import adafruit_sgp30
spi = busio.SPI(board.GP2, MOSI = board.GP3, MISO = board.GP4) #Assign the SPI pins
cs = board.GP0
led = digitalio.DigitalInOut(board.LED)
led.direction = digitalio.Direction.OUTPUT
sdcard = sdcardio.SDCard(spi, cs) #Create an object for the SD card
vfs = storage.VfsFat(sdcard) #Create an object for the SD card's filesystem
storage.mount(vfs, "/sd") #Represent the filesystem with an "sd" folder
filepath = "/sd/temperature.txt" #Create a variable to hold the filepath
with open(filepath, "a") as f:
f.write('Starting new set of measurements\n')
f.write('')
print('Writing to SD card\n')
#Add set up code for your sensors
# Set up DHT connection
dht = adafruit_dht.DHT11(board.GP0)
#Set up the SPG30 connection
i2c = busio.I2C(board.GP21, board.GP20, frequency=100000)
sgp30 = adafruit_sgp30.Adafruit_SGP30(i2c)
sgp30.iaq_init()
elapsed_sec = 0
while True:
try:
# Get the temp and humidity
temp = dht.temperature
humidity = dht.humidity
# Now get the VOC concentration
eCO2 = sgp30.eCO2
TVOC = sgp30.TVOC
with open(filepath, "a") as f:
#Acquire code goes here
f.write(f"({TVOC},{temp},{humidity})")
print(f"({TVOC},{temp},{humidity})")
except OSError as e:
led.value = False
time.sleep(0.5)
led.value = True
print(e)
time.sleep(5)