def on(*buttons, fn=None, action=DOWN): global GAMEPAD for button in buttons: if button not in BUTTONS: if button in DIGITALIO: dio = DigitalInOut(button) dio.direction = Direction.INPUT dio.pull = Pull.DOWN elif button in TOUCHIO: dio = TouchIn(button) else: print("unknown button {}".format(button)) BUTTONS.append(button) DIOS.append(dio) value = tuple(buttons) def wrapper(fn): PRESSES.append((fn, buttons, action)) return fn if fn: return wrapper(fn) return wrapper
def __init__(self, trigger_pin, echo_pin, *, timeout=0.1): """ :param trigger_pin: The pin on the microcontroller that's connected to the ``Trig`` pin on the HC-SR04. :type trig_pin: microcontroller.Pin :param echo_pin: The pin on the microcontroller that's connected to the ``Echo`` pin on the HC-SR04. :type echo_pin: microcontroller.Pin :param float timeout: Max seconds to wait for a response from the sensor before assuming it isn't going to answer. Should *not* be set to less than 0.05 seconds! """ self._timeout = timeout self._trig = DigitalInOut(trigger_pin) self._trig.direction = Direction.OUTPUT if _USE_PULSEIO: self._echo = PulseIn(echo_pin) self._echo.pause() self._echo.clear() else: self._echo = DigitalInOut(echo_pin) self._echo.direction = Direction.INPUT
#calling firebase getting the ID and printing the result firebase = firebase.FirebaseApplication('https://bowall.firebaseio.com/') result = firebase.get('/checkValue','checkID') print(result) #importing the Sounds location = vlc.MediaPlayer("Localistation.wav") Error = vlc.MediaPlayer("Error.wav") Success = vlc.MediaPlayer("Success.wav") Celebration = vlc.MediaPlayer("Celebration.wav") # set the GPIO input pins pad0_pin = board.D4 pad0 = DigitalInOut(pad0_pin) pad0.direction = Direction.INPUT pad0_already_pressed = True while True: if pad0.value and not pad0_already_pressed: #playing the sound on touch Success.play() print("Pad 0 Pressed") #Changing the ID to 1 post = firebase.patch('/checkValue',{'checkID': 1})
import neopixel import adafruit_minimqtt.adafruit_minimqtt as MQTT from adafruit_io.adafruit_io import IO_MQTT from digitalio import DigitalInOut, Direction, Pull from adafruit_debouncer import Debouncer ### 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 switch_pin = DigitalInOut(board.D10) switch_pin.direction = Direction.INPUT switch_pin.pull = Pull.UP switch = Debouncer(switch_pin) # If you are using a board with pre-defined ESP32 Pins: esp32_cs = DigitalInOut(board.D13) esp32_ready = DigitalInOut(board.D11) esp32_reset = DigitalInOut(board.D12) 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 wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(
def runFireAnimation(): for i in range(pixelCount): flamePixels[i][0] = flamePixels[i][0] + flamePixels[i][3] flamePixels[i][1] = flamePixels[i][1] + flamePixels[i][3] / 5 flamePixels[i][2] = flamePixels[i][2] + flamePixels[i][3] / 5 #if we are over 255 in the red, then assign a new set of random flicker values if (flamePixels[i][0] > 255): flamePixels[i][0] = random.randint(25, 100) flamePixels[i][1] = random.randint(2, 50) flamePixels[i][2] = random.randint(2, 50) flamePixels[i][3] = random.randint(1, 12) pixels[i] = (flamePixels[i][0], flamePixels[i][1], flamePixels[i][2]) pixels.show() btn = DigitalInOut(board.GP2) btn.direction = Direction.INPUT btn.pull = Pull.UP pixels = neopixel.NeoPixel(board.GP0, pixelCount, brightness=.3, auto_write=False) def rainbow_cycle(wait, step): j = step for i in range(pixelCount): rc_index = (i * 256 // 10) + j * 5 pixels[i] = wheel(rc_index & 255) pixels.show()
Learn Guide: https://learn.adafruit.com/lora-and-lorawan-for-raspberry-pi Author: Brent Rubell for Adafruit Industries """ # Import Python System Libraries import time # Import Blinka Libraries import busio from digitalio import DigitalInOut, Direction, Pull import board # Import the SSD1306 module. import adafruit_ssd1306 # Import RFM9x import adafruit_rfm9x # Button A btnA = DigitalInOut(board.D5) btnA.direction = Direction.INPUT btnA.pull = Pull.UP # Button B btnB = DigitalInOut(board.D6) btnB.direction = Direction.INPUT btnB.pull = Pull.UP # Button C btnC = DigitalInOut(board.D12) btnC.direction = Direction.INPUT btnC.pull = Pull.UP # Create the I2C interface. i2c = busio.I2C(board.SCL, board.SDA)
class PyPortal: """Class representing the Adafruit PyPortal. :param url: The URL of your data source. Defaults to ``None``. :param headers: The headers for authentication, typically used by Azure API's. :param json_path: The list of json traversal to get data out of. Can be list of lists for multiple data points. Defaults to ``None`` to not use json. :param regexp_path: The list of regexp strings to get data out (use a single regexp group). Can be list of regexps for multiple data points. Defaults to ``None`` to not use regexp. :param default_bg: The path to your default background image file or a hex color. Defaults to 0x000000. :param status_neopixel: The pin for the status NeoPixel. Use ``board.NEOPIXEL`` for the on-board NeoPixel. Defaults to ``None``, no status LED :param str text_font: The path to your font file for your data text display. :param text_position: The position of your extracted text on the display in an (x, y) tuple. Can be a list of tuples for when there's a list of json_paths, for example :param text_color: The color of the text, in 0xRRGGBB format. Can be a list of colors for when there's multiple texts. Defaults to ``None``. :param text_wrap: Whether or not to wrap text (for long text data chunks). Defaults to ``False``, no wrapping. :param text_maxlen: The max length of the text for text wrapping. Defaults to 0. :param text_transform: A function that will be called on the text before display :param json_transform: A function or a list of functions to call with the parsed JSON. Changes and additions are permitted for the ``dict`` object. :param image_json_path: The JSON traversal path for a background image to display. Defaults to ``None``. :param image_resize: What size to resize the image we got from the json_path, make this a tuple of the width and height you want. Defaults to ``None``. :param image_position: The position of the image on the display as an (x, y) tuple. Defaults to ``None``. :param image_dim_json_path: The JSON traversal path for the original dimensions of image tuple. Used with fetch(). Defaults to ``None``. :param success_callback: A function we'll call if you like, when we fetch data successfully. Defaults to ``None``. :param str caption_text: The text of your caption, a fixed text not changed by the data we get. Defaults to ``None``. :param str caption_font: The path to the font file for your caption. Defaults to ``None``. :param caption_position: The position of your caption on the display as an (x, y) tuple. Defaults to ``None``. :param caption_color: The color of your caption. Must be a hex value, e.g. ``0x808000``. :param image_url_path: The HTTP traversal path for a background image to display. Defaults to ``None``. :param esp: A passed ESP32 object, Can be used in cases where the ESP32 chip needs to be used before calling the pyportal class. Defaults to ``None``. :param busio.SPI external_spi: A previously declared spi object. Defaults to ``None``. :param debug: Turn on debug print outs. Defaults to False. """ # pylint: disable=too-many-instance-attributes, too-many-locals, too-many-branches, too-many-statements 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() def set_headers(self, headers): """Set the headers used by fetch(). :param headers: The new header dictionary """ self._headers = headers def set_background(self, file_or_color, position=None): """The background image to a bitmap file. :param file_or_color: The filename of the chosen background image, or a hex color. """ print("Set background to ", file_or_color) while self._bg_group: self._bg_group.pop() if not position: position = (0, 0) # default in top corner if not file_or_color: return # we're done, no background desired if self._bg_file: self._bg_file.close() if isinstance(file_or_color, str): # its a filenme: self._bg_file = open(file_or_color, "rb") background = displayio.OnDiskBitmap(self._bg_file) try: self._bg_sprite = displayio.TileGrid( background, pixel_shader=displayio.ColorConverter(), position=position, ) except TypeError: self._bg_sprite = displayio.TileGrid( background, pixel_shader=displayio.ColorConverter(), x=position[0], y=position[1], ) elif isinstance(file_or_color, int): # Make a background color fill color_bitmap = displayio.Bitmap( board.DISPLAY.width, board.DISPLAY.height, 1 ) color_palette = displayio.Palette(1) color_palette[0] = file_or_color try: self._bg_sprite = displayio.TileGrid( color_bitmap, pixel_shader=color_palette, position=(0, 0) ) except TypeError: self._bg_sprite = displayio.TileGrid( color_bitmap, pixel_shader=color_palette, x=position[0], y=position[1], ) else: raise RuntimeError("Unknown type of background") self._bg_group.append(self._bg_sprite) try: board.DISPLAY.refresh(target_frames_per_second=60) gc.collect() except AttributeError: board.DISPLAY.refresh_soon() gc.collect() board.DISPLAY.wait_for_frame() def set_backlight(self, val): """Adjust the TFT backlight. :param val: The backlight brightness. Use a value between ``0`` and ``1``, where ``0`` is off, and ``1`` is 100% brightness. """ val = max(0, min(1.0, val)) if self._backlight: self._backlight.duty_cycle = int(val * 65535) else: board.DISPLAY.auto_brightness = False board.DISPLAY.brightness = val def preload_font(self, glyphs=None): # pylint: disable=line-too-long """Preload font. :param glyphs: The font glyphs to load. Defaults to ``None``, uses alphanumeric glyphs if None. """ # pylint: enable=line-too-long if not glyphs: glyphs = b"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-!,. \"'?!" print("Preloading font glyphs:", glyphs) if self._text_font: self._text_font.load_glyphs(glyphs) def set_caption(self, caption_text, caption_position, caption_color): # pylint: disable=line-too-long """A caption. Requires setting ``caption_font`` in init! :param caption_text: The text of the caption. :param caption_position: The position of the caption text. :param caption_color: The color of your caption text. Must be a hex value, e.g. ``0x808000``. """ # pylint: enable=line-too-long if self._debug: print("Setting caption to", caption_text) if (not caption_text) or (not self._caption_font) or (not caption_position): return # nothing to do! if self._caption: self._caption._update_text( # pylint: disable=protected-access str(caption_text) ) try: board.DISPLAY.refresh(target_frames_per_second=60) except AttributeError: board.DISPLAY.refresh_soon() board.DISPLAY.wait_for_frame() return self._caption = Label(self._caption_font, text=str(caption_text)) self._caption.x = caption_position[0] self._caption.y = caption_position[1] self._caption.color = caption_color self.splash.append(self._caption) def set_text(self, val, index=0): """Display text, with indexing into our list of text boxes. :param str val: The text to be displayed :param index: Defaults to 0. """ if self._text_font: string = str(val) if self._text_maxlen[index]: string = string[: self._text_maxlen[index]] if self._text[index]: # print("Replacing text area with :", string) # self._text[index].text = string # return try: text_index = self.splash.index(self._text[index]) except AttributeError: for i in range(len(self.splash)): if self.splash[i] == self._text[index]: text_index = i break self._text[index] = Label(self._text_font, text=string) self._text[index].color = self._text_color[index] self._text[index].x = self._text_position[index][0] self._text[index].y = self._text_position[index][1] self.splash[text_index] = self._text[index] return if self._text_position[index]: # if we want it placed somewhere... print("Making text area with string:", string) self._text[index] = Label(self._text_font, text=string) self._text[index].color = self._text_color[index] self._text[index].x = self._text_position[index][0] self._text[index].y = self._text_position[index][1] self.splash.append(self._text[index]) def neo_status(self, value): """The status NeoPixel. :param value: The color to change the NeoPixel. """ if self.neopix: self.neopix.fill(value) def play_file(self, file_name, wait_to_finish=True): """Play a wav file. :param str file_name: The name of the wav file to play on the speaker. """ wavfile = open(file_name, "rb") wavedata = audioio.WaveFile(wavfile) self._speaker_enable.value = True self.audio.play(wavedata) if not wait_to_finish: return while self.audio.playing: pass wavfile.close() self._speaker_enable.value = False @staticmethod def _json_traverse(json, path): value = json for x in path: value = value[x] gc.collect() return value def get_local_time(self, location=None): # pylint: disable=line-too-long """Fetch and "set" the local time of this microcontroller to the local time at the location, using an internet time API. :param str location: Your city and country, e.g. ``"New York, US"``. """ # pylint: enable=line-too-long self._connect_esp() api_url = None try: aio_username = secrets["aio_username"] aio_key = secrets["aio_key"] except KeyError: raise KeyError( "\n\nOur time service requires a login/password to rate-limit. Please register for a free adafruit.io account and place the user/key in your secrets file under 'aio_username' and 'aio_key'" # pylint: disable=line-too-long ) location = secrets.get("timezone", location) if location: print("Getting time for timezone", location) api_url = (TIME_SERVICE + "&tz=%s") % (aio_username, aio_key, location) else: # we'll try to figure it out from the IP address print("Getting time from IP address") api_url = TIME_SERVICE % (aio_username, aio_key) api_url += TIME_SERVICE_STRFTIME try: response = requests.get(api_url, timeout=10) if response.status_code != 200: raise ValueError(response.text) if self._debug: print("Time request: ", api_url) print("Time reply: ", response.text) times = response.text.split(" ") the_date = times[0] the_time = times[1] year_day = int(times[2]) week_day = int(times[3]) is_dst = None # no way to know yet except KeyError: raise KeyError( "Was unable to lookup the time, try setting secrets['timezone'] according to http://worldtimeapi.org/timezones" # pylint: disable=line-too-long ) year, month, mday = [int(x) for x in the_date.split("-")] the_time = the_time.split(".")[0] hours, minutes, seconds = [int(x) for x in the_time.split(":")] now = time.struct_time( (year, month, mday, hours, minutes, seconds, week_day, year_day, is_dst) ) print(now) rtc.RTC().datetime = now # now clean up response.close() response = None gc.collect() def wget(self, url, filename, *, chunk_size=12000): """Download a url and save to filename location, like the command wget. :param url: The URL from which to obtain the data. :param filename: The name of the file to save the data to. :param chunk_size: how much data to read/write at a time. """ print("Fetching stream from", url) self.neo_status((100, 100, 0)) r = requests.get(url, stream=True) if self._debug: print(r.headers) content_length = int(r.headers["content-length"]) remaining = content_length print("Saving data to ", filename) stamp = time.monotonic() file = open(filename, "wb") for i in r.iter_content(min(remaining, chunk_size)): # huge chunks! self.neo_status((0, 100, 100)) remaining -= len(i) file.write(i) if self._debug: print( "Read %d bytes, %d remaining" % (content_length - remaining, remaining) ) else: print(".", end="") if not remaining: break self.neo_status((100, 100, 0)) file.close() r.close() stamp = time.monotonic() - stamp print( "Created file of %d bytes in %0.1f seconds" % (os.stat(filename)[6], stamp) ) self.neo_status((0, 0, 0)) if not content_length == os.stat(filename)[6]: raise RuntimeError def _connect_esp(self): self.neo_status((0, 0, 100)) while not self._esp.is_connected: # secrets dictionary must contain 'ssid' and 'password' at a minimum print("Connecting to AP", secrets["ssid"]) if secrets["ssid"] == "CHANGE ME" or secrets["password"] == "CHANGE ME": change_me = "\n" + "*" * 45 change_me += "\nPlease update the 'secrets.py' file on your\n" change_me += "CIRCUITPY drive to include your local WiFi\n" change_me += "access point SSID name in 'ssid' and SSID\n" change_me += "password in 'password'. Then save to reload!\n" change_me += "*" * 45 raise OSError(change_me) self.neo_status((100, 0, 0)) # red = not connected try: self._esp.connect(secrets) except RuntimeError as error: print("Could not connect to internet", error) print("Retrying in 3 seconds...") time.sleep(3) @staticmethod def image_converter_url(image_url, width, height, color_depth=16): """Generate a converted image url from the url passed in, with the given width and height. aio_username and aio_key must be set in secrets.""" try: aio_username = secrets["aio_username"] aio_key = secrets["aio_key"] except KeyError: raise KeyError( "\n\nOur image converter service require a login/password to rate-limit. Please register for a free adafruit.io account and place the user/key in your secrets file under 'aio_username' and 'aio_key'" # pylint: disable=line-too-long ) return IMAGE_CONVERTER_SERVICE % ( aio_username, aio_key, width, height, color_depth, image_url, ) def sd_check(self): """Returns True if there is an SD card preset and False if there is no SD card. The _sdcard value is set in _init """ if self._sdcard: return True return False def push_to_io(self, feed_key, data): # pylint: disable=line-too-long """Push data to an adafruit.io feed :param str feed_key: Name of feed key to push data to. :param data: data to send to feed """ # pylint: enable=line-too-long try: aio_username = secrets["aio_username"] aio_key = secrets["aio_key"] except KeyError: raise KeyError( "Adafruit IO secrets are kept in secrets.py, please add them there!\n\n" ) wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager( self._esp, secrets, None ) io_client = IO_HTTP(aio_username, aio_key, wifi) while True: try: feed_id = io_client.get_feed(feed_key) except AdafruitIO_RequestError: # If no feed exists, create one feed_id = io_client.create_new_feed(feed_key) except RuntimeError as exception: print("An error occured, retrying! 1 -", exception) continue break while True: try: io_client.send_data(feed_id["key"], data) except RuntimeError as exception: print("An error occured, retrying! 2 -", exception) continue except NameError as exception: print(feed_id["key"], data, exception) continue break def fetch(self, refresh_url=None, timeout=10): """Fetch data from the url we initialized with, perfom any parsing, and display text or graphics. This function does pretty much everything Optionally update the URL """ if refresh_url: self._url = refresh_url json_out = None image_url = None values = [] gc.collect() if self._debug: print("Free mem: ", gc.mem_free()) # pylint: disable=no-member r = None if self._uselocal: print("*** USING LOCALFILE FOR DATA - NOT INTERNET!!! ***") r = Fake_Requests(LOCALFILE) if not r: self._connect_esp() # great, lets get the data print("Retrieving data...", end="") self.neo_status((100, 100, 0)) # yellow = fetching data gc.collect() r = requests.get(self._url, headers=self._headers, timeout=timeout) gc.collect() self.neo_status((0, 0, 100)) # green = got data print("Reply is OK!") if self._debug: print(r.text) if self._image_json_path or self._json_path: try: gc.collect() json_out = r.json() gc.collect() except ValueError: # failed to parse? print("Couldn't parse json: ", r.text) raise except MemoryError: supervisor.reload() if self._regexp_path: import re # pylint: disable=import-outside-toplevel if self._image_url_path: image_url = self._image_url_path # optional JSON post processing, apply any transformations # these MAY change/add element for idx, json_transform in enumerate(self._json_transform): try: json_transform(json_out) except Exception as error: print("Exception from json_transform: ", idx, error) raise # extract desired text/values from json if self._json_path: for path in self._json_path: try: values.append(PyPortal._json_traverse(json_out, path)) except KeyError: print(json_out) raise elif self._regexp_path: for regexp in self._regexp_path: values.append(re.search(regexp, r.text).group(1)) else: values = r.text if self._image_json_path: try: image_url = PyPortal._json_traverse(json_out, self._image_json_path) except KeyError as error: print("Error finding image data. '" + error.args[0] + "' not found.") self.set_background(self._default_bg) iwidth = 0 iheight = 0 if self._image_dim_json_path: iwidth = int( PyPortal._json_traverse(json_out, self._image_dim_json_path[0]) ) iheight = int( PyPortal._json_traverse(json_out, self._image_dim_json_path[1]) ) print("image dim:", iwidth, iheight) # we're done with the requests object, lets delete it so we can do more! json_out = None r = None gc.collect() if image_url: try: print("original URL:", image_url) if iwidth < iheight: image_url = self.image_converter_url( image_url, int( self._image_resize[1] * self._image_resize[1] / self._image_resize[0] ), self._image_resize[1], ) else: image_url = self.image_converter_url( image_url, self._image_resize[0], self._image_resize[1] ) print("convert URL:", image_url) # convert image to bitmap and cache # print("**not actually wgetting**") filename = "/cache.bmp" chunk_size = 4096 # default chunk size is 12K (for QSPI) if self._sdcard: filename = "/sd" + filename chunk_size = 512 # current bug in big SD writes -> stick to 1 block try: self.wget(image_url, filename, chunk_size=chunk_size) except OSError as error: print(error) raise OSError( """\n\nNo writable filesystem found for saving datastream. Insert an SD card or set internal filesystem to be unsafe by setting 'disable_concurrent_write_protection' in the mount options in boot.py""" # pylint: disable=line-too-long ) except RuntimeError as error: print(error) raise RuntimeError("wget didn't write a complete file") if iwidth < iheight: pwidth = int( self._image_resize[1] * self._image_resize[1] / self._image_resize[0] ) self.set_background( filename, ( self._image_position[0] + int((self._image_resize[0] - pwidth) / 2), self._image_position[1], ), ) else: self.set_background(filename, self._image_position) except ValueError as error: print("Error displaying cached image. " + error.args[0]) self.set_background(self._default_bg) finally: image_url = None gc.collect() # if we have a callback registered, call it now if self._success_callback: self._success_callback(values) # fill out all the text blocks if self._text: for i in range(len(self._text)): string = None if self._text_transform[i]: func = self._text_transform[i] string = func(values[i]) else: try: string = "{:,d}".format(int(values[i])) except (TypeError, ValueError): string = values[i] # ok its a string if self._debug: print("Drawing text", string) if self._text_wrap[i]: if self._debug: print("Wrapping text") lines = PyPortal.wrap_nicely(string, self._text_wrap[i]) string = "\n".join(lines) self.set_text(string, index=i) if len(values) == 1: return values[0] return values def show_QR( self, qr_data, *, qr_size=1, x=0, y=0, hide_background=False ): # pylint: disable=invalid-name """Display a QR code on the TFT :param qr_data: The data for the QR code. :param int qr_size: The scale of the QR code. :param x: The x position of upper left corner of the QR code on the display. :param y: The y position of upper left corner of the QR code on the display. :param hide_background: Show the QR code on a black background if True. """ import adafruit_miniqr # pylint: disable=import-outside-toplevel # generate the QR code qrcode = adafruit_miniqr.QRCode() qrcode.add_data(qr_data) qrcode.make() # monochrome (2 color) palette palette = displayio.Palette(2) palette[0] = 0xFFFFFF palette[1] = 0x000000 # pylint: disable=invalid-name # bitmap the size of the matrix, plus border, monochrome (2 colors) qr_bitmap = displayio.Bitmap( qrcode.matrix.width + 2, qrcode.matrix.height + 2, 2 ) for i in range(qr_bitmap.width * qr_bitmap.height): qr_bitmap[i] = 0 # transcribe QR code into bitmap for xx in range(qrcode.matrix.width): for yy in range(qrcode.matrix.height): qr_bitmap[xx + 1, yy + 1] = 1 if qrcode.matrix[xx, yy] else 0 # display the QR code qr_sprite = displayio.TileGrid(qr_bitmap, pixel_shader=palette) if self._qr_group: try: self._qr_group.pop() except IndexError: # later test if empty pass else: self._qr_group = displayio.Group() self.splash.append(self._qr_group) self._qr_group.scale = qr_size self._qr_group.x = x self._qr_group.y = y self._qr_group.append(qr_sprite) if hide_background: board.DISPLAY.show(self._qr_group) self._qr_only = hide_background def hide_QR(self): # pylint: disable=invalid-name """Clear any QR codes that are currently on the screen """ if self._qr_only: board.DISPLAY.show(self.splash) else: try: self._qr_group.pop() except (IndexError, AttributeError): # later test if empty pass # return a list of lines with wordwrapping @staticmethod def wrap_nicely(string, max_chars): """A helper that will return a list of lines with word-break wrapping. :param str string: The text to be wrapped. :param int max_chars: The maximum number of characters on a line before wrapping. """ string = string.replace("\n", "").replace("\r", "") # strip confusing newlines words = string.split(" ") the_lines = [] the_line = "" for w in words: if len(the_line + " " + w) <= max_chars: the_line += " " + w else: the_lines.append(the_line) the_line = "" + w if the_line: # last line remaining the_lines.append(the_line) # remove first space from first line: the_lines[0] = the_lines[0][1:] return the_lines
# Receives and display temperature, humidity, and pressure data from raw LoRa # radio. Run with lora-weather-client.ino on Arduino. # # Required packages: # pip install adafruit-circuitpython-rfm9x # # License: Beerware import time import busio from digitalio import DigitalInOut, Direction, Pull import board import adafruit_rfm9x # Configure RFM9x LoRa Radio CS = DigitalInOut(board.CE1) RESET = DigitalInOut(board.D25) spi = busio.SPI(board.SCK, MOSI=board.MOSI, MISO=board.MISO) # Attempt to set up the RFM9x module try: rfm9x = adafruit_rfm9x.RFM9x(spi, CS, RESET, 915.0) print('RFM9x detected') except RuntimeError: print('RFM9x error') # Wait for LoRa packets while True: packet = None packet = rfm9x.receive() if packet != None:
from touchio import TouchIn # External constants DOWN = 1 UP = 2 PROPOGATE = object() # Internal constants DIGITALIO = [board.BUTTON_A, board.BUTTON_B] TOUCHIO = [board.A1, board.A2, board.A3, board.A4, board.A5, board.A6, board.A7] SAMPLERATE = 8000 # recommended AUDIO = AudioOut(board.A0) SPEAKER = DigitalInOut(board.SPEAKER_ENABLE) SPEAKER.direction = Direction.OUTPUT # Internal state RUNNING = True INTERVALS = {} TIMERS = {} BUTTONS = [] DIOS = [] PRESSES = [] def tick(fn): INTERVALS[fn] = (0, 0) return fn
activate_this = '/home/pi/piled/.venv/bin/activate_this.py' exec(open(activate_this).read(), {'__file__': activate_this}) import adafruit_matrixkeypad import board from digitalio import DigitalInOut import time # 3x4 matrix keypad cols = [DigitalInOut(x) for x in (board.D4, board.D3, board.D2)] rows = [DigitalInOut(x) for x in (board.D23, board.D22, board.D27, board.D17)] keys = [ (1, 2, 3), (4, 5, 6), (7, 8, 9), ('*', 0, '#') ] keypad = adafruit_matrixkeypad.Matrix_Keypad(rows, cols, keys) while True: keys = keypad.pressed_keys if keys: print("Pressed: ", keys) time.sleep(0.1)
#Coding in Python Part 2 import time import board from digitalio import DigitalInOut, Direction, Pull import neopixel pixels = neopixel.NeoPixel(board.A4, 5, brightness=.9, auto_write=True) button = DigitalInOut(board.A3) button.direction = Direction.INPUT button.pull = Pull.UP for pixel in range(0,5): print(pixel) pixels[pixel] = (100, 0, 0) time.sleep(2) while True: buttonUp = button.value buttonDown = not buttonUp if buttonDown: print("start") time.sleep(.2)
# Solenoid Setup GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) GPIO.setup(26, GPIO.OUT) #Digole Setup and clear screen i2c_digole = smbus.SMBus(1) address = 0x27 digoleClearScreen() digoleWriteCommand("ETP99") digoleWriteText("ROOMI") #NFC Setup i2c_nfc = busio.I2C(board.SCL, board.SDA) reset_pin = DigitalInOut(board.D6) req_pin = DigitalInOut(board.D12) pn532 = PN532_I2C(i2c_nfc, debug=False, reset=reset_pin, req=req_pin) pn532.SAM_configuration() config = { "apiKey": "AIzaSyDnDXIpTdqMeTbVK_6S-XvGpUE4juq0Ge4", "authDomain": "roomi-825d0.firebaseapp.com", "databaseURL": "https://roomi-825d0.firebaseio.com/", "storageBucket": "roomi-825d0.appspot.com" } #- Firebase Init -# firebase = pyrebase.initialize_app(config) auth = firebase.auth()
from digitalio import DigitalInOut, Direction #pylint: disable=import-error import board #pylint: disable=import-error import time pin = 8 led = DigitalInOut(getattr(board, "D" + str(pin))) led = DigitalInOut(board.D8) led.direction = Direction.OUTPUT print("blinky") while True: led.value = True time.sleep(0.1) led.value = False time.sleep(0.1)
import time from board import * from pulseio import * from digitalio import DigitalInOut, Direction, Pull led = DigitalInOut(LED1) led.direction = Direction.OUTPUT # Setup BLUE and RED LEDs as PWM output (default frequency is 500 Hz) ledb = PWMOut(LED2_B) ledr = PWMOut(LED2_R) button = DigitalInOut(SW1) button.direction = Direction.INPUT button.pull = Pull.UP # Set the BLUE LED to have a duty cycle of 5000 (out of 65535, so ~7.5%) ledb.duty_cycle = 5000 # Setup pin A0 as a standard PWM out @ 50% to test on the oscilloscope. # You should see a 50% duty cycle waveform at ~500Hz on the scope when you # connect a probe to pin A0 #a0 = PWMOut(A0) #a0.duty_cycle = int(65535/2) def checkButton(): led.value = button.value # Constantly pulse the RED LED
# Open Spreadsheet beforehand and position to start (A,1) # Use slide switch to start and stop sensor readings # Time values are seconds since board powered on (relative time) import time from digitalio import DigitalInOut, Direction, Pull import analogio import board import usb_hid from adafruit_hid.keyboard import Keyboard from adafruit_hid.keycode import Keycode from adafruit_hid.keyboard_layout_us import KeyboardLayoutUS import adafruit_thermistor # Switch to quickly enable/disable switch = DigitalInOut(board.SLIDE_SWITCH) switch.pull = Pull.UP # light level light = analogio.AnalogIn(board.LIGHT) # temperature thermistor = adafruit_thermistor.Thermistor(board.TEMPERATURE, 10000, 10000, 25, 3950) # Set the keyboard object! # Sleep for a bit to avoid a race condition on some systems time.sleep(1) kbd = Keyboard(usb_hid.devices) layout = KeyboardLayoutUS(kbd) # US is only current option... led = DigitalInOut(board.D13) # Set up red LED "D13"
from digitalio import DigitalInOut import binascii from mopidy_client import play_new_tracks, stop_track from tracks_model import get_track_uris, get_all_track_uris import adafruit_ssd1306 from adafruit_pn532.spi import PN532_SPI logging.info('Starting up') spi = busio.SPI(board.SCK, board.MOSI, board.MISO) SHUFFLE_ALL_TAG = "04a3466a186580" # PN532 SPI connection: pn_cs_pin = DigitalInOut(board.D5) pn532 = PN532_SPI(spi, pn_cs_pin, debug=False) # Configure PN532 to communicate with MiFare cards pn532.SAM_configuration() current_tag = None count_loops_without_tag = 0 COUNT_LOOPS_WITHOUT_TAG_TO_STOP = 4 print('Waiting for RFID/NFC card...') while True: try: # Check if a card is available to read uid = pn532.read_passive_target(timeout=0.5) if uid is not None:
import random # One pixel connected internally! dot = neopixel.NeoPixel(board.NEOPIXEL, 1, brightness=0.08) # pizeo buzzer buzzer = PWMOut(board.D5, variable_frequency=True) buzzer.frequency = 262 OFF = 0 ON = 2**15 # Digital input with pullup on D2, D3, D4, D5, D6 buttons = [] for p in [board.D6, board.D9, board.D10, board.A3, board.A4]: button = DigitalInOut(p) button.direction = Direction.INPUT button.pull = Pull.UP buttons.append(button) # Digital output on D8, D9, D10, D11, D12 buttonLeds = [] for p in [board.D11, board.D12, board.D13, board.A1, board.A2]: buttonLed = DigitalInOut(p) buttonLed.direction = Direction.OUTPUT buttonLeds.append(buttonLed) ######################### HELPERS ##############################
# Import the SSD1306 module. import adafruit_ssd1306 # Import RFM9x radio module import adafruit_rfm9x # Import National Marine Electronics Association Standards import pynmea2 import serial import string import config # Create the I2C interface. i2c = busio.I2C(board.SCL, board.SDA) # 128x32 OLED Display reset_pin = DigitalInOut(board.D4) display = adafruit_ssd1306.SSD1306_I2C(128, 32, i2c, reset=reset_pin) # Clear the display. display.fill(0) display.show() width = display.width height = display.height # Configure LoRa Radio CS = DigitalInOut(board.CE1) RESET = DigitalInOut(board.D25) spi = busio.SPI(board.SCK, MOSI=board.MOSI, MISO=board.MISO) rfm9x = adafruit_rfm9x.RFM9x(spi, CS, RESET, 915.0) # 915 MHz rfm9x.tx_power = 23 # Maximum prev_packet = None
SPRITESHEET_FOLDER = "/bmps" DEFAULT_FRAME_DURATION = 0.1 # 100ms AUTO_ADVANCE_LOOPS = 3 FRAME_DURATION_OVERRIDES = { "three_rings1-sheet.bmp": 0.15, "hop1-sheet.bmp": 0.05, "firework1-sheet.bmp": 0.03, } # --- Display setup --- matrix = Matrix(bit_depth=4) sprite_group = displayio.Group() matrix.display.show(sprite_group) # --- Button setup --- pin_down = DigitalInOut(board.BUTTON_DOWN) pin_down.switch_to_input(pull=Pull.UP) button_down = Debouncer(pin_down) pin_up = DigitalInOut(board.BUTTON_UP) pin_up.switch_to_input(pull=Pull.UP) button_up = Debouncer(pin_up) auto_advance = True file_list = sorted( [ f for f in os.listdir(SPRITESHEET_FOLDER) if (f.endswith(".bmp") and not f.startswith(".")) ] )
from adafruit_esp32spi import adafruit_esp32spi import adafruit_requests as requests from adafruit_io.adafruit_io import IO_HTTP, AdafruitIO_RequestError # 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 # 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) print("Connecting to AP...") while not esp.is_connected: try: esp.connect_AP(secrets["ssid"], secrets["password"])
'Média S3': [], 'Média S1 - x': [], 'Média S1 - y': [], 'Média S2 - x': [], 'Média S2 - y': [], 'Média S3 - x': [], 'Média S3 - y': [], 'Cor': [] }) columns = list(df) ## i2c_address = board.I2C() time.sleep(0.5) xshut = [ DigitalInOut(board.D17), DigitalInOut(board.D22), DigitalInOut(board.D27) ] for power_pin in xshut: power_pin.switch_to_output(value=False) # Variáveis vl53 = [] raio_padrao = 160 #unidade: mm distancia_total = 180 #unidade: mm tolerancia = 3 #unidade mm for i, power_pin in enumerate(xshut):
# import modules import board import time from digitalio import DigitalInOut, Direction, Pull # declare objects and variables led = DigitalInOut(board.A3) led.direction = Direction.OUTPUT ledMode = 0 button = DigitalInOut(board.A1) button.direction = Direction.INPUT button.pull = Pull.DOWN buttonPre = False buttonPressTime = 0 blinkInterval = 0.5 blinkTime = time.monotonic() + blinkInterval # loop forever while True: # gather inputs # see if the button has changed if button.value != buttonPre: # reset the previous value buttonPre = button.value if button.value: # mark the time when the button is pushed buttonPressTime = time.monotonic() else:
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()
ble = BLERadio() hit_status = [color.RED, color.ORANGE, color.AMBER, color.GREEN] pixel = NeoPixel(NEOPIXEL, 1) pulse = Pulse( pixel, speed=0.01, color=color.PURPLE, # Use CYAN for Male Key period=3, min_intensity=0.0, max_intensity=0.5) solid = Solid(pixel, color.GREEN) reed_switch = DigitalInOut(D5) reed_switch.direction = Direction.INPUT reed_switch.pull = Pull.UP amp_enable = DigitalInOut(D6) amp_enable.direction = Direction.OUTPUT amp_enable.value = False def play_tone(): """Generate tone and transmit to I2S amp.""" length = 4000 // 440 sine_wave = array("H", [0] * length) for i in range(length): sine_wave[i] = int(sin(pi * 2 * i / 18) * (2**15) + 2**15)
import board import busio from digitalio import DigitalInOut import adafruit_esp32spi.adafruit_esp32spi_socket as socket from adafruit_esp32spi import adafruit_esp32spi import adafruit_requests as requests print("ESP32 SPI webclient test") TEXT_URL = "http://wifitest.adafruit.com/testwifi/index.html" JSON_URL = "http://api.coindesk.com/v1/bpi/currentprice/USD.json" # 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) requests.set_socket(socket, esp) if esp.status == adafruit_esp32spi.WL_IDLE_STATUS: print("ESP32 found and in idle mode") print("Firmware vers.", esp.firmware_version) print("MAC addr:", [hex(i) for i in esp.MAC_address])
""" import time import board from digitalio import DigitalInOut, Direction, Pull from adafruit_matrixportal.network import Network from adafruit_matrixportal.matrix import Matrix import openweather_graphics # pylint: disable=wrong-import-position # 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 jumper = DigitalInOut(board.D12) jumper.direction = Direction.INPUT jumper.pull = Pull.UP if jumper.value: UNITS = "metric" # can pick 'imperial' or 'metric' as part of URL query print("Jumper set to metric") else: UNITS = "imperial" print("Jumper set to imperial") # Use cityname, country code where countrycode is ISO3166 format. # E.g. "New York, US" or "London, GB" LOCATION = "Los Angeles, US" print("Getting weather for {}".format(LOCATION)) # Set up from where we'll be fetching data
import time import board import busio from digitalio import DigitalInOut import adafruit_requests as requests import neopixel import adafruit_fancyled.adafruit_fancyled as fancy from adafruit_wiznet5k.adafruit_wiznet5k import WIZNET5K import adafruit_wiznet5k.adafruit_wiznet5k_socket as socket cs = DigitalInOut(board.D10) spi_bus = busio.SPI(board.SCK, MOSI=board.MOSI, MISO=board.MISO) # Initialize ethernet interface with DHCP eth = WIZNET5K(spi_bus, cs) # Initialize a requests object with a socket and ethernet interface requests.set_socket(socket, eth) DATA_SOURCE = "http://api.thingspeak.com/channels/1417/feeds.json?results=1" DATA_LOCATION = ["feeds", 0, "field2"] # neopixels pixels = neopixel.NeoPixel(board.NEOPIXEL, 1, brightness=0.3) pixels.fill(0) attempts = 3 # Number of attempts to retry each request failure_count = 0 response = None
# our array of button objects buttons = [] # The keycode sent for each button, will be paired with a control key buttonkeys = [Keycode.A, Keycode.B, "Hello World!\n"] controlkey = Keycode.SHIFT # the keyboard object! # sleep for a bit to avoid a race condition on some systems time.sleep(1) kbd = Keyboard(usb_hid.devices) # we're americans :) layout = KeyboardLayoutUS(kbd) # make all pin objects, make them inputs w/pullups for pin in buttonpins: button = DigitalInOut(pin) button.direction = Direction.INPUT button.pull = Pull.UP buttons.append(button) led = DigitalInOut(board.D13) led.direction = Direction.OUTPUT print("Waiting for button presses") while True: # check each button for button in buttons: if not button.value: # pressed? i = buttons.index(button) print("Button #%d Pressed" % i)
import time import math import board from digitalio import DigitalInOut, Direction, Pull import pwmio from adafruit_lsm6ds.lsm6ds33 import LSM6DS33 from adafruit_lsm6ds import AccelRange, AccelHPF, Rate from adafruit_display_text import label import displayio import terminalio button_a = DigitalInOut(board.BUTTON_A) button_a.direction = Direction.INPUT button_a.pull = Pull.UP splash = displayio.Group(max_size=3) # draw the bad egg! begg_file = open("broken_egg.bmp", "rb") begg_bmp = displayio.OnDiskBitmap(begg_file) begg_sprite = displayio.TileGrid(begg_bmp, pixel_shader=displayio.ColorConverter()) splash.append(begg_sprite) # draw the good egg on top gegg_file = open("good_egg.bmp", "rb") gegg_bmp = displayio.OnDiskBitmap(gegg_file) gegg_sprite = displayio.TileGrid(gegg_bmp, pixel_shader=displayio.ColorConverter()) splash.append(gegg_sprite)
# so NeoPixel does not light if powered by USB alone BLACK = (0, 0, 0) RED = (255, 0, 0) GREEN = (0, 255, 0) BLUE = (0, 0, 255) YELLOW = (255, 255, 0) ORANGE = (173, 9, 0) pixels = neopixel.NeoPixel(board.D5, 1, brightness=0.2, auto_write=False, pixel_order=neopixel.GRB) # setup pins for ItsyBitsy Airlift: esp32_cs = DigitalInOut(board.D13) esp32_ready = DigitalInOut(board.D11) esp32_reset = DigitalInOut(board.D12) spi = busio.SPI(board.SCK, board.MOSI, board.MISO) esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset) # setup onboard status light for ItsyBitsy M4 status_light = adafruit_dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1, brightness=0.2) # then initialize wife manager wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager( esp, secrets, status_light)
class HCSR04: """Control a HC-SR04 ultrasonic range sensor. Example use: :: import time import board import adafruit_hcsr04 sonar = adafruit_hcsr04.HCSR04(trigger_pin=board.D2, echo_pin=board.D3) while True: try: print((sonar.distance,)) except RuntimeError: print("Retrying!") pass time.sleep(0.1) """ def __init__(self, trigger_pin, echo_pin, *, timeout=0.1): """ :param trigger_pin: The pin on the microcontroller that's connected to the ``Trig`` pin on the HC-SR04. :type trig_pin: microcontroller.Pin :param echo_pin: The pin on the microcontroller that's connected to the ``Echo`` pin on the HC-SR04. :type echo_pin: microcontroller.Pin :param float timeout: Max seconds to wait for a response from the sensor before assuming it isn't going to answer. Should *not* be set to less than 0.05 seconds! """ self._timeout = timeout self._trig = DigitalInOut(trigger_pin) self._trig.direction = Direction.OUTPUT if _USE_PULSEIO: self._echo = PulseIn(echo_pin) self._echo.pause() self._echo.clear() else: self._echo = DigitalInOut(echo_pin) self._echo.direction = Direction.INPUT def __enter__(self): """Allows for use in context managers.""" return self def __exit__(self, exc_type, exc_val, exc_tb): """Automatically de-initialize after a context manager.""" self.deinit() def deinit(self): """De-initialize the trigger and echo pins.""" self._trig.deinit() self._echo.deinit() @property def distance(self): """Return the distance measured by the sensor in cm. This is the function that will be called most often in user code. The distance is calculated by timing a pulse from the sensor, indicating how long between when the sensor sent out an ultrasonic signal and when it bounced back and was received again. If no signal is received, we'll throw a RuntimeError exception. This means either the sensor was moving too fast to be pointing in the right direction to pick up the ultrasonic signal when it bounced back (less likely), or the object off of which the signal bounced is too far away for the sensor to handle. In my experience, the sensor can detect objects over 460 cm away. :return: Distance in centimeters. :rtype: float """ return self._dist_two_wire() # at this time we only support 2-wire meausre def _dist_two_wire(self): if _USE_PULSEIO: self._echo.clear() # Discard any previous pulse values self._trig.value = True # Set trig high time.sleep(0.00001) # 10 micro seconds 10/1000/1000 self._trig.value = False # Set trig low pulselen = None timestamp = time.monotonic() if _USE_PULSEIO: self._echo.resume() while not self._echo: # Wait for a pulse if (time.monotonic() - timestamp) > self._timeout: self._echo.pause() raise RuntimeError("Timed out") self._echo.pause() pulselen = self._echo[0] else: # OK no hardware pulse support, we'll just do it by hand! # hang out while the pin is low while not self._echo.value: if time.monotonic() - timestamp > self._timeout: raise RuntimeError("Timed out") timestamp = time.monotonic() # track how long pin is high while self._echo.value: if time.monotonic() - timestamp > self._timeout: raise RuntimeError("Timed out") pulselen = time.monotonic() - timestamp pulselen *= 1000000 # convert to us to match pulseio if pulselen >= 65535: raise RuntimeError("Timed out") # positive pulse time, in seconds, times 340 meters/sec, then # divided by 2 gives meters. Multiply by 100 for cm # 1/1000000 s/us * 340 m/s * 100 cm/m * 2 = 0.017 return pulselen * 0.017
""" This example is for use on (Linux) computers that are using CPython with Adafruit Blinka to support CircuitPython libraries. CircuitPython does not support PIL/pillow (python imaging library)! """ import time import random from colorsys import hsv_to_rgb import board from digitalio import DigitalInOut, Direction from PIL import Image, ImageDraw, ImageFont import adafruit_rgb_display.st7789 as st7789 # Create the display cs_pin = DigitalInOut(board.CE0) dc_pin = DigitalInOut(board.D25) reset_pin = DigitalInOut(board.D24) BAUDRATE = 24000000 spi = board.SPI() disp = st7789.ST7789( spi, height=240, y_offset=80, rotation=180, cs=cs_pin, dc=dc_pin, rst=reset_pin, baudrate=BAUDRATE, )
sky_blue = [0, 120, 135] idle_color = [70, 243, 70] hit_color = [150, 20, 00] # One pixel connected internally! dot = dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, n=1, brightness=0.2) dot[0] = sky_blue led = digitalio.DigitalInOut(board.D13) led.direction = digitalio.Direction.OUTPUT # Digital input with pullup on D0 PIR1 = DigitalInOut(board.D0) PIR1.direction = Direction.INPUT PIR1.pull = Pull.DOWN # Digital input with pullup on D2 PIR2 = DigitalInOut(board.D2) PIR2.direction = Direction.INPUT PIR2.pull = Pull.DOWN f_PIR1 = PIR1.value f_PIR2 = PIR2.value while True: time.sleep(0.5)
#set up the neopixels pixels = neopixel.NeoPixel( board.NEOPIXEL, 10, brightness=pixelBrightness ) #determine beightness (Value can be between 0 and 1) # # # # Program the two buttons on the board to be able to move up and down pitches # # # buttonD = DigitalInOut(board.BUTTON_A) #button a is the down button buttonD.direction = Direction.INPUT buttonD.pull = Pull.DOWN buttonU = DigitalInOut(board.BUTTON_B) # button b is the up button buttonU.direction = Direction.INPUT buttonU.pull = Pull.DOWN # # # # enable the speaker # # #
import board import array import time from digitalio import DigitalInOut, Direction, Pull import pulseio ############## Switch to select 'stealth-mode' switch = DigitalInOut(board.SLIDE_SWITCH) switch.direction = Direction.INPUT switch.pull = Pull.UP # Button to see output debug led = DigitalInOut(board.D13) led.direction = Direction.OUTPUT ############## Speaker as haptic feedback spkr_en = DigitalInOut(board.SPEAKER_ENABLE) spkr_en.direction = Direction.OUTPUT spkr_en.value = False spkr = DigitalInOut(board.SPEAKER) spkr.direction = Direction.OUTPUT ############## Allow any button to trigger activity! button_a = DigitalInOut(board.BUTTON_A) button_a.direction = Direction.INPUT button_a.pull = Pull.DOWN button_b = DigitalInOut(board.BUTTON_B) button_b.direction = Direction.INPUT button_b.pull = Pull.DOWN pwm = pulseio.PWMOut(board.REMOTEOUT, frequency=38000, duty_cycle=2 ** 15, variable_frequency=True)
# command interpreter for CircuitPython 4.x import board import pulseio import supervisor import sys from time import sleep from adafruit_motor import servo from digitalio import DigitalInOut, Direction, Pull led13 = DigitalInOut(board.D13) led13.direction = Direction.OUTPUT # create a PWMOut object on M4 Pin A1. pwm = pulseio.PWMOut(board.A1, duty_cycle=2**15, frequency=50) # For Gemma M0, Trinket M0, Metro M0 Express, ItsyBitsy M0 Express, Itsy M4 Express switch = DigitalInOut(board.D2) switch.direction = Direction.INPUT switch.pull = Pull.UP # Create a servo object, my_servo. my_servo = servo.Servo(pwm) angle_open = 10 angle_closed = 150 btm_pushed = 'pushed' btm_pushed_not = 'not pushed' state_btm01 = btm_pushed_not led13.value = False node_name = 'Node1'
# Author: Tony DiCola # License: Public Domain # Import all board pins. import time import board import busio from digitalio import DigitalInOut # Import the SSD1306 module. import adafruit_ssd1306 # Create the I2C interface. i2c = busio.I2C(board.SCL, board.SDA) # A reset line may be required if there is no auto-reset circuitry reset_pin = DigitalInOut(board.D5) # Create the SSD1306 OLED class. # The first two parameters are the pixel width and pixel height. Change these # to the right size for your display! # The I2C address for these displays is 0x3d or 0x3c, change to match # A reset line may be required if there is no auto-reset circuitry display = adafruit_ssd1306.SSD1306_I2C(128, 32, i2c, addr=0x3C, reset=reset_pin) print("Framebuf capability test - these are slow and minimal but don't require" "a special graphics management library, only `adafruit_framebuf`")
from sys import stdin, stdout from time import sleep import board import neopixel from digitalio import DigitalInOut, Direction, Pull from supervisor import runtime from cpgame import after, cancel, every, on, start from colors import RED, ORANGE, GREEN, YELLOW, BLUE, VIOLET, WHITE, OFF pixels = neopixel.NeoPixel(board.NEOPIXEL, 10, brightness=0.02, auto_write=True) pixels.fill(OFF) pixels.show() WAIT = DigitalInOut(board.D7) WAIT.direction = Direction.INPUT WAIT.pull = Pull.UP LED = DigitalInOut(board.D13) LED.direction = Direction.OUTPUT STATUS = 9 class state: active = 0 handshake = 0 data = "" def send(cmd):