Exemple #1
0
"""
Read Signature Test - All this does is read the signature from the chip to
check connectivity!
"""

import board
import busio
import pulseio
import adafruit_avrprog

spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
avrprog = adafruit_avrprog.AVRprog()
avrprog.init(spi, board.D5)

#pylint: disable-msg=no-member
# we can generate an 6 MHz clock for driving bare chips too!
clock_pwm = pulseio.PWMOut(board.D9, frequency=6000000, duty_cycle=65536 // 2)
#pylint: enable-msg=no-member

avrprog.begin()
print("Signature bytes: ", [hex(i) for i in avrprog.read_signature()])
avrprog.end()
Exemple #2
0
"""
Photosensor -> LED

================================================="""

import analogio
import board
import pulseio
from simpleio import map_range

LED = pulseio.PWMOut(board.D9)
LIGHT = analogio.AnalogIn(board.A0)

while True:
    LIGHT_VAL = map_range(LIGHT.value, 20000, 32766, 0, 32766)
    LED.duty_cycle = int(LIGHT_VAL)
Exemple #3
0
    Change the velocity variable below and re-upload
    the program to change the speed.
"""

# Velocity setting: Can be a number between -1.0 and 1.0
velocity = 1.0

# Continuous Servo Test Program for CircuitPython
import time
import board
import pulseio
from adafruit_motor import servo

print("Initialize Servo")
# create a PWMOut object on Pin A2.
pwm = pulseio.PWMOut(board.A2, frequency=50)

# Create a servo object, my_servo.
my_servo = servo.ContinuousServo(pwm)

# Check velocity
if velocity > 1.0: velocity = 1.0
if velocity < -1.0: velocity = -1.0

# Start movement
print("Starting Movement")
my_servo.throttle = velocity

# This should run the servo continuously. If the program aborts
# and stops the movement you might have to add the following lines.
#while True:
Exemple #4
0
#import statements
import time
import board
import pulseio
from adafruit_motor import servo

# create a PWMOut object on Pin A2.
# can change inputs board.A1 etc.
pwm1 = pulseio.PWMOut(board.D13, duty_cycle=2**15, frequency=50)
pwm2 = pulseio.PWMOut(board.D12, duty_cycle=2**15, frequency=50)
pwm3 = pulseio.PWMOut(board.D10, duty_cycle=2**15, frequency=50)
pwm4 = pulseio.PWMOut(board.D5, duty_cycle=2**15, frequency=50)

# Create a servo object, my_servo.
lowLeft = servo.Servo(pwm1)
lowRight = servo.Servo(pwm2)
upRight = servo.Servo(pwm3)
upLeft = servo.Servo(pwm4)


def dance5():
    # set position to forward facing
    lowLeft.angle = 90  # set left foot angle
    lowRight.angle = 90  # set right foot angle
    upLeft.angle = 90  # set left knee angle
    upRight.angle = 90  # set right knee angle
    time.sleep(1)  # sleep for 1 second
    while True:
        count = 0
        # this dance makes it shift backwards
        while count < 5:
Exemple #5
0
ROTATE_RIGHT = 0x03
FORWARD = 0x04
FORWARD_LEFT = 0x05
FORWARD_RIGHT = 0x06
REVERSE = 0x07
REVERSE_LEFT = 0x08
REVERSE_RIGHT = 0x09

TRANSMIT_DELAY = 0.1

# Setup accelerometer
i2c = busio.I2C(board.ACCELEROMETER_SCL, board.ACCELEROMETER_SDA)
sensor = adafruit_lis3dh.LIS3DH_I2C(i2c, address=0x19)

# Create a 'pulseio' output, to send infrared signals on the IR transmitter @ 38KHz
pwm = pulseio.PWMOut(board.IR_TX, frequency=38000, duty_cycle=2 ** 15)
pulseout = pulseio.PulseOut(pwm)

# Create an encoder that will take numbers and turn them into IR pulses
encoder = adafruit_irremote.GenericTransmit(header=[9500, 4500],
                                            one=[550, 550],
                                            zero=[550, 1700],
                                            trail=0)

def log(s):
    """Optionally output some text.
    :param string s: test to output
    """
    if DEBUG_LOG:
        print(s)
i2c = busio.I2C(board.SCL, board.SDA)
rtc = adafruit_ds3231.DS3231(i2c)

audio = audioio.AudioOut(board.A0)

strip = neopixel.NeoPixel(NEOPIXEL_PIN,
                          NUM_PIXELS,
                          brightness=1,
                          auto_write=False)
strip.fill(0)  # NeoPixels off ASAP on startup
strip.show()

switch = Debouncer(SWITCH_PIN, Pull.UP, 0.01)

# create a PWMOut object on Pin A2.
pwm = pulseio.PWMOut(SERVO_PIN, duty_cycle=2**15, frequency=50)

# Create a servo object, my_servo.
servo = servo.ContinuousServo(pwm)
servo.throttle = 0.0

# Set the time for testing
# Once finished testing, the time can be set using the REPL using similar code
if TESTING:
    #                     year, mon, date, hour, min, sec, wday, yday, isdst
    t = time.struct_time((2018, 12, 31, 23, 58, 55, 1, -1, -1))
    # you must set year, mon, date, hour, min, sec and weekday
    # yearday is not supported, isdst can be set but we don't do anything with it at this time
    print("Setting time to:", t)
    rtc.datetime = t
    print()
Exemple #7
0
import time
import board
import digitalio
import pulseio
from adafruit_debouncer import Debouncer

from adafruit_ble import BLERadio
from adafruit_ble.advertising.standard import ProvideServicesAdvertisement
from adafruit_ble.services.nordic import UARTService

led = pulseio.PWMOut(board.P0_13, frequency=5000, duty_cycle=65535)

button_pin = digitalio.DigitalInOut(board.P0_11)
button_pin.direction = digitalio.Direction.INPUT
button_pin.pull = digitalio.Pull.UP
button = Debouncer(button_pin)

connected_led = digitalio.DigitalInOut(board.P0_14)
connected_led.direction = digitalio.Direction.OUTPUT

ble = BLERadio()
uart_service = UARTService()
advertisement = ProvideServicesAdvertisement(uart_service)

PI_SEND_INTERVAL = 1
PWM_INDICATE_BLINK_INTERVAL = 0.25
PWM_INDICATE_BLINKS = 5


# From https://rosettacode.org/wiki/Pi#Python
def calcPi():
Exemple #8
0
    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 = (320, 240)  # 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=(320, 240))
            # 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()
# Jude Fairchild
# Servo Touch
# 8/26/19

import time  #pylint: disable-msg=import-error
import board  #pylint: disable-msg=import-error
import pulseio  #pylint: disable-msg=import-error
from adafruit_motor import servo  #pylint: disable-msg=import-error
import touchio  #pylint: disable-msg=import-error
import digitalio  #pylint: disable-msg=import-error

pwm = pulseio.PWMOut(board.D9, duty_cycle=2**15,
                     frequency=50)  # create a PWMOut object on Pin A2.

my_servo = servo.Servo(pwm)  # Create a servo object, my_servo.

Servo_Angle = 0

touch_A1 = touchio.TouchIn(board.A1)  # Not a touch pin on Trinket M0!
touch_A2 = touchio.TouchIn(board.A2)

while True:

    if touch_A1.value and Servo_Angle < 180:  #Stating that that if the wire connected to A1 is touched and it is less than 180, it will turn the servo
        print("Touched A1!")  # Prints to the Serial Monitor
        Servo_Angle += 1  # Turns the angle by a designated variable which for me is 1
        my_servo.angle = Servo_Angle  # Sets my variable "Servo_Angle" to the actual servo variable

    time.sleep(0.001)

    if touch_A2.value and Servo_Angle > 0:
# Magic 9 Ball
# Turn HalloWing face down and then face up to change images at random
# place 128 x 128 pixel 24-bit .bmp images at root level of HalloWing

import time
import os
import random
import board
import displayio
import pulseio
import busio
import adafruit_lis3dh

backlight = pulseio.PWMOut(board.TFT_BACKLIGHT)
splash = displayio.Group()
board.DISPLAY.show(splash)

max_brightness = 2**15
SENSITIVITY = 5  # reading in Z direction to trigger, adjustable

images = list(filter(lambda x: x.endswith("bmp"), os.listdir("/")))

i = random.randint(0, (len(images) - 1))  # initial image is randomly selected

# Set up accelerometer on I2C bus, 4G range:
I2C = busio.I2C(board.SCL, board.SDA)

ACCEL = adafruit_lis3dh.LIS3DH_I2C(I2C, address=0x18)

ACCEL.range = adafruit_lis3dh.RANGE_4_G
# import modules
import time
import board
import pulseio

# make a led object with pulseio.PWMOut on pin board.A1
led = pulseio.PWMOut(board.A1, duty_cycle=0)

fadeInc = 1000

newDutyCycle = 0
"""
pulseio.PWMOut creates a PWMOut object with the name led

you can set the duty_cycle with the property led.duty_cycle

led.duty_cycle accepts a 16-bit integer value from 0 - 65535
"""

# loop forever
while True:
    newDutyCycle += fadeInc

    if newDutyCycle > 65535:
        newDutyCycle = 65535
        fadeInc = -1000
    elif newDutyCycle < 0:
        newDutyCycle = 0
        fadeInc = 1000

    led.duty_cycle = newDutyCycle
import time
import board
import pulseio
import touchio
from adafruit_motor import servo

# create a PWMOut object on Pin D8.
pwm = pulseio.PWMOut(board.D8, duty_cycle=2**15, frequency=50)

touch_A1 = touchio.TouchIn(board.A1)
touch_A2 = touchio.TouchIn(board.A2)

my_servo = servo.Servo(pwm)  # Create a servo object, my_servo.

while True:
    if touch_A1.value:  # Look at me, im a comment!
        print("Touched A1!")
    if touch_A2.value:
        print("Touched A2!")
    time.sleep(0.05)
Exemple #13
0
import board
from digitalio import DigitalInOut, Direction, Pull
import pulseio
import simpleio
from adafruit_dotstar import DotStar
import time
import random

dotstar = DotStar(board.APA102_SCK, board.APA102_MOSI, 1, brightness=0.3)
led = DigitalInOut(board.D13)
led.direction = Direction.OUTPUT
rightEye = DigitalInOut(board.D0)
leftEye = DigitalInOut(board.D3)
sensor = DigitalInOut(board.D4)
piezo = pulseio.PWMOut(board.D2,
                       duty_cycle=0,
                       frequency=250,
                       variable_frequency=True)
rightEye.direction = Direction.OUTPUT
leftEye.direction = Direction.OUTPUT
sensor.direction = Direction.INPUT
sensor.pull = Pull.UP

loopCount = 0

rightEye.value = True
leftEye.value = True

dotstar[0] = (0, 0, 255)


def moved():
Exemple #14
0
 def on(self):
     # No IR Out without an extra capacitor on the power supply
     self.irtx = pulseio.PWMOut(board.IR_TX,
                                frequency=38000,
                                duty_cycle=2**15)
     self.irout = pulseio.PulseOut(self.irtx)
Exemple #15
0
import board
import pulseio

OFF = 0
ON = 2**15

buzzer = pulseio.PWMOut(board.D4, variable_frequency=True)  # Using Pin D4
buzzer.duty_cycle = ON  # TURN THE BUZZER ON OR OFF
buzzer.frequency = 2000
Exemple #16
0
#button_a = digitalio.DigitalInOut(board.D2) # GrandCentral
button_a = digitalio.DigitalInOut(board.D4)  # CPX
button_a.direction = digitalio.Direction.INPUT
button_a.pull = digitalio.Pull.UP  # GrandCentral
button_a.pull = digitalio.Pull.DOWN  # CPX

#button_b = digitalio.DigitalInOut(board.D3) # GrandCentral
button_b = digitalio.DigitalInOut(board.D5)  # CPX
button_b.direction = digitalio.Direction.INPUT
#button_b.pull = digitalio.Pull.UP # GrandCentral
button_b.pull = digitalio.Pull.DOWN  # CPX

#led = digitalio.DigitalInOut(board.D9)
#led.direction = digitalio.Direction.OUTPUT
#pwm = pulseio.PWMOut(board.D9, frequency=50)    # GrandCentral M4
pwm = pulseio.PWMOut(board.D13, frequency=50)  # CPX

pwm.duty_cycle = 0
brightness = 0
step = 2048

while True:
    #    print ( str(button_a.value) + ' ' +  str(button_b.value) )
    if (button_a.value == True):  # active high in CPX version
        brightness += step
        if (brightness > 65535):
            brightness = 65535

    if (button_b.value == True):  # active high in CPX version
        brightness -= step
        if (brightness < 0):
Exemple #17
0
    def __init__(self, *, url=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,
                 image_json_path=None, image_resize=None, image_position=None,
                 caption_text=None, caption_font=None, caption_position=None,
                 caption_color=0x808080,
                 success_callback=None, debug=False):

        self._debug = debug

        try:
            self._backlight = pulseio.PWMOut(board.TFT_BACKLIGHT)  # pylint: disable=no-member
        except ValueError:
            self._backlight = None
        self.set_backlight(1.0)  # turn on backlight

        self._url = url
        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)
                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)
        self.audio = audioio.AudioOut(board.AUDIO_OUT)
        try:
            self.play_file("pyportal_startup.wav")
        except OSError:
            pass # they deleted the file, no biggie!

        # Make ESP32 connection
        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_interface(self._esp)

        if url and not self._uselocal:
            self._connect_esp()

        # 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

        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

        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")
        # 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=(320, 240))
        # pylint: enable=no-member

        self.set_backlight(1.0)  # turn on backlight

        gc.collect()
Exemple #18
0
from simpleio import map_range
import adafruit_dotstar as dotstar
import time
import pulseio

print("stringcar 2018-03-24 v07.py")

# set up dotstar indicator output
dot = dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1, brightness=0.3)

# set up busy indicator output (red LED)
busy = DigitalInOut(board.D13)
busy.direction = Direction.OUTPUT

# set up motor controller outputs
ain01 = pulseio.PWMOut(board.D3, frequency=1900, duty_cycle=0)
ain02 = pulseio.PWMOut(board.D4, frequency=1900, duty_cycle=0)

# set up EOS sensor switch input
sensor_eos = DigitalInOut(board.D2)
sensor_eos.direction = Direction.INPUT
sensor_eos.pull = Pull.UP

# set up potentiometer control input
ctl = AnalogIn(board.D1)

# set up piezo output
piezo = pulseio.PWMOut(board.D0,
                       duty_cycle=0,
                       frequency=440,
                       variable_frequency=True)
Exemple #19
0
import displayio
import adafruit_miniqr
import board
import pulseio
import busio
import microcontroller as m
import time
from analogio import AnalogIn
import array

from digitalio import DigitalInOut, Direction, Pull
#backlight = DigitalInOut(board.TFT_BACKLIGHT)
#backlight.direction = Direction.OUTPUT
#backlight.value = False

pwm = pulseio.PWMOut(board.TFT_BACKLIGHT)
pwm.duty_cycle = 0  #65535-16000

display = board.DISPLAY


def bitmap_qr(matrix):
    """The QR code bitmap."""
    border_pixels = 2
    bitmap = displayio.Bitmap(matrix.width + 2 * border_pixels,
                              matrix.height + 2 * border_pixels, 2)
    for y in range(matrix.height):
        for x in range(matrix.width):
            if matrix[x, y]:
                bitmap[x + border_pixels, y + border_pixels] = 1
            else:
"""CircuitPython Essentials PWM pin identifying script"""
import board
import pulseio

for pin_name in dir(board):
    pin = getattr(board, pin_name)
    try:
        p = pulseio.PWMOut(pin)
        p.deinit()
        print("PWM on:", pin_name)  # Prints the valid, PWM-capable pins!
    except ValueError:  # This is the error returned when the pin is invalid.
        print("No PWM on:", pin_name)  # Prints the invalid pins.
    except RuntimeError:  # Timer conflict error.
        print("Timers in use:", pin_name)  # Prints the timer conflict pins.
    except TypeError:  # Error returned when checking a non-pin object in dir(board).
        pass  # Passes over non-pin objects in dir(board).
Exemple #21
0
import time
import board
import pulseio

led = pulseio.PWMOut(board.PWM0, frequency=5000, duty_cycle=0)

while True:
    for i in range(100):
        # PWM LED up and down
        if i < 50:
            led.duty_cycle = int(i * 2 * 65535 / 100)  # Up
        else:
            led.duty_cycle = 65535 - int((i - 50) * 2 * 65535 / 100)  # Down
        time.sleep(0.01)
'temp_value_alarm.py'.

=================================================
sounds an alarm when the temp_value crosses a threshold
requires:
- simpleio
"""

import time
import analogio
import pulseio
import board
from simpleio import map_range

piezo = pulseio.PWMOut(board.D8,
                       frequency=440,
                       duty_cycle=0,
                       variable_frequency=True)
tmp36 = analogio.AnalogIn(board.A0)

freeze_temp = 0
boiling_temp = 100

while True:
    temp_value = map_range(tmp36.value, 0, 65535, 0, 5)
    # temp to degrees C
    temp_value = (temp_value - .5) * 100
    print(temp_value)

    if temp_value < freeze_temp:
        piezo.duty_cycle = 30000
    if temp_value > boiling_temp:
from simpleio import map_range
import adafruit_dotstar as dotstar
import time
import pulseio

print("stringcar 2020-09-05 v08.py")

# set up dotstar indicator output (GBR orientation)
dot = dotstar.DotStar(board.DOTSTAR_CI, board.DOTSTAR_DI, 1, brightness=0.5)

# set up busy indicator output (red LED)
busy = DigitalInOut(board.LED_STATUS)
busy.direction = Direction.OUTPUT

# set up motor controller outputs
ain01 = pulseio.PWMOut(board.MOTOR_OUT_1, frequency=25, duty_cycle=0)
ain02 = pulseio.PWMOut(board.MOTOR_OUT_2, frequency=25, duty_cycle=0)

# set up EOS sensor switch input
sensor_eos = DigitalInOut(board.SENSOR_IN)
sensor_eos.direction = Direction.INPUT
sensor_eos.pull = Pull.UP

# Analog input on VOLTAGE_MONITOR
v_plus = AnalogIn(board.VOLTAGE_MONITOR)

# set up potentiometer control input
#ctl = AnalogIn(board.D1)

# set up piezo output
piezo = pulseio.PWMOut(board.PIEZO,
spi_clock = digitalio.DigitalInOut(board.SCK)
spi_clock.direction = digitalio.Direction.OUTPUT
spi_mosi = digitalio.DigitalInOut(board.MOSI)
spi_mosi.direction = digitalio.Direction.OUTPUT
spi_miso = digitalio.DigitalInOut(board.MISO)
spi_miso.direction = digitalio.Direction.INPUT

# print((42 * '*') + "\n" + "init busio.SPI")
# spi = busio.SPI(board.SCK, MOSI=board.MOSI, MISO=board.MISO)
print("init bitbangio.SPI")
spi = bitbangio.SPI(board.SCK, MOSI=board.MOSI, MISO=board.MISO)

# maximum frequency is currently hardcoded to 6MHz
# https://github.com/adafruit/circuitpython/blob/master/ports/atmel-samd/common-hal/pulseio/PWMOut.c#L119
gsclk_freqency = (6000 * 1000)  # 6MHz
gsclk = pulseio.PWMOut(board.D9, duty_cycle=(2**15), frequency=gsclk_freqency)
print("gsclk.frequency: {:}MHz".format(gsclk.frequency / (1000 * 1000)))

latch = digitalio.DigitalInOut(board.D7)
latch.direction = digitalio.Direction.OUTPUT

##########################################
print(42 * '*')
print("define pixel array / init TLC5957")
rows = 4
cols = 4
num_leds = rows * cols
pixels = slight_tlc5957.TLC5957(spi=spi,
                                latch=latch,
                                gsclk=gsclk,
                                spi_clock=spi_clock,
Exemple #25
0
from rtttl import RTTTL
import songs

import board
import pulseio
import time

speaker_pin = board.D0  # Speaker is connected to this DIGITAL pin

# Initialize input/output pins
pwm = pulseio.PWMOut(speaker_pin, variable_frequency=True, duty_cycle=0)


def play_tone(freq, msec):
    #    print('freq = {:6.1f} msec = {:6.1f}'.format(freq, msec))
    if freq > 0:
        pwm.frequency = int(freq)  # Set frequency
        pwm.duty_cycle = 32767  # 50% duty cycle
        time.sleep(msec * 0.001)  # Play for a number of msec
    pwm.duty_cycle = 0  # Stop playing
    time.sleep(0.05)  # Delay 50 ms between notes


tune = RTTTL(songs.find('Super Mario - Main Theme'))

for freq, msec in tune.notes():
    play_tone(freq, msec)
Exemple #26
0
import time

import board
import pulseio
from digitalio import DigitalInOut, Direction

# PWM (fading) LEDs are connected on D0 (PWM not avail on D1)
pwm_leds = board.D0
pwm = pulseio.PWMOut(pwm_leds, frequency=1000, duty_cycle=0)

# digital LEDs connected on D2
digital_leds = DigitalInOut(board.D2)
digital_leds.direction = Direction.OUTPUT
brightness = 0  # how bright the LED is
fade_amount = 4000  # 2% steping of 2^16
counter = 0  # counter to keep track of cycles

while True:

    # And send to LED as PWM level
    pwm.duty_cycle = brightness

    # change the brightness for next time through the loop:
    brightness = brightness + fade_amount

    print(brightness)

    # reverse the direction of the fading at the ends of the fade:
    if brightness <= 0:
        fade_amount = -fade_amount
        counter += 1
Exemple #27
0
keyPressed = False

# IR setup
pulsein = pulseio.PulseIn(board.D12, maxlen=120, idle_state=True)
decoder = adafruit_irremote.GenericDecode()

# size must match what you are decoding! for NEC use 4
received_code = bytearray(4)

# Docs for adafruit_irremote: (https://circuitpython.readthedocs.io/projects/irremote/en/latest/api.html#implementation-notes)
# Article for IR Apple Remote Code: https://www.hackster.io/BlitzCityDIY/circuit-python-ir-remote-for-apple-tv-e97ea0
# IR Test Code (Apple Remote): https://github.com/BlitzCityDIY/Circuit-Python-Apple-TV-IR-Remote/blob/master/ciruitPython_appleTv_IR-Remote
# pwm out test
OKAY = bytearray(b'\x88\x1e\xc5 ')  # decoded [136, 30, 197, 32]
ir_transmitter = adafruit_irremote.GenericTransmit((9050, 4460), (550, 1650), (570, 575), 575)
ir_transmitter_pwm = pulseio.PWMOut(board.D11, frequency=38000, duty_cycle=2 ** 15)

# ----------------------------------------------------------------------------------
""" Functions """


def check_keypresses():
    global remote_keypad, keyPressed, key_pressed_dict

    # this will be a list of returned keys'; [..., ...]
    keys = keypad.pressed_keys

    # if we have any keys, then loop over the key names
    if keys:
        keyPressed = True
Exemple #28
0
import time
import board
import pulseio
from adafruit_motor import servo

# create a PWMOut object on Pin PWM3.
pwm = pulseio.PWMOut(board.PWM3, duty_cycle=0, frequency=50)

# Create a servo object, my_servo.
my_servo = servo.Servo(pwm)

while True:
    for angle in range(0, 180, 5):  # 0 - 180 degrees, 5 degrees at a time.
        my_servo.angle = angle
        time.sleep(0.05)
    for angle in range(180, 0, -5): # 180 - 0 degrees, 5 degrees at a time.
        my_servo.angle = angle
        time.sleep(0.05)
Exemple #29
0
except Exception as e:
    print(e)
    print(
        "You probably don't have a pms5003 connected, continuing without particulate logging"
    )
    is_pms5003 = False

# set up connection with the ltr559
i2c_dev = not_SMBus(I2C=i2c)
ltr559 = LTR559(i2c_dev=i2c_dev)

# setup screen
screen = screen.Screen(backlight_control=False)

# define our pwm pin (for changing the screen brightness)
pwm = pulseio.PWMOut(pimoroni_physical_feather_pins.pin21())

# start the screen at 50% brightness
pwm.duty_cycle = 2**15

# set up mic input
mic = analogio.AnalogIn(pimoroni_physical_feather_pins.pin8())

# colours for the plotter are defined as rgb values in hex, with 2 bytes for each colour
red = 0xFF0000
green = 0x00FF00
blue = 0x0000FF

# Setup bme280 screen plotter
# the max value is set to 70 as it is the screen height in pixels after the labels (top_space) (this is just to make a calculation later on easier)
bme280_splotter = plotter.ScreenPlotter([red, green, blue, red + green + blue],
Exemple #30
0
import time
import board
import pulseio
from adafruit_motor import servo

# SERVO ORIENTATION

# BOTTOMS / towards 0, \ towards 180
# TOPS Counter clockwise towards 0 (right leg in, left leg out), v.v for 180

# calibrated angle for the leg
true90top = 97
true90bottom = 87

# create a PWMOut object on Pin A2.
d10 = pulseio.PWMOut(board.D10, duty_cycle=2**15, frequency=50)
d11 = pulseio.PWMOut(board.D11, duty_cycle=2**15, frequency=50)
d9 = pulseio.PWMOut(board.D9, duty_cycle=2**15, frequency=50)
d7 = pulseio.PWMOut(board.D7, duty_cycle=2**15, frequency=50)

# Create a servo object, my_servo.
LT = servo.Servo(d11)
LB = servo.Servo(d9)
RT = servo.Servo(d10)
RB = servo.Servo(d7)


# reset servos to their default angle.
def resetServo():
    LT.angle = true90top
    time.sleep(0.5)