code.py
  1  # SPDX-FileCopyrightText: 2021 Kattni Rembor for Adafruit Industries
  2  # SPDX-License-Identifier: MIT
  3  """
  4  CircuitPython Adafruit IO Example for LC709203 Sensor
  5  """
  6  import time
  7  import ssl
  8  import alarm
  9  import board
 10  import digitalio
 11  import wifi
 12  import socketpool
 13  import adafruit_requests
 14  from adafruit_io.adafruit_io import IO_HTTP
 15  from adafruit_lc709203f import LC709203F, PackSize
 16  try:
 17      from secrets import secrets
 18  except ImportError:
 19      print("WiFi and Adafruit IO credentials are kept in secrets.py, please add them there!")
 20      raise
 21  
 22  # Duration of sleep in seconds. Default is 600 seconds (10 minutes).
 23  # Feather will sleep for this duration between sensor readings / sending data to AdafruitIO
 24  sleep_duration = 600
 25  
 26  # Update to match the mAh of your battery for more accurate readings.
 27  # Can be MAH100, MAH200, MAH400, MAH500, MAH1000, MAH2000, MAH3000.
 28  # Choose the closest match. Include "PackSize." before it, as shown.
 29  battery_pack_size = PackSize.MAH400
 30  
 31  # Setup the little red LED
 32  led = digitalio.DigitalInOut(board.LED)
 33  led.switch_to_output()
 34  
 35  # Set up the LC709203 sensor
 36  battery_monitor = LC709203F(board.I2C())
 37  battery_monitor.pack_size = battery_pack_size
 38  
 39  # Collect the sensor data values and format the data
 40  battery_voltage = "{:.2f}".format(battery_monitor.cell_voltage)
 41  battery_percent = "{:.1f}".format(battery_monitor.cell_percent)
 42  
 43  
 44  def go_to_sleep(sleep_period):
 45      # Create a an alarm that will trigger sleep_period number of seconds from now.
 46      time_alarm = alarm.time.TimeAlarm(monotonic_time=time.monotonic() + sleep_period)
 47      # Exit and deep sleep until the alarm wakes us.
 48      alarm.exit_and_deep_sleep_until_alarms(time_alarm)
 49  
 50  
 51  # Send the data. Requires a feed name and a value to send.
 52  def send_io_data(feed, value):
 53      return io.send_data(feed["key"], value)
 54  
 55  
 56  # Wi-Fi connections can have issues! This ensures the code will continue to run.
 57  try:
 58      # Connect to Wi-Fi
 59      wifi.radio.connect(secrets["ssid"], secrets["password"])
 60      print("Connected to {}!".format(secrets["ssid"]))
 61      print("IP:", wifi.radio.ipv4_address)
 62  
 63      pool = socketpool.SocketPool(wifi.radio)
 64      requests = adafruit_requests.Session(pool, ssl.create_default_context())
 65  
 66  # Wi-Fi connectivity fails with error messages, not specific errors, so this except is broad.
 67  except Exception as e:  # pylint: disable=broad-except
 68      print(e)
 69      go_to_sleep(60)
 70  
 71  # Set your Adafruit IO Username and Key in secrets.py
 72  # (visit io.adafruit.com if you need to create an account,
 73  # or if you need your Adafruit IO key.)
 74  aio_username = secrets["aio_username"]
 75  aio_key = secrets["aio_key"]
 76  
 77  # Initialize an Adafruit IO HTTP API object
 78  io = IO_HTTP(aio_username, aio_key, requests)
 79  
 80  # Turn on the LED to indicate data is being sent.
 81  led.value = True
 82  # Print data values to the serial console. Not necessary for Adafruit IO.
 83  print("Current battery voltage: {0} V".format(battery_voltage))
 84  print("Current battery percent: {0} %".format(battery_percent))
 85  
 86  # Adafruit IO sending can run into issues if the network fails!
 87  # This ensures the code will continue to run.
 88  try:
 89      print("Sending data to AdafruitIO...")
 90      # Send data to Adafruit IO
 91      send_io_data(io.create_and_get_feed("battery-voltage"), battery_voltage)
 92      send_io_data(io.create_and_get_feed("battery-percent"), battery_percent)
 93      print("Data sent!")
 94      # Turn off the LED to indicate data sending is complete.
 95      led.value = False
 96  
 97  # Adafruit IO can fail with multiple errors depending on the situation, so this except is broad.
 98  except Exception as e:  # pylint: disable=broad-except
 99      print(e)
100      go_to_sleep(60)
101  
102  go_to_sleep(sleep_duration)