# Write the temperature to the temperature.txt file every 10 seconds.
temp_log.write('{0:.2f}\n'.format(temperature))
temp_log.flush()
# Blink the LED on every write...
led.value = True
time.sleep(1) # ...for one second.
led.value = False # Then turn it off...
time.sleep(9) # ...for the other 9 seconds.
except OSError as e: # When the filesystem is NOT writable by CircuitPython...
delay = 0.5 # ...blink the LED every half second.
if e.args[0] == 28: # If the file system is full...
delay = 0.15 # ...blink the LED every 0.15 seconds!
while True:
led.value = not led.value
time.sleep(delay)
First you import the necessary modules to make them available to your code, and you
set up the LED.
Next you have a try / except block, which is used to handle the three potential
states of the board: read/write, read-only, or filesystem full. The code in the try
block will run if the filesystem is writable by CircuitPython. The code in the except
block will run if the filesystem is read-only to CircuitPython OR if the filesystem is full.
Under the try , you open a temperature.txtī¤log file. If it is the first time, it will create
the file. For all subsequent times, it opens the file and appends data. Inside the loop,
you get the microcontroller temperature value and assign it to a temperature
variable. Then, you write the temperature value to the log file, followed by clearing
the buffer for the next time through the loop. The temperature data is limited to two
decimal points to save space for more data. Finally, you turn the LED on for one
second, and then turn it off for the next nine seconds. Essentially, you blink the LED
for one second every time the temperature is logged to the file which happens every
ten seconds.
Next you except an OSError . An OSError number 30 is raised when trying to
create, open or write to a file on a filesystem that is read-only to CircuitPython. If any
OSError other than 28 is raised (e.g. 30), the delay is set to 0.5 seconds. If the
filesystem fills up, CircuitPython raises OSError number 28. If OSError number 28
is raised, the delay is set to 0.15 seconds. Inside the loop, the LED is turned on for
the duration of the delay , and turned off for the duration of the delay , effectively
blinking the LED at the speed of the delay .
©Adafruit Industries Page 168 of 263