code.py
 1  # SPDX-FileCopyrightText: 2022 Kattni Rembor for Adafruit Industries
 2  # SPDX-License-Identifier: MIT
 3  """
 4  CircuitPython Essentials Storage CP Filesystem code.py file
 5  
 6  For use with boards with a built-in red LED.
 7  
 8  Logs temperature using MCP9808 temperature sensor.
 9  """
10  import time
11  import board
12  import digitalio
13  import adafruit_mcp9808
14  
15  led = digitalio.DigitalInOut(board.LED)
16  led.switch_to_output()
17  
18  # For connecting MCP9808 via STEMMA QT
19  mcp9808 = adafruit_mcp9808.MCP9808(board.STEMMA_I2C())
20  
21  # For connecting MCP9808 via pins and breadboard
22  # mcp9808 = adafruit_mcp9808.MCP9808(board.I2C())
23  
24  try:
25      with open("/temperature.txt", "a") as temp_log:
26          while True:
27              # The temperature in Celsius. Include the
28              # math to do the C to F conversion here, if desired.
29              temperature = mcp9808.temperature
30  
31              # Write the temperature to the temperature.txt file every 10 seconds.
32              temp_log.write('{0:.2f}\n'.format(temperature))
33              temp_log.flush()
34  
35              # Blink the LED on every write...
36              led.value = True
37              time.sleep(1)  # ...for one second.
38              led.value = False  # Then turn it off...
39              time.sleep(9)  # ...for the other 9 seconds.
40  
41  except OSError as e:  # When the filesystem is NOT writable by CircuitPython...
42      delay = 0.5  # ...blink the LED every half second.
43      if e.args[0] == 28:  # If the file system is full...
44          delay = 0.15  # ...blink the LED every 0.15 seconds!
45      while True:
46          led.value = not led.value
47          time.sleep(delay)