/ examples / adafruit_io_http / adafruit_io_analog_in.py
adafruit_io_analog_in.py
 1  """
 2  Example of reading an analog light sensor
 3  and sending the value to Adafruit IO
 4  """
 5  import time
 6  import board
 7  import busio
 8  from digitalio import DigitalInOut
 9  from analogio import AnalogIn
10  from adafruit_esp32spi import adafruit_esp32spi, adafruit_esp32spi_wifimanager
11  
12  # Import NeoPixel Library
13  import neopixel
14  
15  # Import Adafruit IO HTTP Client
16  from adafruit_io.adafruit_io import IO_HTTP, AdafruitIO_RequestError
17  
18  # Delay between polling and sending light sensor data, in seconds
19  SENSOR_DELAY = 30
20  
21  # Get wifi details and more from a secrets.py file
22  try:
23      from secrets import secrets
24  except ImportError:
25      print("WiFi secrets are kept in secrets.py, please add them there!")
26      raise
27  
28  # ESP32 Setup
29  try:
30      esp32_cs = DigitalInOut(board.ESP_CS)
31      esp32_ready = DigitalInOut(board.ESP_BUSY)
32      esp32_reset = DigitalInOut(board.ESP_RESET)
33  except AttributeError:
34      esp32_cs = DigitalInOut(board.D9)
35      esp32_ready = DigitalInOut(board.D10)
36      esp32_reset = DigitalInOut(board.D5)
37  
38  spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
39  esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)
40  status_light = neopixel.NeoPixel(
41      board.NEOPIXEL, 1, brightness=0.2
42  )  # Uncomment for Most Boards
43  """Uncomment below for ItsyBitsy M4"""
44  # status_light = dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1, brightness=0.2)
45  wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(esp, secrets, status_light)
46  
47  # Set your Adafruit IO Username and Key in secrets.py
48  # (visit io.adafruit.com if you need to create an account,
49  # or if you need your Adafruit IO key.)
50  aio_username = secrets["aio_username"]
51  aio_key = secrets["aio_key"]
52  
53  # Create an instance of the Adafruit IO HTTP client
54  io = IO_HTTP(aio_username, aio_key, wifi)
55  
56  try:
57      # Get the 'light' feed from Adafruit IO
58      light_feed = io.get_feed("light")
59  except AdafruitIO_RequestError:
60      # If no 'light' feed exists, create one
61      light_feed = io.create_new_feed("light")
62  
63  # Set up an analog light sensor on the PyPortal
64  adc = AnalogIn(board.LIGHT)
65  
66  while True:
67      light_value = adc.value
68      print("Light Level: ", light_value)
69      print("Sending to Adafruit IO...")
70      io.send_data(light_feed["key"], light_value)
71      print("Sent!")
72      # delay sending to Adafruit IO
73      time.sleep(SENSOR_DELAY)