# 3)Ctrl+X to exit, save changes, and reboot! #----------------------------------------------------------------------------------------------------- #Acceleration/Gyro Sensor : adafruit LSM6DSOX #RTC Module : adafruit DS3231 #----------------------------------------------------------------------------------------------------- #Coded by : Nicholas P. Shay, Mechanical Engineering 2022, [email protected] #Date : 12/5/2020 #----------------------------------------------------------------------------------------------------- import time #Library for debugging and buffering import csv #Library to write data into csv file import board #Library for CircuitPi to get board info import busio #Library for CircuitPi bus communication from adafruit_lsm6ds.lsm6dsox import LSM6DSOX #Library for CircuitPi accel/gyrosensor import adafruit_ds3231 #Library for CircuitPi RTC i2c = busio.I2C(board.SCL, board.SDA) #Define i2c connection with circuitPi busio sox = LSM6DSOX(i2c) #Define acceleration sensor for data ds3231 = adafruit_ds3231.DS3231(i2c) #Define RTC module for timing with open('accel_test2.csv', 'w', newline='') as f: #Create .csv file and define writing = csv.writer(f) #Open writing connection with csv file writing.writerow([ 'Time', 'Temperature', '--a_x--', '--a_y--', '--a_z--', '--g_x--', '--g_y--', '--g_z--' ]) #Write Headers to each column t = time.struct_time((2020, 12, 12, 00, 00, 00, 0, -1, -1)) #Set t to zero time for RCT initialization ds3231.datetime = t #Set RTC Clock to 0 hr/min/s before starting data collection #print("Success, time is:",t) #Used for debugging RTC clockset #print() #Used for debugging RTC clockset
from matplotlib import pyplot as plt import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) GPIO.setup(12, GPIO.OUT) p = GPIO.PWM(12, 4) p.start(50.0) # Data collection setup RATE = 250 RATEB = 250 SAMPLES = 1000 # Create the I2C bus with a fast frequency i2c = busio.I2C(board.SCL, board.SDA, frequency=1000000) # Create the ADC object using the I2C bus ads1015 = ADS0.ADS1015(i2c) ads1115 = ADS1.ADS1115(i2c, address=0x4a) # Create single-ended input on channel 0 chan0 = AnalogIn(ads1015, ADS0.P0) chan1 = AnalogIn(ads1015, ADS0.P1) chan2 = AnalogIn(ads1015, ADS0.P2) chan3 = AnalogIn(ads1015, ADS0.P3) chanB0 = AnalogIn(ads1115, ADS1.P0) chanB1 = AnalogIn(ads1115, ADS1.P1) chanB2 = AnalogIn(ads1115, ADS1.P2)
def run_test(pins, sda_pin=SDA_PIN_NAME, scl_pin=SCL_PIN_NAME): """ Performs random writes and reads to I2C EEPROM. :param list[str] pins: list of pins to run the test on :param str sda_pin: pin name of I2C SDA :param str scl_pin: pin name of I2C SCL :return: tuple(str, list[str]): test result followed by list of pins tested """ # Write values to I2C EEPROM and verify the values match if list(set(pins).intersection(set([sda_pin, scl_pin]))): # Tell user to connect EEPROM chip print("Connect a Microchip AT24HC04B EEPROM I2C chip. " + "Press enter to continue.") input() # Set up I2C i2c = busio.I2C(getattr(board, scl_pin), getattr(board, sda_pin)) # Wait for I2C lock while not i2c.try_lock(): pass # Pick a random address, write to it, read from it, and see if they match pass_test = True for _ in range(NUM_I2C_TESTS): # Randomly pick an address and a data value (one byte) mem_addr = random.randint(0, EEPROM_I2C_MAX_ADDR) mem_data = random.randint(0, 255) print("Address:\t" + hex(mem_addr)) print("Writing:\t" + hex(mem_data)) # Try writing this random value to the random address result = _eeprom_i2c_write_byte(i2c, EEPROM_I2C_ADDR, mem_addr, mem_data) if not result: print("FAIL: I2C could not communicate") pass_test = False break # Try reading the written value back from EEPROM result = _eeprom_i2c_read_byte(i2c, EEPROM_I2C_ADDR, mem_addr) print("Read:\t\t" + hex(result[1][0])) print() if not result[0]: print("FAIL: I2C could not communicate") pass_test = False break # Compare the read value to the original value if result[1][0] != mem_data: print("FAIL: Data does not match") pass_test = False break # Release I2C pins i2c.deinit() # Store results if pass_test: return PASS, [sda_pin, scl_pin] return FAIL, [sda_pin, scl_pin] # Else (no pins found) print("No I2C pins found") return NA, []
def pHECT(): global temperature global pH global EC global TDS global S global SG global pHVar global ECVar GPIO.setmode(GPIO.BCM) while True: now = datetime.now() now = now.strftime("%Y-%m-%d %H:%M:%S") try: pH = Atlas(99, "r") except: pass while pH == "Error 254" or pH == "Error 255" or pH == "?I,pH,1.96": pH = Atlas(99, "r") pH = pH.rstrip('\x00') ECs = Atlas(100, "r") while ECs == "Error 254" or ECs == "Error 255" or ECs == "?I,EC,2.12": ECs = Atlas(100, "r") try: ECs.split(',') Ec, TDS, S, SG = ECs.split(',') EC = float(float(Ec.rstrip('\x00')) / 1.0) TDS = float(float(TDS.rstrip('\x00')) / 1.0) S = float(float(S.rstrip('\x00')) * 1000) SG = float(float(SG.rstrip('\x00')) / 1.0) except: pass #ECs == "Error 254" i2c = busio.I2C(board.SCL, board.SDA) sht = adafruit_shtc3.SHTC3(i2c) temperature, rh = sht.measurements if temperature > 26: if not GPIO.input(20): GPIO.output(20, GPIO.HIGH) LogString = "Fan: temperature: " + str( temperature) + "C, RH: " + str(rh) + "%, Fan STARTED" LogString = str(LogString) syslog.syslog(syslog.LOG_INFO, LogString) elif temperature < 25: if GPIO.input(20): GPIO.output(20, GPIO.LOW) LogString = "Fan: temperature: " + str( temperature) + "C, RH: " + str(rh) + "%, Fan STOPPED" LogString = str(LogString) syslog.syslog(syslog.LOG_INFO, LogString) last = dbRead('H2O') LDate = last[0] date = datetime.now() SinceLast = date - LDate SinceLastSec = SinceLast.seconds if SinceLastSec > 5: Farm = mysql.connector.connect(host="192.168.1.14", user="******", passwd="a-51d41e", database="Farm") H2O = Farm.cursor() sql = "INSERT INTO Farm.H2O (date,temp,RH,pH,EC,TDS,S,SG) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)" val = (now, temperature, rh, pH, Ec, TDS, S, SG) H2O.execute(sql, val) H2O.close Farm.commit() Farm.close LogString = str("pHECT: temperature: ") + str(temperature) + str( " ,RH: ") + str(rh) + str("% ,pH: ") + str(pH) + " ,EC: " + str( EC) + " ,TDS: " + str(TDS) + " ,S: " + str(S) + " ,SG: " + str( SG) LogString = str(LogString) syslog.syslog(syslog.LOG_INFO, LogString) time.sleep(25)
from board import SCL, SDA import busio # Import the PCA9685 module. from adafruit_pca9685 import PCA9685 # This example also relies on the Adafruit motor library available here: # https://github.com/adafruit/Adafruit_CircuitPython_Motor from adafruit_motor import servo i2c = busio.I2C(SCL, SDA) # Create a simple PCA9685 class instance. pca = PCA9685(i2c) pca.frequency = 50 # To get the full range of the servo you will likely need to adjust the min_pulse and max_pulse to # match the stall points of the servo. # This is an example for the Sub-micro servo: https://www.adafruit.com/product/2201 # servo7 = servo.Servo(pca.channels[7], min_pulse=580, max_pulse=2480) # This is an example for the Micro Servo - High Powered, High Torque Metal Gear: # https://www.adafruit.com/product/2307 # servo7 = servo.Servo(pca.channels[7], min_pulse=600, max_pulse=2400) # This is an example for the Standard servo - TowerPro SG-5010 - 5010: # https://www.adafruit.com/product/155 # servo7 = servo.Servo(pca.channels[7], min_pulse=600, max_pulse=2500) # This is an example for the Analog Feedback Servo: https://www.adafruit.com/product/1404 # servo7 = servo.Servo(pca.channels[7], min_pulse=600, max_pulse=2600) # The pulse range is 1000 - 2000 by default.
In addition, the Crickit FeatherWing always uses seesaw pin #20. In either of those cases, this object will work. .. code-block:: python from adafruit_crickit.crickit import crickit crickit.init_neopixel(24) crickit.neopixel.fill((100, 0, 0)) """ from adafruit_seesaw.neopixel import NeoPixel self._neopixel = NeoPixel(self._seesaw, _NEOPIXEL, n, bpp=bpp, brightness=brightness, auto_write=auto_write, pixel_order=pixel_order) def reset(self): """Reset the whole Crickit board.""" self._seesaw.sw_reset() crickit = None # pylint: disable=invalid-name """A singleton instance to control a single Crickit board, controlled by the default I2C pins.""" # Sphinx's board is missing real pins so skip the constructor in that case. if "SCL" in dir(board): crickit = Crickit(Seesaw(busio.I2C(board.SCL, board.SDA))) # pylint: disable=invalid-name
def I2C(): """The singleton I2C interface""" import busio return busio.I2C(SCL, SDA)
from PyQt5 import QtCore from PyQt5.QtCore import Qt import threading #쓰레드 라이브러리입니다. import numpy as np import pytesseract #OCR 파이테서렉트 라이브러리입니다. from time import sleep #프로그램 딜레이 함수입니다. import busio #i2c핀 참조 라이브러리입니다. #서보모터 드라이버, 서보모터 제어 라이브러리입니다. from adafruit_pca9685 import PCA9685 from adafruit_motor import servo i2c = busio.I2C(3, 2) #서보모터 드라이버의 SCL, SDA핀을 참조하여 i2c 핀을 설정합니다. pca = PCA9685(i2c) #서보모터 드라이버의 i2c핀을 지정해줍니다. pca.frequency = 50 #서보모터 PWM 주파수 설정합니다. #서보모터 드라이버 0번 핀에 500~2500펄스의 범위로 각도를 제어하는 서보로 지정 servo0 = servo.Servo(pca.channels[0], min_pulse=500, max_pulse=2500) servo0.angle = 10 # 초기 서보모터 각도입니다. def img_to_chars(): print("Thread Running") global img_result global return_result_chars while True: if len(img_result) != 0: longest_idx, longest_text = -1, 0 plate_chars = []
gc.collect() import adafruit_bmp280 gc.collect() #import gfx #gc.collect() # needed? #import framebuf #gc.collect()0 import pulseio gc.collect() # debug mode debug = False # init I2c on board i2c = io.I2C(board.SCL, board.SDA) gc.collect() ## BMP280 ## sensor = adafruit_bmp280.Adafruit_BMP280_I2C(i2c) gc.collect() ## OLED/ssd1306 ## oled = adafruit_ssd1306.SSD1306_I2C(128, 32, i2c, addr=0x3c) gc.collect() ## Piezo # tones to play TONE_FREQ = [ 262, # C4 294, # D4 330, # E4
# Importing libraries used to program this script from gpiozero import RGBLED, Button from time import sleep, time from cell import Cell # Initializing RPI board and I2C ports import board import busio import adafruit_tcs34725 # RGB Sensor Library import adafruit_tca9548a # Multiplexer Library i2c = busio.I2C(board.SCL, board.SDA) # Initiate I2C object mpx = adafruit_tca9548a.TCA9548A(i2c) # multiplexer object # Specify which channels on the TCA9548A multiplexer are being used mpx_channels = [3, 4, 5] sensor_array = [] for mpx_channel in mpx_channels: sensor_array.append(adafruit_tcs34725.TCS34725(mpx[mpx_channel])) # Specifying RGB Pins using GPIO# # RGB PIN EQUIVALENT led1 = RGBLED(5, 6, 13) # RGB LED1 PINS: RED PIN 29, GREEN PIN 31, BLUE PIN 33 led2 = RGBLED(19, 26, 12) # RGB LED2 PINS: RED PIN 35, GREEN PIN 37, BLUE PIN 32 led3 = RGBLED(16, 20, 21) # RGB LED3 PINS: RED PIN 36, GREEN PIN 38, BLUE PIN 40 ledArray = [led1, led2, led3] # Toggle Switch button = Button(4)
def connect(self): i2c = busio.I2C(board.SCL, board.SDA) tsl = adafruit_tsl2561.TSL2561(i2c) return tsl
import board import busio import adafruit_vl53l0x import simpleio import neopixel #not enough memory available to load the whole cp library, so we only load the neopixel part of it import adafruit_fancyled.adafruit_fancyled as fancy #initialize the neopixels without using the cp library pixels = neopixel.NeoPixel(board.NEOPIXEL, 10, brightness=.05, auto_write=False) pixels.fill((0, 0, 0)) pixels.show() i2c_bus_offboard = busio.I2C(board.SCL, board.SDA) rangefinder = adafruit_vl53l0x.VL53L0X(i2c_bus_offboard) color_RGB = (0, 0, 255) while True: distance_mm = rangefinder.range if distance_mm > 1000: #the rangefinder isn't reliable at values greater than around 1000mmm distance_mm = 1000 #so rather than have it jump to 8000mm, cap the value at 1000. print(distance_mm) #set up the ranges for remapping distance_mm_minimum = 100 distance_mm_maximum = 600 hue_minimum = 0.0
def main(): """Abstract main() into a function. Normally exits after execution. A function abstracting the main code in the module, which allows it to be used for libraries as well as testing (i.e., it can be called as a script for testing or imported as a library, without modification). """ # Create the I2C interface. i2c = busio.I2C(SCL, SDA) cs_pin = digitalio.DigitalInOut(board.CE0) dc_pin = digitalio.DigitalInOut(board.D25) reset_pin = None BAUDRATE = 6400000 disp = st7789.ST7789( board.SPI(), cs=cs_pin, dc=dc_pin, rst=reset_pin, baudrate=BAUDRATE, width=135, height=240, x_offset=53, y_offset=40, ) height = disp.width width = disp.height image = Image.new("RGB", (width, height)) rotation = 90 # Get drawing object to draw on image. draw = ImageDraw.Draw(image) # Draw a black filled box to clear the image. draw.rectangle((0, 0, width, height), outline=0, fill=(0,0,0)) disp.image(image, rotation) padding = -2 top = padding bottom = height - padding x = 0 font = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", 20) # Create array named difference with size 4 elements all with value 0 difference = [0] * 4 while True: # Draw a black filled box to clear the image. draw.rectangle((0, 0, width, height), outline=0, fill=0) try: oldstats = newstats except: print("[!] Starting i2c device") try: newstats = getStats() except Exception as e: print("[!] Error retrieving stats; website most likely denied request. Reattempting in 60 seconds") time.sleep(60) try: newstats = getStats() except Exception as e: print("[!] Error retrieving second time; waiting 2m50s then running again") time.sleep(150) continue try: difference[0] += (int(re.sub("\D", "", newstats[0])) - int(re.sub("\D", "", oldstats[0]))) difference[1] += (int(re.sub("\D", "", newstats[1])) - int(re.sub("\D", "", oldstats[1]))) difference[2] += (int(re.sub("\D", "", newstats[2])) - int(re.sub("\D", "", oldstats[2]))) difference[3] += (int(re.sub("\D", "", newstats[3])) - int(re.sub("\D", "", oldstats[3]))) except Exception as e: print("[!] Variable old stats does not exist yet; most likely first run") try: y = top draw.text((x, y), "US C:" + "{:>7}".format(newstats[0]) + " (+" + str(difference[0]) + ")", font=font, fill="#FFFFFF") y += font.getsize("US")[1] draw.text((x, y), "US D:" + "{:>7}".format(newstats[1]) + " (+" + str(difference[1]) + ")", font=font, fill="#FFFF00") y += font.getsize("US")[1] draw.text((x, y), "WW C:" + "{:>7}".format(newstats[2]) + " (+" + str(difference[2]) + ")", font=font, fill="#00FF00") y += font.getsize("WW")[1] draw.text((x, y), "WW D:" + "{:>7}".format(newstats[3]) + " (+" + str(difference[3]) + ")", font=font, fill="#FF00FF") except Exception as e: print("[!] Error:", e) continue # Display image. disp.image(image, rotation) print("[*] Updated stats at:", datetime.datetime.now()) time.sleep(300)
# CircuitPython Test for Robotics Masters MM1 # # Notes: # This is to be run using CircuitPython 3.1 # import board import digitalio import time import busio servo_pins = [ board.SERVO1, board.SERVO2, board.SERVO3, board.SERVO4, board.SERVO5, board.SERVO6, board.SERVO7, board.SERVO8 ] rc_pins = [board.RCH1, board.RCH2, board.RCH3, board.RCH4] # setup I2C i2c = busio.I2C(board.SCL, board.SDA) i2c_2 = busio.I2C(board.GPS_SCL, board.GPS_SDA) while True: while not i2c_2.try_lock(): pass [print(hex(x)) for x in i2c_2.scan()] i2c_2.unlock() time.sleep(3)
def __init__(self): i2c = busio.I2C(board.SCL, board.SDA, frequency=100000) self.display = segments.BigSeg7x4(i2c, auto_write=False)
# Requires installation of: # adafruit-blinka # sparkfun-circuitpython-serlcd # +5v -> PWR.RAW # GND -> PWR.GND # GPI0 2 -> I2C.DA # GPIO 3 -> I2C.CL # run once to save splash screen for LCD import board import busio from sparkfun_serlcd import Sparkfun_SerLCD_I2C i2c = busio.I2C(1, 0) serlcd = Sparkfun_SerLCD_I2C(i2c) serlcd.set_fast_backlight_rgb(255, 255, 255) serlcd.write(' SHOTS ALARM ') serlcd.save_splash_screen() serlcd.splash_screen(True)
return q, val, p if i == 2: return p, val, t if i == 3: return p, q, val if i == 4: return t, p, val if i == 5: return val, p, q # Will never reach here but it keeps pylint happier return val, val, val # Create the I2C bus on a Pico Explorer Base i2c = busio.I2C(board.GP5, board.GP4) # Set up 5x5 RGB matrix Breakout display = Display(i2c) def test_pixels(r, g, b): # Draw each row from left to right, top to bottom for y in range(0, 5): for x in range(0, 5): display.fill(0) # Clear display display.pixelrgb(x, y, r, g, b) time.sleep(0.05) def test_rows(r, g, b):
# SPDX-FileCopyrightText: 2018 Dan Halbert for Adafruit Industries # # SPDX-License-Identifier: MIT import time import board import busio from adafruit_seesaw.seesaw import Seesaw myI2C = busio.I2C(board.SCL, board.SDA) ss = Seesaw(myI2C) ss.pin_mode(15, ss.OUTPUT) while True: ss.digital_write(15, True) # turn the LED on (True is the voltage level) time.sleep(1) # wait for a second ss.digital_write(15, False) # turn the LED off by making the voltage LOW time.sleep(1)
def main(): # creating i2c instance i2c = io.I2C(board.SCL, board.SDA) # creating sensor object (i2c object, height, width) oled = OledText(i2c, 128, 64) # layout oled.layout = { 1: SmallLine(2, 4, font="FreeSans.ttf", size=12), # title 2: BigLine(5, 20, font="FreeSans.ttf", size=24), # value 3: BigLine(80, 24, font="FreeSans.ttf", size=18), # unit 4: BigLine(74, 20, font="FontAwesomeSolid.ttf", size=10), # degree 5: SmallLine(120, 20, font="FreeSans.ttf", size=8), # exponent 6: SmallLine(2, 50, font="FreeSans.ttf", size=12), # name } oled.text("WCWH BEVO Beacon", 1) while True: # Getting Newest Measurements # --------------------------- # standard m = get_measurements( variables=["CO2", "PM_C_2p5", "Lux", "TVOC", "NO2", "CO", "T_NO2"], units=["ppm", "ug/m", "lux", "ppb", "ppb", "ppm", "C"], names=[ "Carbon Dioxide", "Particulate Matter", "Light Level", "Nitrogen Dioxide", "TVOCs", "Carbon Monoxide", "Temperature" ]) # demo purposes #m = get_measurements(variables=["CO2","PM_C_2p5","PM_C_10","T_NO2","RH_NO2"],units=["ppm","ug/m","ug/m","F","%"],names=["Carbon Dioxide","PM2.5","PM10","Temperature","Relative Humidity"]) # Displaying Measurements # ----------------------- try: for value, unit, name in m: print(f"{name}: {value} {unit}") if name == "Carbon Monoxide": # converting raw CO measurements to ppm value /= 1000 value = round(value, 1) if unit == "F": value = round(1.8 * value + 32, 2) oled.text(f"{value}", 2) # output of measured value oled.text(f"{unit}", 3) # output of the variable if unit in ["C", "F"]: # adding degree symbol for temperature oled.text(f"\uf22d", 4) oled.text(f"", 5) elif unit == "ug/m": # adding exponent for pm oled.text(f"", 4) oled.text(f"3", 5) else: # no output on these "lines" oled.text(f"", 4) oled.text(f"", 5) oled.text(f"{name}", 6) # output of the display name oled.show() time.sleep(3) # holding display for 3 seconds except OSError: oled.clear() oled.text(f"ERROR", 3) time.sleep(3)
#GPS _SENSOR_GPS_BASIC = False try: from dateutil import tz from dateutil import parser _SENSOR_GPS_BASIC = True except: pass _SENSOR_GPS_ADAFRUIT_I2C = False try: if _SENSOR_GPS_BASIC: import board import busio import adafruit_gps _sensor_adafruit_gps = adafruit_gps.GPS_GtopI2C(busio.I2C( board.SCL, board.SDA), debug=False) _SENSOR_GPS_ADAFRUIT_I2C = True except: pass _SENSOR_GPS_GPSD = False try: if _SENSOR_GPS_BASIC and not _SENSOR_GPS_ADAFRUIT_I2C: from gps3 import gps3 #device test _gps_socket = gps3.GPSDSocket() _gps_socket.connect() _gps_socket.close() _SENSOR_GPS_GPSD = True except:
# Simple demo of reading and writing the time for the DS1307 real-time clock. # Change the if False to if True below to set the time, otherwise it will just # print the current date and time every second. Notice also comments to adjust # for working with hardware vs. software I2C. import time import board # For hardware I2C (M0 boards) use this line: import busio as io # Or for software I2C (ESP8266) use this line instead: #import bitbangio as io import adafruit_ds1307 # Change to the appropriate I2C clock & data pins here! i2c_bus = io.I2C(board.SCL, board.SDA) # Create the RTC instance: rtc = adafruit_ds1307.DS1307(i2c_bus) # Lookup table for names of days (nicer printing). days = ("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday") #pylint: disable-msg=bad-whitespace #pylint: disable-msg=using-constant-test if False: # change to True if you want to set the time! # year, mon, date, hour, min, sec, wday, yday, isdst t = time.struct_time((2017, 10, 29, 15, 14, 15, 0, -1, -1)) # you must set year, mon, date, hour, min, sec and weekday # yearday is not supported, isdst can be set but we don't do anything with it at this time
class ShowcaseApp(App): #kivy properties brightness = StringProperty() flo_read = ListProperty([0, 0, 0]) hierarchy_index = ListProperty([]) DNA_result = StringProperty() #config config = configparser.ConfigParser() config.read('config.ini') #brightness =config['BASIC']['brightness'] led_red_on = False led_blue_on = False adc_gain = 1 sample_rate = 8 unit = NumericProperty(1) home_screen = Builder.load_file("./kv/home.kv") #adc_loop = False try: spi = busio.SPI(board.SCK, MOSI=board.MOSI) except: print('>>>>>>>>>>>>>>>spi init failed<<<<<<<<<<<<<<<<<<<') try: leds = adafruit_tlc59711.TLC59711(spi, auto_show=False) leds[0] = (0, 0, 0) leds[1] = (0, 0, 0) leds.show() except: print('>>>>>>>>>>>>>>>led init failed<<<<<<<<<<<<<<<<<<<') try: i2c = busio.I2C(board.SCL, board.SDA) except: print('>>>>>>>>>>>>>>>i2c init failed<<<<<<<<<<<<<<<<<<<') try: ads = ADS.ADS1115(i2c, gain=adc_gain, data_rate=sample_rate, address=0x48) except: print('>>>>>>>>>>>>>>>ads init failed<<<<<<<<<<<<<<<<<<<') try: file = open("/sys/class/backlight/rpi_backlight/brightness", "r") brightness = file.read() file.close() except: print('>>>>>>>>>>>>>>>Brightness init error<<<<<<<<<<<<<<<<<<<<<<<') def build(self): self.root = Builder.load_file('kv/main.kv') self.title = 'Fluorometer' Window.size = (800, 480) #self.go_home() self.hierarchy_index.append('home') print(self.hierarchy_index) #screen = Builder.load_file("./kv/home.kv") self.root.ids.sm.switch_to(self.home_screen, direction='right') self.root.ids.main_label.text = 'Choose an assay' self.root.ids.back_btn.disabled = True def go_home(self): if (len(self.hierarchy_index) == 1) and (self.hierarchy_index[0] == 'home'): return del self.hierarchy_index[:] self.hierarchy_index.append('home') print(self.hierarchy_index) #screen = Builder.load_file("./kv/home.kv") self.root.ids.sm.switch_to(self.home_screen, direction='right') self.root.ids.main_label.text = 'Choose an assay' self.root.ids.back_btn.disabled = True def go_settings(self): if (len(self.hierarchy_index) == 1) and (self.hierarchy_index[0] == 'settings'): return del self.hierarchy_index[:] self.hierarchy_index.append('settings') print(self.hierarchy_index) screen = Builder.load_file("./kv/settings.kv") self.root.ids.sm.switch_to(screen, direction='right') self.root.ids.main_label.text = 'Settings' self.root.ids.back_btn.disabled = True def go_screen(self, screen_name): self.hierarchy_index.append('{0}'.format(screen_name)) print(self.hierarchy_index) #self.previous_screen = self.current_screen #self.current_screen = screen_name screen = self.load_screen(screen_name) #sm = self.root.ids.sm #sm.switch_to(screen, direction='left') self.root.ids.sm.switch_to(screen, direction='left') self.root.ids.main_label.text = '{0}'.format(screen_name) self.root.ids.back_btn.disabled = False def go_previous(self): if len(self.hierarchy_index) == 2: if self.hierarchy_index[0] == 'home': self.go_home() return if self.hierarchy_index[0] == 'settings': self.go_settings() return self.hierarchy_index.pop() previous_name = self.hierarchy_index[-1] print(self.hierarchy_index) #self.previous_screen = self.current_screen #self.current_screen = screen_name screen = self.load_screen(previous_name) #sm = self.root.ids.sm #sm.switch_to(screen, direction='left') self.root.ids.sm.switch_to(screen, direction='right') self.root.ids.main_label.text = '{0}'.format(previous_name) def load_screen(self, screen_name): screen = Builder.load_file("./kv/{0}.kv".format(screen_name)) return screen #-----------------------------Settings--------------------------------- def brightness_control(self, *args): self.brightness = str(int(args[1])) try: file = open("/sys/class/backlight/rpi_backlight/brightness", "w") file.write(self.brightness) file.close() except: print('Brightness error') def blue_led_test(self): try: print("SCK, MOSI:") print(board.SCK) print(board.MOSI) #spi = busio.SPI(board.SCK, MOSI=board.MOSI) #leds = adafruit_tlc59711.TLC59711(self.spi, auto_show=False) if self.led_blue_on: self.leds[0] = (0, 0, 0) self.led_blue_on = False self.leds.show() print('Blue Led off') return else: self.leds[0] = (65535, 65535, 65535) self.led_blue_on = True self.leds.show() print('Blue Led on') return except: print('Blue test false') def red_led_test(self): print("SCK, MOSI:") print(board.SCK) print(board.MOSI) #leds = adafruit_tlc59711.TLC59711(self.spi, auto_show=False) if self.led_red_on: self.leds[1] = (0, 0, 0) self.led_red_on = False self.leds.show() print('Red Led off') return else: self.leds[1] = (65535, 65535, 65535) self.led_red_on = True self.leds.show() print('Red Led on') return def adc_test(self): try: #chan0 = AnalogIn(ads, ADS.P0) chan1 = AnalogIn(self.ads, ADS.P1) chan2 = AnalogIn(self.ads, ADS.P2) chan3 = AnalogIn(self.ads, ADS.P3) #print("{:>5}\t{:>5.3f}".format(chan0.value, chan0.voltage)) while True: #print("channel 01 {:>5}\t{:>5.3f}".format(chan3.value, chan3.voltage)) #print("channel 02 {:>5}\t{:>5.3f}".format(chan2.value, chan2.voltage)) #print("channel 03 {:>5}\t{:>5.3f}".format(chan1.value, chan1.voltage)) #print("----------------") adc01 = chan3.value adc02 = chan2.value adc03 = chan1.value print("{0}, {1}, {2}".format(adc01, adc02, adc03)) time.sleep(0.3) except: print('ADC test begin false') def adc_diff(self): try: chan1 = AnalogIn(self.ads, ADS.P1) chan2 = AnalogIn(self.ads, ADS.P2) chan3 = AnalogIn(self.ads, ADS.P3) adc01 = chan3.value adc02 = chan2.value adc03 = chan1.value print("befor led {:>5}\t{:>5}\t{:>5}".format(adc01, adc02, adc03)) self.leds[0] = (32767, 32767, 32767) self.leds.show() time.sleep(0.5) adc01_af = chan3.value adc02_af = chan2.value adc03_af = chan1.value print("after led {:>5}\t{:>5}\t{:>5}".format( adc01_af, adc02_af, adc03_af)) adc01 = adc01_af - adc01 adc02 = adc02_af - adc02 adc03 = adc03_af - adc03 print("after dif {:>5}\t{:>5}\t{:>5}".format(adc01, adc02, adc03)) print("---------------------------------------") self.leds[0] = (0, 0, 0) self.leds.show() except: print('ADC diff test failed') #-----------------------------Fluorometer--------------------------------- def adc_aver(self): try: chan1sum = 0 chan2sum = 0 chan3sum = 0 chan1 = AnalogIn(self.ads, ADS.P1) chan2 = AnalogIn(self.ads, ADS.P2) chan3 = AnalogIn(self.ads, ADS.P3) for i in range(10): chan1read = chan1.value chan2read = chan2.value chan3read = chan3.value chan1sum = chan1sum + chan1read chan2sum = chan2sum + chan2read chan3sum = chan3sum + chan3read print( str(chan3read) + " " + str(chan2read) + " " + str(chan1read)) print('ADC average: ') print(chan3sum / 10) print(chan2sum / 10) print(chan1sum / 10) self.flo_read[0] = str(chan3sum / 10) self.flo_read[1] = str(chan2sum / 10) self.flo_read[2] = str(chan1sum / 10) except: print('ADC average test failed') def adc_aver_with_led(self): try: self.leds[0] = (32767, 32767, 32767) self.leds.show() time.sleep(0.3) chan1sum = 0 chan2sum = 0 chan3sum = 0 chan1 = AnalogIn(self.ads, ADS.P1) chan2 = AnalogIn(self.ads, ADS.P2) chan3 = AnalogIn(self.ads, ADS.P3) for i in range(10): chan1read = chan1.value chan2read = chan2.value chan3read = chan3.value chan1sum = chan1sum + chan1read chan2sum = chan2sum + chan2read chan3sum = chan3sum + chan3read print( str(chan3read) + " " + str(chan2read) + " " + str(chan1read)) time.sleep(0.3) print("result led always on: ") print( str(chan3sum / 10) + " " + str(chan2sum / 10) + " " + str(chan1sum / 10)) self.leds[0] = (0, 0, 0) self.leds.show() self.flo_read[0] = str(chan3sum / 10) self.flo_read[1] = str(chan2sum / 10) self.flo_read[2] = str(chan1sum / 10) except: print('ADC average led always on failed') def adc_aver_with_blink(self): try: chan1sum = 0 chan2sum = 0 chan3sum = 0 chan1 = AnalogIn(self.ads, ADS.P1) chan2 = AnalogIn(self.ads, ADS.P2) chan3 = AnalogIn(self.ads, ADS.P3) for i in range(10): self.leds[0] = (32767, 32767, 32767) self.leds.show() time.sleep(0.3) chan1read = chan1.value chan2read = chan2.value chan3read = chan3.value chan1sum = chan1sum + chan1read chan2sum = chan2sum + chan2read chan3sum = chan3sum + chan3read print( str(chan3read) + " " + str(chan2read) + " " + str(chan1read)) self.leds[0] = (0, 0, 0) self.leds.show() time.sleep(0.3) print("result blink: ") print( str(chan3sum / 10) + " " + str(chan2sum / 10) + " " + str(chan1sum / 10)) self.flo_read[0] = str(chan3sum / 10) self.flo_read[1] = str(chan2sum / 10) self.flo_read[2] = str(chan1sum / 10) #self.root.ids.flo_read1.text = '{0}'.format(str(chan3sum/10)) #self.root.ids.flo_read2.text = '{0}'.format(str(chan2sum/10)) #self.root.ids.flo_read3.text = '{0}'.format(str(chan1sum/10)) except: print('ADC average blink failed') def read_standard(self): print('read stadndard') fake_read = 400 ShowcaseApp.config['DNA']['v'] = str(fake_read) with open('config.ini', 'w') as configfile: ShowcaseApp.config.write(configfile) def read_tube(self): fake_read = 459.40 k = float(ShowcaseApp.config['DNA']['k']) g = float(ShowcaseApp.config['DNA']['g']) #r = float(ShowcaseApp.config['DNA']['r']) n = float(ShowcaseApp.config['DNA']['n']) v = float(ShowcaseApp.config['DNA']['v']) s = float(ShowcaseApp.config['DNA']['s']) print(v) r = (v - g) * ((pow(s, n) + k) / pow(s, n)) ShowcaseApp.DNA_result = str( pow(k * (fake_read - g) / (r - (fake_read - g)), 1 / n)) #print(ShowcaseApp.DNA_result) self.go_screen('DNA Result')
# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries # SPDX-License-Identifier: MIT import time from board import SCL, SDA import busio from adafruit_neotrellis.neotrellis import NeoTrellis from adafruit_neotrellis.multitrellis import MultiTrellis # create the i2c object for the trellis i2c_bus = busio.I2C(SCL, SDA) """create the trellis. This is for a 2x2 array of NeoTrellis boards for a 2x1 array (2 boards connected left to right) you would use: trelli = [ [NeoTrellis(i2c_bus, False, addr=0x2E), NeoTrellis(i2c_bus, False, addr=0x2F)] ] """ trelli = [ [ NeoTrellis(i2c_bus, False, addr=0x2E), NeoTrellis(i2c_bus, False, addr=0x2F) ], [ NeoTrellis(i2c_bus, False, addr=0x30), NeoTrellis(i2c_bus, False, addr=0x31) ], ]
import busio import adafruit_bmp280 import subprocess import RPi.GPIO as GPIO ################## config LED ################## GPIO.setmode(GPIO.BCM) LED_RED = 17 LED_GREEN = 27 LED_BLUE = 22 GPIO.setup(LED_RED, GPIO.OUT, initial=GPIO.LOW) GPIO.setup(LED_GREEN, GPIO.OUT, initial=GPIO.LOW) GPIO.setup(LED_BLUE, GPIO.OUT, initial=GPIO.LOW) ################## config BMP280 ################## bmp280 = adafruit_bmp280.Adafruit_BMP280_I2C(busio.I2C(board.SCL, board.SDA), 0x76) bmp280.sea_level_pressure = 992 ################## config display ################## device = sh1106(i2c(port=1, address=0x3C), rotate=0) device.clear() ### setup different fonts FA_solid = ImageFont.truetype('/home/pi/Desktop/fonts/fa-solid-900.ttf', 16) text_large = ImageFont.truetype( '/home/pi/Desktop/fonts/coolvetica-condensed-rg.ttf', 48) text_small = ImageFont.truetype( '/home/pi/Desktop/fonts/coolvetica-condensed-rg.ttf', 12) ### Initialize drawing zone (aka entire screen)
v_s = '' for c in msg[val_i + len(val_str):]: if c == ',': break v_s += c v = int(v_s) palette = v write_palette(palette) send_property_changed("palette", str(palette)) # Our keypad + neopixel driver trellis = adafruit_trellis_express.TrellisM4Express(rotation=90) # Our accelerometer i2c = busio.I2C(board.ACCELEROMETER_SCL, board.ACCELEROMETER_SDA) accelerometer = adafruit_adxl34x.ADXL345(i2c) # Input a value 0 to 255 to get a color value. def wheel(palette, pos): if pos < 0 or pos > 255: return (0, 0, 0) if palette == 0: if pos < 85: return (int(pos * 3), int(255 - pos * 3), 0) elif pos < 170: pos -= 85 return (int(255 - pos * 3), 0, int(pos * 3)) else: pos -= 170
# Disable Active Low Reset of I2C MUX GPIO.setup(4, GPIO.OUT) GPIO.output(4, GPIO.HIGH) time.sleep(5) # Using I2C channel 1 I2C1_SDA_PIN = 2 I2C1_SCL_PIN = 3 # For Channel 0 # GPIO 0, Board Pin Numbers 27 # GPIO 1, Board Pin Numbers 28 # Initialize I2C bus. i2c = busio.I2C(I2C1_SCL_PIN, I2C1_SDA_PIN) # default TCA address=0x70 tca = adafruit_tca9548a.TCA9548A(i2c) print("attempting to connect to DAC") # Initialize all 5 MCP4725 at default address=0x60 time.sleep(1) dac1 = adafruit_mcp4725.MCP4725(tca[0], address=0x60) print("connected to MCP on tca[0]") input("Press enter...") time.sleep(1) dac2 = adafruit_mcp4725.MCP4725(tca[1], address=0x60) print("connected to MCP on tca[1]") input("Press enter...") dac3 = adafruit_mcp4725.MCP4725(tca[2], address=0x60) print("connected to MCP on tca[2]")
def __init__(self, report_function): threading.Thread.__init__(self) self.report_function = report_function self.i2c = busio.I2C(board.SCL, board.SDA) self.sensor = adafruit_bme680.Adafruit_BME680_I2C(self.i2c)
def __init__(self): self.i2c = busio.I2C(board.SCL, board.SDA) self.oled = adafruit_ssd1306.SSD1306_I2C(128, 32, self.i2c) self.oled.fill(0) self.oled.show()
# MQTT publishing data (what you see below is merely a rudimentary test script); # important note: a broker (mosquitto) has to be installed on your system as well. import Adafruit_BMP.BMP280 as BMP280 import time import board import busio i2c = busio.I2C(board.SCL, board.SDA) sensor = BMP280.BMP280() import paho.mqtt.client as mqtt def on_connect(client, userdata, flags, rc): print("Connected with result code " + str(rc)) client = mqtt.Client() client.on_connect = on_connect username = "******" password = "******" client.username_pw_set(username, password) # parameters: '"localhost"' MQTT broker; '1883' MQTT TCP-Port; '60' keep alive time in seconds client.connect("localhost", 1883, 60) while True: temperature = sensor.read_temperature() data1 = "{0:0.1f}".format(temperature)
def init_i2c(self): # Define i2c object i2c = busio.I2C(board.SCL, board.SDA) self.ads = ADS.ADS1115(i2c)