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 that have a built-in NeoPixel or NeoPixels, but no little red LED.
 7  
 8  It will use only one pixel as an indicator, even if there is more than one NeoPixel.
 9  
10  Logs temperature using MCP9808 temperature sensor.
11  """
12  import time
13  import board
14  import neopixel
15  import adafruit_mcp9808
16  
17  pixel = neopixel.NeoPixel(board.NEOPIXEL, 1)
18  
19  # For connecting MCP9808 via STEMMA QT
20  mcp9808 = adafruit_mcp9808.MCP9808(board.STEMMA_I2C())
21  
22  # For connecting MCP9808 via pins and breadboard
23  # mcp9808 = adafruit_mcp9808.MCP9808(board.I2C())
24  
25  try:
26      with open("/temperature.txt", "a") as temp_log:
27          while True:
28              # The temperature in Celsius. Include the
29              # math to do the C to F conversion here, if desired.
30              temperature = mcp9808.temperature
31  
32              # Write the temperature to the temperature.txt file every 10 seconds.
33              temp_log.write('{0:.2f}\n'.format(temperature))
34              temp_log.flush()
35  
36              # Blink the NeoPixel on every write...
37              pixel.fill((255, 0, 0))
38              time.sleep(1)  # ...for one second.
39              pixel.fill((0, 0, 0))  # Then turn it off...
40              time.sleep(9)  # ...for the other 9 seconds.
41  
42  except OSError as e:  # When the filesystem is NOT writable by CircuitPython...
43      delay = 0.5  # ...blink the NeoPixel every half second.
44      if e.args[0] == 28:  # If the file system is full...
45          delay = 0.15  # ...blink the NeoPixel every 0.15 seconds!
46      while True:
47          pixel.fill((255, 0, 0))
48          time.sleep(delay)
49          pixel.fill((0, 0, 0))
50          time.sleep(delay)