/ Disconnected_CO2_Data_Logger / code.py
code.py
1 # SPDX-FileCopyrightText: 2021 Liz Clark for Adafruit Industries 2 # 3 # SPDX-License-Identifier: MIT 4 5 import time 6 import board 7 import adafruit_scd4x 8 import sdcardio 9 import busio 10 import storage 11 import adafruit_pcf8523 12 13 # setup for I2C 14 i2c = board.I2C() 15 # setup for SCD40 16 scd4x = adafruit_scd4x.SCD4X(i2c) 17 # setup for RTC 18 rtc = adafruit_pcf8523.PCF8523(i2c) 19 # start measuring co2 with SCD40 20 scd4x.start_periodic_measurement() 21 # list of days to print to the text file on boot 22 days = ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday") 23 24 # SPI SD_CS pin 25 SD_CS = board.D10 26 27 # SPI setup for SD card 28 spi = busio.SPI(board.SCK, board.MOSI, board.MISO) 29 sdcard = sdcardio.SDCard(spi, SD_CS) 30 vfs = storage.VfsFat(sdcard) 31 try: 32 storage.mount(vfs, "/sd") 33 print("sd card mounted") 34 except ValueError: 35 print("no SD card") 36 37 # to update the RTC, change set_clock to True 38 # otherwise RTC will remain set 39 # it should only be needed after the initial set 40 # if you've removed the coincell battery 41 set_clock = False 42 43 if set_clock: 44 # year, mon, date, hour, min, sec, wday, yday, isdst 45 t = time.struct_time((2021, 10, 31, 00, 00, 00, 0, -1, -1)) 46 47 print("Setting time to:", t) 48 rtc.datetime = t 49 print() 50 51 # variable to hold RTC datetime 52 t = rtc.datetime 53 54 time.sleep(1) 55 56 # initial write to the SD card on startup 57 try: 58 with open("/sd/co2.txt", "a") as f: 59 # writes the date 60 f.write('The date is {} {}/{}/{}\n'.format(days[t.tm_wday], t.tm_mday, t.tm_mon, t.tm_year)) 61 # writes the start time 62 f.write('Start time: {}:{}:{}\n'.format(t.tm_hour, t.tm_min, t.tm_sec)) 63 # headers for data, comma-delimited 64 f.write('CO2,Time\n') 65 # debug statement for REPL 66 print("initial write to SD card complete, starting to log") 67 except ValueError: 68 print("initial write to SD card failed - check card") 69 70 while True: 71 try: 72 # variable for RTC datetime 73 t = rtc.datetime 74 # append SD card text file 75 with open("/sd/co2.txt", "a") as f: 76 # read co2 data from SCD40 77 co2 = scd4x.CO2 78 # write co2 data followed by the time, comma-delimited 79 f.write('{},{}:{}:{}\n'.format(co2, t.tm_hour, t.tm_min, t.tm_sec)) 80 print("data written to sd card") 81 # repeat every 30 seconds 82 time.sleep(30) 83 except ValueError: 84 print("data error - cannot write to SD card") 85 time.sleep(10)