bme280.overscan_pressure = adafruit_bme280.OVERSCAN_X16 bme280.overscan_humidity = adafruit_bme280.OVERSCAN_X1 bme280.overscan_temperature = adafruit_bme280.OVERSCAN_X2 uart = busio.UART(board.A2, board.A3, baudrate=9600, timeout=10) gps = adafruit_gps.GPS(uart, debug=False) gps.send_command(const(b"PMTK314,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0")) gps.send_command(const(b"PMTK220,1000")) btn = digitalio.DigitalInOut(board.B0) btn.direction = digitalio.Direction.INPUT btn.pull = digitalio.Pull.DOWN # Release any resources currently in use for the displays displayio.release_displays() # Display init spi = busio.SPI(clock=board.B10, MOSI=board.B15, MISO=board.B14) while not spi.try_lock(): pass spi.configure(baudrate=25000000, phase=0, polarity=0) spi.unlock() init_sequence = ( b"\x01\x80\x32" # _SWRESET and Delay 50ms b"\x11\x80\xFF" # _SLPOUT b"\x3A\x81\x05\x0A" # _COLMOD b"\xB1\x83\x00\x06\x03\x0A" # _FRMCTR1 b"\x36\x01\x08" # _MADCTL b"\xB6\x02\x15\x02" # _DISSET5 # 1 clk cycle nonoverlap, 2 cycle gate, rise, 3 cycle osc equalize, Fix on VTL #b"\xB4\x00\x00" # _INVCTR line inversion b"\xC0\x82\x02\x70\x0A" # _PWCTR1 GVDD = 4.7V, 1.0uA, 10 ms delay
def __init__(self, *, url=None, headers=None, json_path=None, regexp_path=None, default_bg=0x000000, status_neopixel=None, text_font=None, text_position=None, text_color=0x808080, text_wrap=False, text_maxlen=0, text_transform=None, json_transform=None, image_json_path=None, image_resize=None, image_position=None, image_dim_json_path=None, caption_text=None, caption_font=None, caption_position=None, caption_color=0x808080, image_url_path=None, success_callback=None, esp=None, external_spi=None, debug=False): self._debug = debug try: if hasattr(board, 'TFT_BACKLIGHT'): self._backlight = pulseio.PWMOut(board.TFT_BACKLIGHT) # pylint: disable=no-member elif hasattr(board, 'TFT_LITE'): self._backlight = pulseio.PWMOut(board.TFT_LITE) # pylint: disable=no-member except ValueError: self._backlight = None self.set_backlight(1.0) # turn on backlight self._url = url self._headers = headers if json_path: if isinstance(json_path[0], (list, tuple)): self._json_path = json_path else: self._json_path = (json_path,) else: self._json_path = None self._regexp_path = regexp_path self._success_callback = success_callback if status_neopixel: self.neopix = neopixel.NeoPixel(status_neopixel, 1, brightness=0.2) else: self.neopix = None self.neo_status(0) try: os.stat(LOCALFILE) self._uselocal = True except OSError: self._uselocal = False if self._debug: print("Init display") self.splash = displayio.Group(max_size=15) if self._debug: print("Init background") self._bg_group = displayio.Group(max_size=1) self._bg_file = None self._default_bg = default_bg self.splash.append(self._bg_group) # show thank you and bootup file if available for bootscreen in ("/thankyou.bmp", "/pyportal_startup.bmp"): try: os.stat(bootscreen) board.DISPLAY.show(self.splash) for i in range(100, -1, -1): # dim down self.set_backlight(i/100) time.sleep(0.005) self.set_background(bootscreen) try: board.DISPLAY.refresh(target_frames_per_second=60) except AttributeError: board.DISPLAY.wait_for_frame() for i in range(100): # dim up self.set_backlight(i/100) time.sleep(0.005) time.sleep(2) except OSError: pass # they removed it, skip! self._speaker_enable = DigitalInOut(board.SPEAKER_ENABLE) self._speaker_enable.switch_to_output(False) if hasattr(board, 'AUDIO_OUT'): self.audio = audioio.AudioOut(board.AUDIO_OUT) elif hasattr(board, 'SPEAKER'): self.audio = audioio.AudioOut(board.SPEAKER) else: raise AttributeError('Board does not have a builtin speaker!') try: self.play_file("pyportal_startup.wav") except OSError: pass # they deleted the file, no biggie! if esp: # If there was a passed ESP Object if self._debug: print("Passed ESP32 to PyPortal") self._esp = esp if external_spi: #If SPI Object Passed spi = external_spi else: # Else: Make ESP32 connection spi = busio.SPI(board.SCK, board.MOSI, board.MISO) else: if self._debug: print("Init ESP32") esp32_ready = DigitalInOut(board.ESP_BUSY) esp32_gpio0 = DigitalInOut(board.ESP_GPIO0) esp32_reset = DigitalInOut(board.ESP_RESET) esp32_cs = DigitalInOut(board.ESP_CS) spi = busio.SPI(board.SCK, board.MOSI, board.MISO) self._esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset, esp32_gpio0) #self._esp._debug = 1 for _ in range(3): # retries try: print("ESP firmware:", self._esp.firmware_version) break except RuntimeError: print("Retrying ESP32 connection") time.sleep(1) self._esp.reset() else: raise RuntimeError("Was not able to find ESP32") requests.set_socket(socket, self._esp) if url and not self._uselocal: self._connect_esp() if self._debug: print("My IP address is", self._esp.pretty_ip(self._esp.ip_address)) # set the default background self.set_background(self._default_bg) board.DISPLAY.show(self.splash) if self._debug: print("Init SD Card") sd_cs = DigitalInOut(board.SD_CS) self._sdcard = None try: self._sdcard = adafruit_sdcard.SDCard(spi, sd_cs) vfs = storage.VfsFat(self._sdcard) storage.mount(vfs, "/sd") except OSError as error: print("No SD card found:", error) self._qr_group = None # Tracks whether we've hidden the background when we showed the QR code. self._qr_only = False if self._debug: print("Init caption") self._caption = None if caption_font: self._caption_font = bitmap_font.load_font(caption_font) self.set_caption(caption_text, caption_position, caption_color) if text_font: if isinstance(text_position[0], (list, tuple)): num = len(text_position) if not text_wrap: text_wrap = [0] * num if not text_maxlen: text_maxlen = [0] * num if not text_transform: text_transform = [None] * num else: num = 1 text_position = (text_position,) text_color = (text_color,) text_wrap = (text_wrap,) text_maxlen = (text_maxlen,) text_transform = (text_transform,) self._text = [None] * num self._text_color = [None] * num self._text_position = [None] * num self._text_wrap = [None] * num self._text_maxlen = [None] * num self._text_transform = [None] * num self._text_font = bitmap_font.load_font(text_font) if self._debug: print("Loading font glyphs") # self._text_font.load_glyphs(b'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' # b'0123456789:/-_,. ') gc.collect() for i in range(num): if self._debug: print("Init text area", i) self._text[i] = None self._text_color[i] = text_color[i] self._text_position[i] = text_position[i] self._text_wrap[i] = text_wrap[i] self._text_maxlen[i] = text_maxlen[i] self._text_transform[i] = text_transform[i] else: self._text_font = None self._text = None # Add any JSON translators self._json_transform = [] if json_transform: if callable(json_transform): self._json_transform.append(json_transform) else: self._json_transform.extend(filter(callable, json_transform)) self._image_json_path = image_json_path self._image_url_path = image_url_path self._image_resize = image_resize self._image_position = image_position self._image_dim_json_path = image_dim_json_path if image_json_path or image_url_path: if self._debug: print("Init image path") if not self._image_position: self._image_position = (0, 0) # default to top corner if not self._image_resize: self._image_resize = (board.DISPLAY.width, board.DISPLAY.height) # default to full screen if hasattr(board, 'TOUCH_XL'): if self._debug: print("Init touchscreen") # pylint: disable=no-member self.touchscreen = adafruit_touchscreen.Touchscreen(board.TOUCH_XL, board.TOUCH_XR, board.TOUCH_YD, board.TOUCH_YU, calibration=((5200, 59000), (5800, 57000)), size=(board.DISPLAY.width, board.DISPLAY.height)) # pylint: enable=no-member self.set_backlight(1.0) # turn on backlight elif hasattr(board, 'BUTTON_CLOCK'): if self._debug: print("Init cursor") self.mouse_cursor = Cursor(board.DISPLAY, display_group=self.splash, cursor_speed=8) self.mouse_cursor.hide() self.cursor = CursorManager(self.mouse_cursor) else: raise AttributeError('PyPortal module requires either a touchscreen or gamepad.') gc.collect()
from secrets import secrets except ImportError: print("WiFi secrets are kept in secrets.py, please add them there!") raise # If you are using a board with pre-defined ESP32 Pins: esp32_cs = DigitalInOut(board.ESP_CS) esp32_ready = DigitalInOut(board.ESP_BUSY) esp32_reset = DigitalInOut(board.ESP_RESET) # If you have an externally connected ESP32: # esp32_cs = DigitalInOut(board.D9) # esp32_ready = DigitalInOut(board.D10) # esp32_reset = DigitalInOut(board.D5) spi = busio.SPI(board.SCK, board.MOSI, board.MISO) esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset) """Use below for Most Boards""" status_light = neopixel.NeoPixel(board.NEOPIXEL, 1, brightness=0.2) # Uncomment for Most Boards """Uncomment below for ItsyBitsy M4""" # status_light = dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1, brightness=0.2) # Uncomment below for an externally defined RGB LED # import adafruit_rgbled # from adafruit_esp32spi import PWMOut # RED_LED = PWMOut.PWMOut(esp, 26) # GREEN_LED = PWMOut.PWMOut(esp, 27) # BLUE_LED = PWMOut.PWMOut(esp, 25) # status_light = adafruit_rgbled.RGBLED(RED_LED, BLUE_LED, GREEN_LED) wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager( esp, secrets, status_light)
# -------------------------------------------------------------------------------- # Initialize I2C and OLED i2c = busio.I2C(board.SCL, board.SDA) oled = adafruit_ssd1306.SSD1306_I2C(128, 32, i2c) oled.fill(0) oled.text("Initializing SD", 0, 10) oled.show() # -------------------------------------------------------------------------------- # Initialize SD card # SD_CS = board.D10 # Connect to the card and mount the filesystem. spi = busio.SPI(board.D13, board.D11, board.D12) # SCK, MOSI, MISO cs = digitalio.DigitalInOut(board.D10) sdcard = adafruit_sdcard.SDCard(spi, cs) vfs = storage.VfsFat(sdcard) storage.mount(vfs, "/sd") oled.fill(0) oled.text("Done", 0, 10) oled.show() # -------------------------------------------------------------------------------- # Initialize globals encoder_counter = 0 encoder_direction = 0
import time import random from board import TX, RX, A1 import busio import digitalio from adafruit_max7219 import bcddigits mosi = TX clk = RX cs = digitalio.DigitalInOut(A1) spi = busio.SPI(clk, MOSI=mosi) leds = bcddigits.BCDDigits(spi, cs, nDigits=8) while True: # clear display and dim 0 leds.brightness(0) leds.clear_all() # place 8-digit number on display value = 12345678 leds.show_str(0, "{:8}".format(value)) leds.show() # increase the brightness slowly for i in range(16): leds.brightness(i) time.sleep(0.5) leds.brightness(3)
utx = board.TX urx = board.RX uart_port = busio.UART(utx, urx, baudrate=9600, timeout=3000) except Exception as e: print('TG:HW: unable to create uart port') print(e) #spi for display try: backlight = board.D9 disp_sck = board.SCK disp_mosi = board.MOSI disp_miso = board.MISO disp_cs = board.D8 disp_dc = board.D7 disp_rst = board.D10 disp_spi = busio.SPI(clock=board.SCK, MOSI=board.MOSI, MISO=board.MISO) except Exception as e: print('TG:HW: unable to create DISP SPI port') print(e) try: spkr_pin = board.A1 spkr_en_pin = board.A2 spkr_en = ezio.dio(spkr_en_pin, 0) spkr = ezio.sndio(spkr_pin) except Exception as e: print('TG:HW: unable to create spkr pins') print(e) time.sleep(.1)
import digitalio import busio import board from pl_uc8156 import PL_UC8156 # define the pins we will need clk = board.SCK # clock mosi = board.MOSI # MOSI miso = board.MISO # MISO cs = digitalio.DigitalInOut(board.D5) # chip-select rst = digitalio.DigitalInOut(board.D12) # reset busy = digitalio.DigitalInOut(board.D9) # busy # create the spi-device spi = busio.SPI(clock=clk, MOSI=mosi, MISO=miso) # give them all to our driver display = PL_UC8156(spi=spi, cs_pin=cs, rst_pin=rst, busy_pin=busy) # OPTIONAL: If you want to change the baudrate of the spi-connection # (default = 4MHz), uncomment and adapt the next line! #display.setbaudrate(4000000) # OPTIONAL: Color-definitions # The displays support up to 4 grayscale-colors: WHITE = PL_UC8156.WHITE LGRAY = PL_UC8156.LGRAY # light gray DGRAY = PL_UC8156.DGRAY # dark gray BLACK = PL_UC8156.BLACK
from xpt2046 import Touch from gpiozero import Button, DigitalOutputDevice import board import busio from time import sleep # touch callback def touchscreen_press(x, y): print(x, y) cs = DigitalOutputDevice(17, active_high=False, initial_value=None) clk = board.SCLK_1 # same as writing 21 mosi = board.MOSI_1 # same as writing 20 miso = board.MISO_1 # same as writing 19 irq = Button(26) spi = busio.SPI(clk, mosi, miso) # auxiliary SPI xpt = Touch(spi, cs=cs, int_pin=irq, int_handler=touchscreen_press) while True: #print(xpt.get_touch()) # to get the (x, y) coords when you desire sleep(.01)
base_url = "https://edgecollective.farmos.net/farm/sensor/listener/" JSON_POST_URL = base_url + farmos_pubkey + "?private_key=" + farmos_privkey # esp32 import adafruit_esp32spi.adafruit_esp32spi_socket as socket from adafruit_esp32spi import adafruit_esp32spi import adafruit_requests as requests esp32_cs = DigitalInOut(board.D10) esp32_ready = DigitalInOut(board.D9) esp32_reset = DigitalInOut(board.A0) esp_spi = busio.SPI(board.SCK, board.MOSI, board.MISO) esp = adafruit_esp32spi.ESP_SPIcontrol(esp_spi, esp32_cs, esp32_ready, esp32_reset) def connect(essid, password ): # note that these are arguments are b'essid' and b'password' print("Connecting to AP...") while not esp.is_connected: try: esp.connect_AP(essid, password) except RuntimeError as e: print("could not connect to AP, retrying: ", e) continue print("Connected to", str(esp.ssid, 'utf-8'), "\tRSSI:", esp.rssi)
return roll, pitch, heading # Initialize the onboard LED heartBeatLED = DigitalInOut(PIN_ONBOARD_LED) heartBeatLED.direction = Direction.OUTPUT packetReceivedLED = DigitalInOut(PIN_PACKET_LED) packetReceivedLED.direction = Direction.OUTPUT # Initialize the I2C bus i2c = busio.I2C(board.SCL, board.SDA) # Initialize the SPI bus spi = busio.SPI(SPI_SCK, MOSI=SPI_MOSI, MISO=SPI_MISO) print("This is node #{0}".format(RFM69_NETWORK_NODE)) print() print("{0} v{1:1.1f}".format(BLUEFRUIT_DEV_NAME, SCRIPT_VERSION)) # Initialize the Bluefruit LE SPI Friend and perform a factory reset bluefruit = BluefruitSPI(spi, cs=BLUEFRUIT_CS, irq=BLUEFRUIT_IRQ, reset=BLUEFRUIT_RST) print() print("Initializing Bluetooth") bluefruit.init() bluefruit.command_check_OK(b'AT+FACTORYRESET', delay=1)
def dataReadOut(): conn = psycopg2.connect(database="TemaccessToRemoteRp2", user="******", password="******", host="127.0.0.1", port="5432") #print ("Opened database successfully") c = conn.cursor() # Initialize SPI bus and sensor. spi = busio.SPI(board.SCK, MOSI=board.MOSI, MISO=board.MISO) cs1 = digitalio.DigitalInOut( board.D4) # Chip select of the MAX31865 board. cs2 = digitalio.DigitalInOut( board.D5) # Chip select of the MAX31865 board. cs3 = digitalio.DigitalInOut(board.D6) cs4 = digitalio.DigitalInOut(board.D13) cs5 = digitalio.DigitalInOut(board.D19) cs6 = digitalio.DigitalInOut(board.D26) cs7 = digitalio.DigitalInOut(board.D21) cs8 = digitalio.DigitalInOut(board.D20) cs9 = digitalio.DigitalInOut(board.D16) cs10 = digitalio.DigitalInOut(board.D12) cs11 = digitalio.DigitalInOut(board.D1) cs12 = digitalio.DigitalInOut(board.D7) cs13 = digitalio.DigitalInOut(board.D25) cs14 = digitalio.DigitalInOut(board.D24) cs15 = digitalio.DigitalInOut(board.D23) cs16 = digitalio.DigitalInOut(board.D18) cs17 = digitalio.DigitalInOut(board.D15) cs18 = digitalio.DigitalInOut(board.D14) cs19 = digitalio.DigitalInOut(board.D2) sensor1 = adafruit_max31865.MAX31865(spi, cs1, wires=4) sensor2 = adafruit_max31865.MAX31865(spi, cs2, wires=4) sensor3 = adafruit_max31865.MAX31865(spi, cs3, wires=4) sensor4 = adafruit_max31865.MAX31865(spi, cs4, wires=3) sensor5 = adafruit_max31865.MAX31865(spi, cs5, wires=4) sensor6 = adafruit_max31865.MAX31865(spi, cs6, wires=4) sensor7 = adafruit_max31865.MAX31865(spi, cs7, wires=4) sensor8 = adafruit_max31865.MAX31865(spi, cs8, wires=3) sensor9 = adafruit_max31865.MAX31865(spi, cs9, wires=4) sensor10 = adafruit_max31865.MAX31865(spi, cs10, wires=4) sensor11 = adafruit_max31865.MAX31865(spi, cs11, wires=4) sensor12 = adafruit_max31865.MAX31865(spi, cs12, wires=4) sensor13 = adafruit_max31865.MAX31865(spi, cs13, wires=4) sensor14 = adafruit_max31865.MAX31865(spi, cs14, wires=4) sensor15 = adafruit_max31865.MAX31865(spi, cs15, wires=4) sensor16 = adafruit_max31865.MAX31865(spi, cs16, wires=4) sensor17 = adafruit_max31865.MAX31865(spi, cs17, wires=4) sensor18 = adafruit_max31865.MAX31865(spi, cs18, wires=4) sensor19 = adafruit_max31865.MAX31865(spi, cs19, wires=4) c.execute('DROP TABLE IF EXISTS "sensors";') print('table deleted') c.execute( 'CREATE TABLE sensors(id SERIAL PRIMARY KEY, ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP, Temp1d4 FLOAT, Temp2d5 FLOAT, Temp3d6 FLOAT, \ Temp4d13 FLOAT, Temp5d19 FLOAT, Temp6d26 FLOAT, Temp7d21 FLOAT,Temp8d20 FLOAT,Temp9d16 FLOAT, \ Temp10d12 FLOAT,Temp11d1 FLOAT,Temp12d7 FLOAT, Temp13d8 FLOAT,Temp14d24 FLOAT,\ Temp15d23 FLOAT, Temp16d18 FLOAT,Temp17d15 FLOAT, Temp18d14 FLOAT,Temp19d2 FLOAT);' ) while True: # Read temperature. temp1 = sensor1.temperature temp2 = sensor2.temperature temp3 = sensor3.temperature temp4 = sensor4.temperature temp5 = sensor5.temperature temp6 = sensor6.temperature temp7 = sensor7.temperature temp8 = sensor8.temperature temp9 = sensor9.temperature temp10 = sensor10.temperature temp11 = sensor11.temperature temp12 = sensor12.temperature temp13 = sensor13.temperature temp14 = sensor14.temperature temp15 = sensor15.temperature temp16 = sensor16.temperature temp17 = sensor17.temperature temp18 = sensor18.temperature temp19 = sensor19.temperature c.execute("INSERT INTO sensors(Temp1d4, Temp2d5, Temp3d6,Temp4d13, \ Temp5d19, Temp6d26,Temp7d21,Temp8d20, Temp9d16, Temp10d12,Temp11d1,Temp12d7,Temp13d8,Temp14d24, \ Temp15d23, Temp16d18,Temp17d15, Temp18d14,Temp19d2) VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s, %s,%s,%s, %s,%s)" ,\ (temp1, temp2,temp3,temp4,temp5,temp6, temp7, temp8, temp9, temp10, temp11,temp12, temp13, temp14, temp15,temp16, temp17,temp18, temp19)) conn.commit() #print ('Top Source Tank:', temp4) #print ('Bottom Source Tank:', temp8) #print ('Top Testing HP circuit:', temp2) #print ('Bottom Testing HP circuit:', temp3) #print ('Top Testing load circuit:', temp6) #print ('Bottom Testing load circuit:', temp9) #print ('Load Tank tem.:', temp5) #print ('Mix tem at load:', temp7) #print('--------------------------') #print(stdout) print('done everything') sleep(0.1) return
### WiFi ### # Get wifi details and more from a secrets.py file try: from secrets import secrets except ImportError: print("WiFi secrets are kept in secrets.py, please add them there!") raise # Raspberry Pi RP2040 esp32_cs = DigitalInOut(board.GP13) esp32_ready = DigitalInOut(board.GP14) esp32_reset = DigitalInOut(board.GP15) spi = busio.SPI(board.GP10, board.GP11, board.GP12) esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset) wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(esp, secrets) # Configure the RP2040 Pico LED Pin as an output led_pin = DigitalInOut(board.LED) led_pin.switch_to_output() # Define callback functions which will be called when certain events happen. # pylint: disable=unused-argument def connected(client): # Connected function will be called when the client is connected to Adafruit IO. print("Connected to Adafruit IO! ")
def talk_to_xbee(): serial_set = False spi = busio.SPI(clock=board.SCK, MISO=board.MISO, MOSI=board.MOSI) cs = digitalio.DigitalInOut(board.D25) mcp = MCP.MCP3008(spi, cs) anemometer = AnalogIn(mcp, MCP.P0) dht = adafruit_dht.DHT22(board.D5) speed_average = [0, 0, 0, 0, 0] temp_average = [0, 0, 0, 0, 0] humidity_average = [0, 0, 0, 0, 0] pointer = 0 while not serial_set and datalocker.ProgramRunning: try: # The Miniuart (ttyS0) is used on the Raspberry Pi # The full UART is connected to the onboard Bluetooth device # Default settings: 8bits, no parity, 1 stopbit, baud 9600 # Timeout can be set as Serial("/dev/ttyS0", 115200, timeout = 5) in seconds # Timeout will stop the readline() function, no timeout implies the function will run until data is received port = serial.Serial("/dev/ttyS0", 115200) serial_set = True except serial.SerialException: print("Serial connection failed, trying again...") while pointer < 5: try: temp_average[pointer] = dht.temperature humidity_average[pointer] = dht.humidity pointer = pointer + 1 except RuntimeError as e: sleep(10) pointer = 0 # Possibly average this value anemometer_offset = anemometer.voltage while pointer < 5: try: speed_average[pointer] = abs((anemometer.voltage - anemometer_offset) * 20.25) pointer = pointer + 1 except RuntimeError as e: sleep(10) pointer = 0 while datalocker.ProgramRunning: if port.inWaiting() > 0: temp = convert_to_dict(port.readline()) temp['Timestamp'] = datetime.timestamp(datetime.now()) temp['Minute'] = datetime.now().minute temp['Hour'] = datetime.now().hour temp['Day'] = datetime.now().day temp['Month'] = datetime.now().month temp['Year'] = datetime.now().year temp['Temperature'] = sum(temp_average)/len(temp_average) temp['Humidity'] = sum(humidity_average)/len(humidity_average) temp['Wind'] = sum(speed_average)/len(speed_average) log_data(temp) datalocker.SensorStats[temp.get('Sector')] = temp datalocker.set_new() if datetime.now().minute / 2 == 0: try: speed_average[pointer] = abs((anemometer.voltage - anemometer_voffset) * 20.25) pointer = (pointer + 1) % 5 except RuntimeError as e: print("Wind speed retrieve failed") try: temp_average[pointer] = dht.temperature humidity_average[pointer] = dht.humidity pointer = (pointer + 1) % 5 except RuntimeError as e: print("Temp/Humidity") port.close()
# import simpleio # simpleio.tone(buzzer_pin, 300,duration=0.1) # display imports import displayio import framebufferio import sharpdisplay import busio from adafruit_display_text.label import Label from terminalio import FONT # Release the existing display, if any displayio.release_displays() bus = busio.SPI(board.P0_12, board.P0_04) chip_select_pin = board.P0_08 framebuffer = sharpdisplay.SharpMemoryFramebuffer(bus, chip_select_pin, 400, 240, baudrate=2000000) display_on_in = DigitalInOut(board.P0_30) display_on_in.direction = Direction.OUTPUT display_on_in.value = True display = framebufferio.FramebufferDisplay(framebuffer) my_label = Label(FONT, text="hello hal", y=120, x=20, scale=4) display.show(my_label)
import math print("importing adafruit libs") import busio import board import digitalio import adafruit_74hc595 import pulseio from supervisor import runtime from sys import stdin ### CPX SCL is A4, SDA is A5 print("instantiating spi srlatchpin and sr") spi = busio.SPI(board.SCL, board.SDA) srlatchpin = digitalio.DigitalInOut(board.A7) sr = adafruit_74hc595.ShiftRegister74HC595(spi, srlatchpin) ##sr.gpio = 0x00 ##sr.gpio = 0x55 ##sr.gpio = 0xaa ##sr.gpio = 0xff ##sr.gpio = 0x00 ### TODO - turn this into a library ### TODO - look into MIDI over USB or over RX pin (I'm using TX!!) ### TODO - check behaviour/response of A0 to see if it's usable with speaker disabled ### TODO - look at manual envelope and modulation ### Using A3 for now - be wary of A0 as may have extra capacitance twomeg = const(2 * 1000 * 1000)
print("==============================") print(os.uname()) print("Hello Raspberry Pi Pico/CircuitPython ST7789 SPI IPS Display") print(adafruit_st7789.__name__ + " version: " + adafruit_st7789.__version__) print() # Release any resources currently in use for the displays displayio.release_displays() tft_cs = board.GP17 tft_dc = board.GP16 spi_mosi = board.GP19 spi_clk = board.GP18 spi = busio.SPI(spi_clk, MOSI=spi_mosi) display_bus = displayio.FourWire(spi, command=tft_dc, chip_select=tft_cs) #I get the parameters by guessing and trying #display = ST7789(display_bus, width=135, height=240, rowstart=40, colstart=53) display = adafruit_st7789.ST7789(display_bus, width=240, height=240, rowstart=80, colstart=0) display.rotation = 180 # Make the display context splash = displayio.Group() display.show(splash) color_bitmap = displayio.Bitmap(240, 240, 1) color_palette = displayio.Palette(1) color_palette[0] = 0x00FF00
img_time = 10 # Release any resources currently in use for the displays displayio.release_displays() # attempt to auto-detect board type import os board_type = os.uname().machine if 'QT Py M0 Haxpress' in board_type or 'QT Py RP2040' in board_type: tft_clk = board.SCK tft_mosi = board.MOSI tft_rst = board.TX tft_dc = board.RX tft_cs = board.A3 tft_bl = board.A2 spi = busio.SPI(clock=tft_clk, MOSI=tft_mosi) elif 'ItsyBitsy M4' in board_type: tft_clk = board.SCK tft_mosi = board.MOSI tft_rst = board.MISO tft_dc = board.D2 tft_cs = board.A5 tft_bl = board.A3 # optional spi = busio.SPI(clock=tft_clk, MOSI=tft_mosi) elif 'Pico' in board_type: # Raspberry Pi Pico pinout, one possibility, at "southwest" of board tft_clk = board.GP10 # must be a SPI CLK tft_mosi = board.GP11 # must be a SPI TX tft_rst = board.GP12 tft_dc = board.GP13 tft_cs = board.GP14
# Turtle Gizmo Star Fancy #==| Turtle Gizmo Setup start |======================================== import board import busio import displayio from adafruit_st7789 import ST7789 from adafruit_turtle import Color, turtle displayio.release_displays() spi = busio.SPI(board.SCL, MOSI=board.SDA) display_bus = displayio.FourWire(spi, command=board.TX, chip_select=board.RX) display = ST7789(display_bus, width=240, height=240, rowstart=80, backlight_pin=board.A3, rotation=180) turtle = turtle(display) #==| Turtle Gizmo Setup end |========================================= turtle.pendown() turtle.pencolor(Color.BLUE) for i in range(26): turtle.fd(i * 10) turtle.rt(144) while True: pass
# Will update channel values to different PWM duty cycles. # Author: Tony DiCola import board import busio import digitalio import adafruit_tlc5947 # Define pins connected to the TLC5947 SCK = board.SCK MOSI = board.MOSI LATCH = digitalio.DigitalInOut(board.D5) # Initialize SPI bus. spi = busio.SPI(clock=SCK, MOSI=MOSI) # Initialize TLC5947 tlc5947 = adafruit_tlc5947.TLC5947(spi, LATCH) # You can optionally disable auto_write which allows you to control when # channel state is written to the chip. Normally auto_write is true and # will automatically write out changes as soon as they happen to a channel, but # if you need more control or atomic updates of multiple channels then disable # and manually call write as shown below. #tlc5947 = adafruit_tlc5947.TLC5947(spi, LATCH, auto_write=False) # There are two ways to channel channel PWM values. The first is by getting # a PWMOut object that acts like the built-in PWMOut and can be used anywhere # it is used in your code. Change the duty_cycle property to a 16-bit value # (note this is NOT the 12-bit value supported by the chip natively) and the # PWM channel will be updated.
import logging import time import board import busio from adafruit_bus_device.spi_device import SPIDevice from communications.ax5043_manager.ax5043_driver import Ax5043 from communications.ax5043_manager.ax5043_manager import Manager logging.basicConfig(level=logging.DEBUG) driver = Ax5043( SPIDevice(busio.SPI(board.SCK, MOSI=board.MOSI, MISO=board.MISO))) mgr = Manager(driver) mgr.tx_enabled = True mgr.inbox.put(bytearray([0xCA, 0xFE, 0xBA, 0xBE])) cycles = 0 while True: logging.debug('Start of control cycle') # Dispatch components mgr.dispatch() # Health monitoring if mgr.is_faulted(): logging.error('Radio manager faulted') mgr.reset_requested = True cycles += 1 # After 10s, break for clean shutdown
wallet = sys.argv[2] if wallet.startswith("0x"): wallet = wallet[2:] value_api_url = "https://api.coingecko.com/api/v3/simple/price?ids=ethereum&vs_currencies=usd" # Configuration for CS and DC pins (these are FeatherWing defaults on M0/M4): cs_pin = digitalio.DigitalInOut(board.CE0) dc_pin = digitalio.DigitalInOut(board.CE1) reset_pin = None # Config for display baudrate (default max is 24mhz): BAUDRATE = 24000000 # Setup SPI bus using hardware SPI: spi = busio.SPI(clock=SCK, MOSI=MOSI, MISO=MISO) # Create the ST7789 display: disp = hx8357.HX8357(spi, cs=cs_pin, dc=dc_pin, rst=reset_pin, baudrate=BAUDRATE, width=99, height=99) # Create blank image for drawing. # Make sure to create image with mode 'RGB' for full color. if disp.rotation % 180 == 90: height = disp.width # we swap height/width to rotate it to landscape! width = disp.height
import digitalio import busio import board from adafruit_epd.epd import Adafruit_EPD from PIL import Image, ImageDraw, ImageFont import RPi.GPIO as GPIO from adafruit_epd.il0373 import Adafruit_IL0373 import time #EINK 1--------------------------------------------------------------------- spi1 = busio.SPI(board.SCK, MOSI=board.MOSI, MISO=board.MISO) ecs1 = digitalio.DigitalInOut(board.D5) dc1 = digitalio.DigitalInOut(board.D22) rst1 = digitalio.DigitalInOut(board.D27) busy1 = digitalio.DigitalInOut(board.D4) srcs1 = None display1 = Adafruit_IL0373(104, 212, spi1, cs_pin=ecs1, dc_pin=dc1, sramcs_pin=srcs1, rst_pin=rst1, busy_pin=busy1) #for flexible display: display1.set_black_buffer(1, False) display1.set_color_buffer(1, False) #--------------------------------------------------------------------------- #EINK 2 --------------------------------------------------------------------
import busio import digitalio import board import adafruit_mcp3xxx.mcp3008 as MCP from adafruit_mcp3xxx.analog_in import AnalogIn import time # create the spi bus spi = busio.SPI(clock=board.SCK, MISO=board.MISO, MOSI=board.MOSI) # create the cs (chip select) cs = digitalio.DigitalInOut(board.D5) # create the mcp object mcp = MCP.MCP3008(spi, cs) # create an analog input channel on pin 0 chan = AnalogIn(mcp, MCP.P6) ##### Initialize Parameters ####### kvalue = 0.996 #kvalueLow = 1.0 #kvalueHigh = 1.0 temperature = 25.000 v_level = 5 ################################## while True: ##### Calculations ############### voltage = ((chan.value)/(2**16)*1000*v_level) rawEC = 1000.000*voltage/(820.000*200.000) valueTemp = rawEC * kvalue
def SPI(): """The singleton SPI interface""" import busio return busio.SPI(SCLK, MOSI, MISO)
from adafruit_mcp3xxx.analog_in import AnalogIn #Magnetometer imports import smbus #BME imports import adafruit_bme280 #Camera imports #from picamera import PiCamera #from time import sleep #Setup Phase # Create ADC SPI buses ADC1spi = busio.SPI(clock=board.SCK, MISO=board.MISO, MOSI=board.MOSI) ADC1cs = digitalio.DigitalInOut(board.D5) ADC1mcp = MCP.MCP3008(ADC1spi, ADC1cs) ADC1channel = AnalogIn(ADC1mcp, MCP.P0) ADC2spi = busio.SPI(clock=board.SCK_1, MISO=board.MISO_1, MOSI=board.MOSI_1) ADC2cs = digitalio.DigitalInOut(board.D5) ADC2mcp = MCP.MCP3008(ADC2spi, ADC2cs) ADC2channel = AnalogIn(ADC2mcp, MCP.P0) #Create Magnetometer I2C bus bus = smbus.SMBus(1) config = [0x00, 0x5C, 0x00] bus.write_i2c_block_data(0x0C, 0x60, config) data = bus.read_byte(0x0C) config = [0x02, 0xB4, 0x08]
# from https://circuitpython.org/libraries from adafruit_display_text import label from adafruit_st7789 import ST7789 import adafruit_bmp280 # custom code for VL53L1x (not official support at this time) from custom_vl53l1x import VL53L1X # release any resources currently in use for the displays displayio.release_displays() # init SPI for pico explorer ST7789 display tft_cs = board.GP17 tft_dc = board.GP16 spi_mosi = board.GP19 spi_clk = board.GP18 spi = busio.SPI(spi_clk, spi_mosi) display_bus = displayio.FourWire(spi, command=tft_dc, chip_select=tft_cs) display = ST7789(display_bus, width=240, height=240, rowstart=80, rotation=180) # init BMP280 and VL53L1X sensor i2c_scl = board.GP21 i2c_sda = board.GP20 i2c = busio.I2C(scl=i2c_scl, sda=i2c_sda) bmp = adafruit_bmp280.Adafruit_BMP280_I2C(i2c, address=0x76) vl53 = VL53L1X(i2c, address=0x29) # create the text label with built-in font temp_txt = label.Label(terminalio.FONT, text=" ", color=0x00FF00, scale=2,
# Simple demo of the TLC59711 16-bit 12 channel LED PWM driver. # Shows setting channel values in a few ways. # Author: Tony DiCola import board import busio import adafruit_tlc59711 # Define SPI bus connected to chip. You only need the clock and MOSI (output) # line to use this chip. spi = busio.SPI(board.SCK, MOSI=board.MOSI) # Define the TLC59711 instance. leds = adafruit_tlc59711.TLC59711(spi) # Optionally you can disable the auto_show behavior that updates the chip # as soon as any channel value is written. The default is True/on but you can # disable and explicitly call show to control when updates happen for better # animation or atomic RGB LED updates. # leds = adafruit_tlc59711.TLC59711(spi, auto_show=False) # There are a couple ways to control the channels of the chip. # The first is using an interface like a strip of NeoPixels. Index into the # class for the channel and set or get its R, G, B tuple value. Note the # component values are 16-bit numbers that range from 0-65535 (off to full # brightness). Remember there are only 4 channels available too (0 to 3). # For example set channel 0 (R0, G0, B0) to half brightness: leds[0] = (32767, 32767, 32767) # Dont forget to call show if you disabled auto_show above. # leds.show() # Or to set channel 1 to full red only (green and blue off).
#!/usr/bin/env python3 import board import busio import digitalio import adafruit_max31855 temp1 = board.D5 # BBQ temp2 = board.D19 # Meat spi0 = busio.SPI(board.SCK, MOSI=board.MOSI, MISO=board.MISO) spi1 = busio.SPI(board.SCK, MOSI=board.MOSI, MISO=board.MISO) cs0 = digitalio.DigitalInOut(temp1) cs1 = digitalio.DigitalInOut(temp2) max318551 = adafruit_max31855.MAX31855(spi0, cs0) max318552 = adafruit_max31855.MAX31855(spi1, cs1) def get_temp(): return (max318551.temperature, max318552.temperature)
# Controller: Adafruit Feather M4 # Radar: SiversIMA RS3400X FMCW # GPS: Adafruit Ultimate GPS # IMU: Adafruit BNO055 import time import board import busio from digitalio import DigitalInOut, Direction, Pull import adafruit_bno055 import neopixel import adafruit_sdcard import storage # SD Card Init spi = busio.SPI(board.SCK, MOSI=board.MOSI, MISO=board.MISO) cs = DigitalInOut(board.D10) sdcard = adafruit_sdcard.SDCard(spi, cs) vfs = storage.VfsFat(sdcard) storage.mount(vfs, "/sd") sd_error = 0 # Status LEDs pixel = neopixel.NeoPixel(board.NEOPIXEL, 1, brightness=0.5, auto_write=True) pixel.fill((0, 0, 255)) # Blue status while booting # This function constructs a JSON-like object def write_data(file_name, data): #gc.collect() error_code = update_status(True)
def __init__(self, *, url, json_path=None, xml_path=None, default_bg=None, status_neopixel=None, text_font=None, text_position=None, text_color=0x808080, text_wrap=0, text_maxlen=0, image_json_path=None, image_resize=None, image_position=None, time_between_requests=60, success_callback=None, caption_text=None, caption_font=None, caption_position=None, caption_color=0x808080, debug=True): self._debug = debug try: self._backlight = pulseio.PWMOut(board.TFT_BACKLIGHT) except: self._backlight = None self.set_backlight(1.0) # turn on backlight self._url = url if json_path: if isinstance(json_path[0], tuple) or isinstance( json_path[0], list): self._json_path = json_path else: self._json_path = (json_path, ) else: self._json_path = None self._xml_path = xml_path self._time_between_requests = time_between_requests self._success_callback = success_callback if status_neopixel: self.neopix = neopixel.NeoPixel(status_neopixel, 1, brightness=0.2) else: self.neopix = None self.neo_status(0) try: os.stat(LOCALFILE) self._uselocal = True except OSError: self._uselocal = False # Make ESP32 connection if self._debug: print("Init ESP32") esp32_cs = DigitalInOut(microcontroller.pin.PB14) # PB14 esp32_ready = DigitalInOut(microcontroller.pin.PB16) esp32_gpio0 = DigitalInOut(microcontroller.pin.PB15) esp32_reset = DigitalInOut(microcontroller.pin.PB17) spi = busio.SPI(board.SCK, board.MOSI, board.MISO) if not self._uselocal: self._esp = adafruit_esp32spi.ESP_SPIcontrol( spi, esp32_cs, esp32_ready, esp32_reset, esp32_gpio0) #self._esp._debug = 1 for _ in range(3): # retries try: print("ESP firmware:", self._esp.firmware_version) break except RuntimeError: print("Retrying ESP32 connection") time.sleep(1) self._esp.reset() else: raise RuntimeError("Was not able to find ESP32") requests.set_interface(self._esp) if self._debug: print("Init display") self.splash = displayio.Group(max_size=5) board.DISPLAY.show(self.splash) if self._debug: print("Init background") self._bg_group = displayio.Group(max_size=1) self._bg_file = None self.set_background(default_bg) self.splash.append(self._bg_group) self._qr_group = None if self._debug: print("Init caption") self._caption = None if caption_font: self._caption_font = bitmap_font.load_font(caption_font) self.set_caption(caption_text, caption_position, caption_color) if text_font: if isinstance(text_position[0], tuple) or isinstance( text_position[0], list): num = len(text_position) if not text_wrap: text_wrap = [0] * num if not text_maxlen: text_maxlen = [0] * num else: num = 1 text_position = (text_position, ) text_color = (text_color, ) text_wrap = (text_wrap, ) text_maxlen = (text_maxlen, ) self._text = [None] * num self._text_color = [None] * num self._text_position = [None] * num self._text_wrap = [None] * num self._text_maxlen = [None] * num self._text_font = bitmap_font.load_font(text_font) if self._debug: print("Loading font glyphs") #self._text_font.load_glyphs(b'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789:/-_,. ') gc.collect() for i in range(num): if self._debug: print("Init text area", i) self._text[i] = None self._text_color[i] = text_color[i] self._text_position[i] = text_position[i] self._text_wrap[i] = text_wrap[i] self._text_maxlen[i] = text_maxlen[i] else: self._text_font = None self._text = None self._image_json_path = image_json_path self._image_resize = image_resize self._image_position = image_position if image_json_path: if self._debug: print("Init image path") if not self._image_position: self._image_position = (0, 0) # default to top corner if not self._image_resize: self._image_resize = (320, 240) # default to full screen if self._debug: print("Init touchscreen") self.ts = adafruit_touchscreen.Touchscreen(microcontroller.pin.PB01, microcontroller.pin.PB08, microcontroller.pin.PA06, microcontroller.pin.PB00, calibration=((5200, 59000), (5800, 57000)), size=(320, 240)) self.set_backlight(1.0) # turn on backlight gc.collect()