def __init__(self): self.sensor = adafruit_ahtx0.AHTx0(board.I2C())
import time import board from adafruit_motorkit import MotorKit kit = MotorKit(i2c=board.I2C()) kit.motor1.throttle = 0 while True: print("Forward!") kit.motor1.throttle = 0.5 time.sleep(1) print("Speed up...") for i in range(0, 101): speed = i * 0.01 kit.motor1.throttle = speed time.sleep(0.01) print("Slow down...") for i in range(100, -1, -1): speed = i * 0.01 kit.motor1.throttle = speed time.sleep(0.01) print("Backward!") kit.motor1.throttle = -0.5 time.sleep(1) print("Speed up...") for i in range(0, -101, -1):
# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries # SPDX-License-Identifier: MIT # Display inclination data five times per second # See this page to learn the math and physics principals behind this example: # https://learn.adafruit.com/how-tall-is-it/gravity-and-acceleration import time from math import atan2, degrees import board import adafruit_mpu6050 i2c = board.I2C() # uses board.SCL and board.SDA sensor = adafruit_mpu6050.MPU6050(i2c) # Given a point (x, y) return the angle of that point relative to x axis. # Returns: angle in degrees def vector_2_degrees(x, y): angle = degrees(atan2(y, x)) if angle < 0: angle += 360 return angle # Given an accelerometer sensor object return the inclination angles of X/Z and Y/Z # Returns: tuple containing the two angles in degrees
# SPDX-FileCopyrightText: 2020 Carter Nelson for Adafruit Industries # # SPDX-License-Identifier: MIT import time import board import adafruit_lsm6ds.lsm6ds33 from adafruit_ht16k33 import matrix import matrixsand DELAY = 0.00 # add some delay if you want # the accelo accelo = adafruit_lsm6ds.lsm6ds33.LSM6DS33(board.I2C()) # the matrix matrix = matrix.Matrix8x8(board.I2C(), 0x70) # the sand sand = matrixsand.MatrixSand(8, 8) # simple helper def update_matrix(): for x in range(8): for y in range(8): matrix[x, y] = sand[x, y] # add some initial sand for sx in range(4):
import time import board import displayio from adafruit_clue import clue from simpleio import map_range from adafruit_bitmap_font import bitmap_font from adafruit_lsm6ds.lsm6ds33 import LSM6DS33 from adafruit_lsm6ds import Rate, AccelRange from adafruit_progressbar.progressbar import ProgressBar from adafruit_display_text.label import Label # turns off onboard NeoPixel to conserve battery clue.pixel.brightness = (0.0) # accessing the Clue's accelerometer sensor = LSM6DS33(board.I2C()) # step goal step_goal = 10000 # onboard button states a_state = False b_state = False # array to adjust screen brightness bright_level = [0, 0.5, 1] countdown = 0 # variable for the step goal progress bar clock = 0 # variable used to keep track of time for the steps per hour counter clock_count = 0 # holds the number of hours that the step counter has been running clock_check = 0 # holds the result of the clock divided by 3600 seconds (1 hour)
def __init__(self, i2c=None): if i2c is None: i2c = board.I2C() self._ina219 = adafruit_ina219.INA219(i2c)
def __init__(self, address=0x70, i2c=None): super().__init__() if i2c is None: i2c = board.I2C() self._segments = segments.Seg7x4(i2c, address) self._segments.auto_write = False
# cedargrove_pypanel.py # Cedar Grove Studios 2019-12-15 v02 # uses revised adafruit_pybadger and adafruit_crickit # configuration dictionary is contained in 'pypanel_device.py' import board i2c = board.I2C() # establish i2C instance for Stemma devices # Enumerate Stemma/I2C-connected devices stemma = [] # clear the list try: from pypanel_device import catalog except: raise RuntimeError("pypanel_device.py file error") for device in catalog.keys(): try: exec(catalog[device]['import']) exec(catalog[device]['instance']) exec(catalog[device]['test']) stemma.append((device, catalog[device]['name'], catalog[device]['desc'])) except: pass # establish PyBadger instance from adafruit_pybadger import PyBadger panel = PyBadger(pixels_brightness=0.01) # look for PyGamer's joystick if hasattr(board, "JOYSTICK_X"):
import time import ssl import json import alarm import board import socketpool import wifi import adafruit_minimqtt.adafruit_minimqtt as MQTT import adafruit_shtc3 PUBLISH_DELAY = 60 MQTT_TOPIC = "state/temp-sensor" USE_DEEP_SLEEP = True # Connect to the Sensor sht = adafruit_shtc3.SHTC3(board.I2C()) # Add a secrets.py to your filesystem that has a dictionary called secrets with "ssid" and # "password" keys with your WiFi credentials. DO NOT share that file or commit it into Git or other # source control. # pylint: disable=no-name-in-module,wrong-import-order try: from secrets import secrets except ImportError: print("WiFi secrets are kept in secrets.py, please add them there!") raise wifi.radio.connect(secrets["ssid"], secrets["password"]) print("Connected to %s!" % secrets["ssid"]) # Create a socket pool
import random import board import displayio import adafruit_lis3dh splash = displayio.Group() board.DISPLAY.show(splash) SENSITIVITY = 5 # reading in Z direction to trigger, adjustable images = list(filter(lambda x: x.endswith("bmp"), os.listdir("/"))) i = random.randint(0, (len(images)-1)) # initial image is randomly selected # Set up accelerometer on I2C bus, 4G range: ACCEL = adafruit_lis3dh.LIS3DH_I2C(board.I2C(), address=0x18) ACCEL.range = adafruit_lis3dh.RANGE_4_G while True: shaken = False print("Image load {}".format(images[i])) # CircuitPython 6 & 7 compatible try: f = open(images[i], "rb") odb = displayio.OnDiskBitmap(f) except ValueError: print("Image unsupported {}".format(images[i])) del images[i] continue
"""This example is for Raspberry Pi (Linux) only! It will not work on microcontrollers running CircuitPython!""" import math from PIL import Image import board import adafruit_mlx90640 FILENAME = "mlx.jpg" MINTEMP = 25.0 # low range of the sensor (deg C) MAXTEMP = 45.0 # high range of the sensor (deg C) COLORDEPTH = 1000 # how many color values we can have INTERPOLATE = 10 # scale factor for final image mlx = adafruit_mlx90640.MLX90640(board.I2C()) # the list of colors we can choose from heatmap = ( (0.0, (0, 0, 0)), (0.20, (0, 0, 0.5)), (0.40, (0, 0.5, 0)), (0.60, (0.5, 0, 0)), (0.80, (0.75, 0.75, 0)), (0.90, (1.0, 0.75, 0)), (1.00, (1.0, 1.0, 1.0)), ) colormap = [0] * COLORDEPTH # some utility functions
# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries # SPDX-License-Identifier: MIT """This example uses the LIS3DH accelerometer. Debug_I2C can be used with any I2C device.""" import board import digitalio import adafruit_lis3dh from adafruit_debug_i2c import DebugI2C i2c = DebugI2C(board.I2C()) int1 = digitalio.DigitalInOut(board.ACCELEROMETER_INTERRUPT) accelerometer = adafruit_lis3dh.LIS3DH_I2C(i2c, address=0x19, int1=int1) print(accelerometer.acceleration) for i in range(2): print(accelerometer.acceleration)
def __init__(self): super().__init__(board.I2C(), self.DEVICE_ADDRESS)
Proximity Trinkey MIDI Touch pads switch between CC and Pitch Bend modes Blue LED for CC, Red LED for pitchbend Brightness of LEDs for proximity """ import board import neopixel import touchio import usb_midi import adafruit_midi from adafruit_midi.control_change import ControlChange from adafruit_midi.pitch_bend import PitchBend from adafruit_apds9960.apds9960 import APDS9960 apds = APDS9960(board.I2C()) apds.enable_proximity = True touch1 = touchio.TouchIn(board.TOUCH1) touch2 = touchio.TouchIn(board.TOUCH2) pixels = neopixel.NeoPixel(board.NEOPIXEL, 2) midi = adafruit_midi.MIDI(midi_in=usb_midi.ports[0], in_channel=0, midi_out=usb_midi.ports[1], out_channel=0) CC_NUM = 46 # pick your midi cc number here
import time import board from adafruit_motorkit import MotorKit wheels = MotorKit(i2c=board.I2C()) def turnLeft90(): wheels.motor3.throttle = 0.75 wheels.motor4.throttle = 0.75 time.sleep(1) wheels.motor3.throttle = 0 wheels.motor4.throttle = 0 time.sleep(2) def turnRight90(): wheels.motor3.throttle = -0.75 wheels.motor4.throttle = -0.75 time.sleep(1) wheels.motor3.throttle = 0 wheels.motor4.throttle = 0 time.sleep(2) def goStraight(): wheels.motor3.throttle = 0.75 wheels.motor4.throttle = -0.75 time.sleep(0.5) wheels.motor3.throttle = 0 wheels.motor4.throttle = 0
def __init__(self, i2c_bus=board.I2C(), addr=0x2E): super(TFTShield18, self).__init__(i2c_bus, addr) self.pin_mode(_TFTSHIELD_RESET_PIN, self.OUTPUT) self.pin_mode_bulk(self._button_mask, self.INPUT_PULLUP)
import adafruit_sht31d from adafruit_ble_adafruit.adafruit_service import AdafruitServerAdvertisement from adafruit_ble_adafruit.accelerometer_service import AccelerometerService from adafruit_ble_adafruit.addressable_pixel_service import AddressablePixelService from adafruit_ble_adafruit.barometric_pressure_service import BarometricPressureService from adafruit_ble_adafruit.button_service import ButtonService from adafruit_ble_adafruit.humidity_service import HumidityService from adafruit_ble_adafruit.light_sensor_service import LightSensorService from adafruit_ble_adafruit.microphone_service import MicrophoneService from adafruit_ble_adafruit.temperature_service import TemperatureService from adafruit_ble_adafruit.gyroscope_service import GyroscopeService # Accelerometer and gyro lsm6ds33 = adafruit_lsm6ds.lsm6ds33.LSM6DS33(board.I2C()) # Used for pressure and temperature. bmp280 = adafruit_bmp280.Adafruit_BMP280_I2C(board.I2C()) # Humidity. sht31d = adafruit_sht31d.SHT31D(board.I2C()) # Used only for light sensor apds9960 = adafruit_apds9960.apds9960.APDS9960(board.I2C()) apds9960.enable_color = True mic = audiobusio.PDMIn( board.MICROPHONE_CLOCK, board.MICROPHONE_DATA, sample_rate=16000, bit_depth=16, ) # Create and initialize the available services. accel_svc = AccelerometerService()
class SmokeyController(): __keyboardController = None __smokeyGpio = None __currentSpeed = 0 __i2c = busio.I2C(SCL, SDA) __pca = PCA9685(__i2c) __pca.frequency = 50 __greenArm = None __redArm = None __blueArm = None __currentArm = None __currentlySelectedArm = None __kit = MotorKit(i2c=board.I2C()) __max_angle = 36 __min_angle = 0 __min_speed = 100 def __init__(self, smokeyGpio, exit_condition): self.__keyboardController = KeyboardController(exit_condition) self.__smokeyGpio = smokeyGpio self.__greenArm = SmokeyArm(self.__pca, self.__kit.motor3, 12, servo.Servo(self.__pca.channels[2]), servo.Servo(self.__pca.channels[5]), 30, 0, False, 6) self.__redArm = SmokeyArm(self.__pca, self.__kit.motor2, 22, servo.Servo(self.__pca.channels[1]), None, 30, 0, False, 10) self.__blueArm = SmokeyArm(self.__pca, self.__kit.motor1, 21, servo.Servo(self.__pca.channels[0]), servo.Servo(self.__pca.channels[4]), 30, 0, True) def start(self): done_processing = False input_str = "" while not done_processing: if self.__keyboardController.input_queued(): input_str = self.__keyboardController.input_get() print(input_str + '\n') if input_str.strip() == "quit": done_processing = True elif input_str.strip() == "w": self.go_straight_forwards() # go straight forward elif input_str.strip() == "s": self.go_straight_backwards() # go straight back elif input_str.strip() == "a": # strafe left self.strafe_left() elif input_str.strip() == "d": # strafe right self.strafe_right() elif input_str.strip() == 'q': # diagonal left forward self.diagonal_left_forward() elif input_str.strip() == 'e': # diagonal right forward self.diagonal_right_forward() elif input_str.strip() == 'z': # diagonal right reverse self.diagonal_right_reverse() elif input_str.strip() == 'c': # diagonal left reverse self.diagonal_left_reverse() elif input_str.strip() == 'y': # spin clockwise self.spin_clockwise() elif input_str.strip() == 't': # spin anti-clockwise self.spin_anti_clockwise() elif input_str.strip() == 'r': # select Red Arm self.select_red_arm() elif input_str.strip() == 'g': # select Green Arm self.select_green_arm() elif input_str.strip() == 'b': # select Blue Arm self.select_blue_arm() elif input_str.strip() == 'o': # Release hand if self.__currentArm != None: self.__currentArm.release_hand() elif input_str.strip() == 'p': # Pinch Hand if self.__currentArm != None: self.__currentArm.pinch_hand() elif input_str.strip() == 'l': # Grab Hand if self.__currentArm != None: self.__currentArm.grab_hand() elif input_str.strip() == '\'': # Raise selected arm if self.__currentArm != None: self.__currentArm.raise_arm() elif input_str.strip() == '/': # Lower selected arm if self.__currentArm != None: self.__currentArm.lower_arm() elif input_str.strip() == 'h': # Swing arm inwards if self.__currentArm != None: self.__currentArm.arm_hug() elif input_str.strip() == 'j': # Swing arm outwards if self.__currentArm != None: self.__currentArm.arm_wide() elif input_str == "1": #Calibration mode self.__blueArm.set_mode(1) self.__redArm.set_mode(1) self.__greenArm.set_mode(1) elif input_str == "2": #Challenge mode self.__blueArm.set_mode(2) self.__redArm.set_mode(2) self.__greenArm.set_mode(2) elif input_str == "0": #STOP self.set_speed(0) elif input_str == "`": #STOP and quit self.set_speed(0) done_processing = True self.__keyboardController.clear() def select_blue_arm(self): print("\r\n\ Select CurrentArm: Blue") self.__currentArm = self.__blueArm def select_green_arm(self): self.__currentArm = self.__greenArm def select_red_arm(self): self.__currentArm = self.__redArm def set_speed(self, speed): print("set_speed {}".format(speed)) if (speed < 256 and speed > -255): self.__currentSpeed = speed self.__smokeyGpio.set_speed(self.__currentSpeed) def go_straight_forwards(self): if self.__currentSpeed == 0: # Bot is stopped self.__currentSpeed = self.__min_speed self.__currentSpeed = self.__currentSpeed + 10 self.__smokeyGpio.set_speed_LfLrRfRr(self.__currentSpeed, self.__currentSpeed, self.__currentSpeed, self.__currentSpeed) def go_straight_backwards(self): if self.__currentSpeed == 0: #Bot is stopped self.__currentSpeed = -1 * self.__min_speed self.__currentSpeed = self.__currentSpeed - 10 self.__smokeyGpio.set_speed_LfLrRfRr(self.__currentSpeed, self.__currentSpeed, self.__currentSpeed, self.__currentSpeed) def strafe_right(self): if self.__currentSpeed == 0: # Bot is stopped self.__currentSpeed = self.__min_speed self.__smokeyGpio.set_speed_LfLrRfRr(self.__currentSpeed, -self.__currentSpeed, -self.__currentSpeed, self.__currentSpeed) def strafe_left(self): if self.__currentSpeed == 0: # Bot is stopped self.__currentSpeed = self.__min_speed self.__smokeyGpio.set_speed_LfLrRfRr(-self.__currentSpeed, self.__currentSpeed, self.__currentSpeed, -self.__currentSpeed) def diagonal_left_forward(self): if self.__currentSpeed == 0: # Bot is stopped self.__currentSpeed = self.__min_speed self.__smokeyGpio.set_speed_LfLrRfRr(self.__currentSpeed, 0, 0, self.__currentSpeed) def diagonal_right_forward(self): if self.__currentSpeed == 0: # Bot is stopped self.__currentSpeed = self.__min_speed self.__smokeyGpio.set_speed_LfLrRfRr(0, self.__currentSpeed, self.__currentSpeed, 0) def diagonal_left_reverse(self): if self.__currentSpeed == 0: # Bot is stopped self.__currentSpeed = self.__min_speed self.__smokeyGpio.set_speed_LfLrRfRr(-self.__currentSpeed, 0, 0, -self.__currentSpeed) def diagonal_right_reverse(self): if self.__currentSpeed == 0: # Bot is stopped self.__currentSpeed = self.__min_speed self.__smokeyGpio.set_speed_LfLrRfRr(0, -self.__currentSpeed, -self.__currentSpeed, 0) def spin_clockwise(self): if self.__currentSpeed == 0: # Bot is stopped self.__currentSpeed = self.__min_speed self.__smokeyGpio.set_speed_LfLrRfRr(self.__currentSpeed, self.__currentSpeed, -self.__currentSpeed, -self.__currentSpeed) def spin_anti_clockwise(self): if self.__currentSpeed == 0: # Bot is stopped self.__currentSpeed = self.__min_speed self.__smokeyGpio.set_speed_LfLrRfRr(-self.__currentSpeed, -self.__currentSpeed, self.__currentSpeed, self.__currentSpeed) def dispose(self): self.__pca.deinit()
import board import adafruit_nunchuk from adafruit_hid.mouse import Mouse m = Mouse() nc = adafruit_nunchuk.Nunchuk(board.I2C()) centerX = 128 centerY = 128 scaleX = 0.3 scaleY = 0.3 cDown = False zDown = False #This is to allow double checking (only on left click - and it doesn't really work) CHECK_COUNT = 0 #This is just to show that we're getting back data - uncomment it and hold down the buttons #while True: # print((0 if nc.button_C else 1, 0 if nc.button_Z else 1)) while True: x, y = nc.joystick #Eliminate spurious reads if (x == 255 or y == 255): continue relX = x - centerX relY = centerY - y
tvoc.anchored_position = (5, 235) eco2 = label.Label(data_font, text="eCO2=?????", color=0x000000) eco2.anchor_point = (0, 1) eco2.anchored_position = (130, 235) splash = displayio.Group(max_size=5) splash.append(background) splash.append(mouth) splash.append(message) splash.append(tvoc) splash.append(eco2) clue.display.show(splash) # setup SGP30 and wait for initial warm up sgp30 = adafruit_sgp30.Adafruit_SGP30(board.I2C()) time.sleep(15) # loop forever while True: eCO2, TVOC = sgp30.iaq_measure() tvoc.text = "TVOC={:5d}".format(TVOC) eco2.text = "eCO2={:5d}".format(eCO2) level = 0 for thresh in TVOC_LEVELS: if TVOC <= thresh: break level += 1
speaker_enable = digitalio.DigitalInOut(board.SPEAKER_ENABLE) speaker_enable.direction = digitalio.Direction.OUTPUT speaker_enable.value = True except AttributeError: pass AUDIO = audioio.AudioOut(board.SPEAKER) # Speaker board.DISPLAY.auto_brightness = False TOUCH1 = touchio.TouchIn(board.TOUCH1) # Capacitive touch pads TOUCH2 = touchio.TouchIn(board.TOUCH2) TOUCH3 = touchio.TouchIn(board.TOUCH3) TOUCH4 = touchio.TouchIn(board.TOUCH4) # Set up accelerometer on I2C bus, 4G range: I2C = board.I2C() if IS_HALLOWING_M4: import adafruit_msa301 ACCEL = adafruit_msa301.MSA301(I2C) else: import adafruit_lis3dh try: ACCEL = adafruit_lis3dh.LIS3DH_I2C(I2C, address=0x18) # Production board except ValueError: ACCEL = adafruit_lis3dh.LIS3DH_I2C(I2C, address=0x19) # Beta hardware ACCEL.range = adafruit_lis3dh.RANGE_4_G try: board.DISPLAY.brightness = 0 SCREEN = displayio.Group()
class ht16k33_clock: """ Object for interacting with ht16k33 board controlled 7x4 clock display """ # setup clock display # variables are the same for every instance setup, so not inside __init__ display = Seg7x4(board.I2C()) display.brightness = 0.4 # setup display variables time_display: Optional[str] = None def display_time(self, train_times: List[datetime.datetime], min_clock_display=0): """ Finds the time difference between the first train and now, then displays it on the clock display """ # set the countdown display time self.clock_countdown_time(train_times, min_clock_display) # If a time is not None, display if self.time_display is not None: self.display.print(self.time_display) # Else clear the clock else: self.clear_clock() def clock_countdown_time(self, train_times: List[datetime.datetime], min_clock_display: int): """ Takes in the train departure times and finds the difference between the soonest departure and now. Aslo has a minimum difference varaible so that if it takes a certain amount of time to walk to station, to account for that and only display a countdown that is achievable to walk to. :train_times: list of train departure times :min_clock_display: the minimum difference to display in minutes :return: Either the display countdown time or None if there isn't one within 99 minutes, the display limit """ # Retrieve current time to compare now = datetime.datetime.now() # Get the difference between the soonest train and now train_num = 0 next_train = train_times[train_num] - now # get seconds for the display next_train_seconds = str(next_train.seconds % 60) # make sure it is 0 padded if len(next_train_seconds) == 1: next_train_seconds = f"0{next_train_seconds}" # get the minutes for the display next_train_minutes = next_train.seconds / 60 # While the difference is less than the minimum, use the next train/bus while (next_train_minutes < min_clock_display) and train_num < len(train_times): train_num += 1 next_train = train_times[train_num] - now next_train_minutes = next_train.seconds / 60 next_train_minutes_str = str(int(next_train_minutes)) # make sure it is 0 padded if len(next_train_minutes_str) == 1: next_train_minutes_str = f"0{next_train_minutes}" # If minutes are not a length of 3 (too large for display) if len(next_train_minutes_str) == 2 and (next_train_minutes) > min_clock_display: # Change the display time self.time_display = f"{next_train_minutes}:{next_train_seconds}" # Else time display is None else: self.time_display = None def clear_clock(self): """ Clears the clock display. Otherwise it stays on, even after the program runs """ # Use I2C connection for clock display i2c = board.I2C() # Create a new display which clears the current display self.display = Seg7x4(i2c)
"""Sample code and test for adafruit_in219""" import time import board from adafruit_ina219 import ADCResolution, BusVoltageRange, INA219 i2c_bus = board.I2C() ina219 = INA219(i2c_bus) print("ina219 test") # display some of the advanced field (just to test) print("Config register:") print(" bus_voltage_range: 0x%1X" % ina219.bus_voltage_range) print(" gain: 0x%1X" % ina219.gain) print(" bus_adc_resolution: 0x%1X" % ina219.bus_adc_resolution) print(" shunt_adc_resolution: 0x%1X" % ina219.shunt_adc_resolution) print(" mode: 0x%1X" % ina219.mode) print("") # optional : change configuration to use 32 samples averaging for both bus voltage and shunt voltage ina219.bus_adc_resolution = ADCResolution.ADCRES_12BIT_32S ina219.shunt_adc_resolution = ADCResolution.ADCRES_12BIT_32S # optional : change voltage range to 16V ina219.bus_voltage_range = BusVoltageRange.RANGE_16V # measure and display loop while True: bus_voltage = ina219.bus_voltage # voltage on V- (load side) shunt_voltage = ina219.shunt_voltage # voltage between V+ and V- across the shunt
red_alert_blink_speed = 0.5 # These are the thresholds the z-axis values must exceed for the orientation to be considered # "up" or "down". These values are valid if the LIS3DH breakout is mounted flat inside the timer # assembly. If you want the option to have the timer on an angle while timing, you can calibrate # these values by uncommenting the print(z) in orientation() to see the z-axis values and update # the thresholds to match the desired range. down_threshold = -8 up_threshold = 8 # Number of LEDs. Default is 32 (2 x rings of 16 each). If you use a different form of NeoPixels, # update this to match the total number of pixels. number_of_pixels = 32 # Set up accelerometer and LEDs. lis3dh = adafruit_lis3dh.LIS3DH_I2C(board.I2C()) pixels = neopixel.NeoPixel(board.A3, number_of_pixels, brightness=led_brightness) pixels.fill(0) # Turn off the LEDs if they're on. STATE_IDLE = "Idle" STATE_TIMING = "Timing" STATE_TIMING_COMPLETE = "Timing complete" RED_ALERT = "Red Alert" def gradient(color_one, color_two, blend_weight): """ Blend between two colors with a given ratio.
# SPDX-FileCopyrightText: 2021 Kattni Rembor for Adafruit Industries # SPDX-License-Identifier: MIT """ Simple seesaw test for ATtiny8x7 breakout using built-in LED on pin 5. """ import time import board from adafruit_seesaw.seesaw import Seesaw ss = Seesaw(board.I2C()) ss.pin_mode(5, ss.OUTPUT) while True: ss.digital_write( 5, False) # Turn the LED on (the built-in LED is active low!) time.sleep(1) # Wait for one second ss.digital_write(5, True) # Turn the LED off time.sleep(1) # Wait for one second
simulation using accelerometer and math. This uses only the rings, not the matrix portion. Adapted from Bill Earl's STEAM-Punk Goggles project: https://learn.adafruit.com/steam-punk-goggles """ import math import random import board import supervisor import adafruit_lis3dh import adafruit_is31fl3741 from adafruit_is31fl3741.adafruit_ledglasses import LED_Glasses # HARDWARE SETUP ---- i2c = board.I2C() # Shared by both the accelerometer and LED controller # Initialize the accelerometer lis3dh = adafruit_lis3dh.LIS3DH_I2C(i2c) # Initialize the IS31 LED driver, buffered for smoother animation glasses = LED_Glasses(i2c, allocate=adafruit_is31fl3741.MUST_BUFFER) # PHYSICS SETUP ----- class Pendulum: """A small class for our pendulum simulation.""" def __init__(self, ring, color): """Initial pendulum position, plus axle friction, are randomized so the two rings don't spin in perfect lockstep."""
import time import board import adafruit_ahtx0 # Create the sensor object using I2C sensor = adafruit_ahtx0.AHTx0(board.I2C()) while True: print("\nTemperature: %0.1f C" % sensor.temperature) print("Humidity: %0.1f %%" % sensor.relative_humidity) time.sleep(2)
# Duration of sleep in seconds. Default is 600 seconds (10 minutes). # Feather will sleep for this duration between sensor readings / sending data to AdafruitIO sleep_duration = 600 # Update to match the mAh of your battery for more accurate readings. # Can be MAH100, MAH200, MAH400, MAH500, MAH1000, MAH2000, MAH3000. # Choose the closest match. Include "PackSize." before it, as shown. battery_pack_size = PackSize.MAH400 # Setup the little red LED led = digitalio.DigitalInOut(board.LED) led.switch_to_output() # Set up the LC709203 sensor battery_monitor = LC709203F(board.I2C()) battery_monitor.pack_size = battery_pack_size # Collect the sensor data values and format the data battery_voltage = "{:.2f}".format(battery_monitor.cell_voltage) battery_percent = "{:.1f}".format(battery_monitor.cell_percent) def go_to_sleep(sleep_period): # Create a an alarm that will trigger sleep_period number of seconds from now. time_alarm = alarm.time.TimeAlarm(monotonic_time=time.monotonic() + sleep_period) # Exit and deep sleep until the alarm wakes us. alarm.exit_and_deep_sleep_until_alarms(time_alarm)
import board import digitalio from PIL import Image, ImageDraw, ImageFont import adafruit_ssd1306 # Define the Reset Pin oled_reset = digitalio.DigitalInOut(board.D4) # Change these # to the right size for your display! WIDTH = 128 HEIGHT = 32 # Change to 64 if needed BORDER = 5 # Use for I2C. i2c = board.I2C() oled = adafruit_ssd1306.SSD1306_I2C(WIDTH, HEIGHT, i2c, addr=0x3c, reset=oled_reset) # Use for SPI #spi = board.SPI() #oled_cs = digitalio.DigitalInOut(board.D5) #oled_dc = digitalio.DigitalInOut(board.D6) #oled = adafruit_ssd1306.SSD1306_SPI(WIDTH, HEIGHT, spi, oled_dc, oled_reset, oled_cs) # Clear display. oled.fill(0) oled.show() # Create blank image for drawing. # Make sure to create image with mode '1' for 1-bit color. image = Image.new('1', (oled.width, oled.height))
import bme280 import datetime import time import pymysql.cursors import signal import board import busio import adafruit_ads1x15.ads1115 as ADS from adafruit_ads1x15.analog_in import AnalogIn import adafruit_bme280 i2c = busio.I2C(board.SCL,board.SDA) bme280 = adafruit_bme280.Adafruit_BME280_I2C(board.I2C(),address = 0x76) ADS0 = ADS.ADS1115(i2c,gain = 1,address = 0x48) ADS1 = ADS.ADS1115(i2c,gain = 1,address = 0x49) ch0_10 = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] connection = pymysql.connect( user = "******", passwd = "minoru0869553434", # host = "localhost", # host = "192.168.1.104", host = "127.0.0.1", db = "IoT_TEST", charset = "utf8mb4", ) def getData(arg1,args2): #EnvData = bme280.sample(bus, BMP280address,BMP280calibration_params)