def __init__(self, enButtons=True): self._buttonA = None self._buttonB = None self._enbuttons = False if enButtons: self._enbuttons = True self._buttonA = DigitalInOut(board.IO43) self._buttonA.switch_to_input(pull=Pull.UP) self._db_buttonA = Debouncer(self._buttonA, 0.01, True) self._buttonB = DigitalInOut(board.IO44) self._buttonB.switch_to_input(pull=Pull.UP) self._db_buttonB = Debouncer(self._buttonB, 0.01, True) # 3x Neopixels RGB pixels: IO0 self._pixels = neopixel.NeoPixel( board.IO0, 3, \ brightness=0.5, auto_write=False, pixel_order=neopixel.GRB ) self._colors = [(255, 0, 0), (0, 255, 0), (0, 0, 255)] for i in range(3): self._pixels[i] = self._colors[i] self._pixels.show() self._pixelsRotationDt = 0.2 self._pixelsRotationSt = time.monotonic() # Sense color Sensor (颜色传感器): IO7 self._colorSensor = AnalogIn(board.IO7) # Lighting Sensor (光强度传感器): IO8--leftLightSensor, IO9--rightLightSensor self._leftLightSensor = AnalogIn(board.IO8) self._rightLightSensor = AnalogIn(board.IO9) # left and right head-LED: IO17--rightHeadLED, IO18--leftHeadLED self._leftHeadLED = DigitalInOut(board.IO18) self._leftHeadLED.direction = Direction.OUTPUT self._leftHeadLED.value = 0 self._rightHeadLED = DigitalInOut(board.IO17) self._rightHeadLED.direction = Direction.OUTPUT self._rightHeadLED.value = 0 # Ultrasonic module (超声波模块): IO11--trig, IO10--echo self._timeout = 0.1 self._trig = DigitalInOut(board.IO11) self._trig.direction = Direction.OUTPUT self._trig.value = 0 if _USE_PULSEIO: self._echo = PulseIn(board.IO10) self._echo.pause() self._echo.clear() else: self._echo = DigitalInOut(board.IO10) self._echo.direction = Direction.INPUT # Tracking sensors (循迹传感器): IO4--rightTracker, IO3--rightTracker self._leftTracker = DigitalInOut(board.IO4) self._leftTracker.direction = Direction.INPUT self._rightTracker = DigitalInOut(board.IO3) self._rightTracker.direction = Direction.INPUT # Motor (Right): IO41--rightMotor1IN, IO42--rightMotor2IN self._rightMotor1IN = PWMOut(board.IO41, frequency=100, duty_cycle=0) self._rightMotor2IN = PWMOut(board.IO42, frequency=100, duty_cycle=0) # Motor (Left): IO12--leftMotor1IN, IO40--leftMotor2IN self._leftMotor1IN = PWMOut(board.IO12, frequency=100, duty_cycle=0) self._leftMotor2IN = PWMOut(board.IO40, frequency=100, duty_cycle=0)
def __init__(self): super(DriveSystem, self).__init__() self._motor_enable = DigitalInOut(board.A2) self._motor_enable.direction = Direction.OUTPUT self._motor_enable.value = False self._right_motor = DCMotor(PWMOut(board.D12), PWMOut(board.D13)) self._left_motor = DCMotor(PWMOut(board.D4), PWMOut(board.D11)) self._base_speed = 0.5
class PWMOut(object): """PWM output.""" def __init__(self, pin, freq=5000, duty=0): self._pID = pin self._pin = PWMOut_(pin, frequency=int(freq), duty_cycle=duty) def deinit(self): self._pin.deinit() @property def duty_percent(self): """ duty in percent """ return self._pin.duty_cycle /MAX_DUTY *100 @duty_percent.setter def duty_percent(self, value): self._pin.duty_cycle = int(min(max(0, value/100.0 *MAX_DUTY), MAX_DUTY)) @property def duty(self): """ duty as raw value """ return self._pin.duty_cycle @duty.setter def duty(self, value): self._pin.duty_cycle = int(value) @property def freq_Hz(self): """ frequency in [Hz] """ return self._pin.frequency @freq_Hz.setter def freq_Hz(self, value): # Frequency cannot be changed unless variable frequency option is set, # therefore here just recreate instance with same duty cycle but new # frequency d = self._pin.duty_cycle self._pin.deinit() self._pin = PWMOut_(self._pID, frequency=int(value), duty_cycle=d) @property def max_duty(self): return MAX_DUTY
def freq_Hz(self, value): # Frequency cannot be changed unless variable frequency option is set, # therefore here just recreate instance with same duty cycle but new # frequency d = self._pin.duty_cycle self._pin.deinit() self._pin = PWMOut_(self._pID, frequency=int(value), duty_cycle=d)
def main(addon): badge.show_bitmap('drivers/assets/speaker.bmp') audio = PWMOut(board.GPIO1, duty_cycle=0, frequency=440, variable_frequency=True) led = digitalio.DigitalInOut(board.GPIO2) led.switch_to_output(True) try: for (notename, eigths) in sequence: length = eigths * 0.1 if notename: led.value = False audio.frequency = round(note(notename)) audio.duty_cycle = 0x8000 time.sleep(length) led.value = True audio.duty_cycle = 0 time.sleep(0.025) time.sleep(3) finally: led.deinit() audio.deinit()
def __init__(self, name, pwmpin, channelpin, directionpin=None, value=REMOTE_STOP_PULSE, frequency=60, duty_cycle=0): self.name = name self.pwm = PWMOut(pwmpin, frequency=frequency, duty_cycle=duty_cycle) self.channel = PulseIn(channelpin, maxlen=64, idle_state=0) # extra motor control things for PWM Motors if directionpin not None: self.direction = DigitalInOut(directionpin) self.direction.direction = Direction.OUTPUT self.direction.value = False self.update_function = motor_duty_cycle
def __init__(self, red_pin, green_pin, blue_pin, invert_pwm=False): self._rgb_led_pins = [red_pin, green_pin, blue_pin] for i in range(len(self._rgb_led_pins)): if hasattr(self._rgb_led_pins[i], "frequency"): self._rgb_led_pins[i].duty_cycle = 0 elif str(type(self._rgb_led_pins[i])) == "<class 'Pin'>": self._rgb_led_pins[i] = PWMOut(self._rgb_led_pins[i]) self._rgb_led_pins[i].duty_cycle = 0 else: raise TypeError("Must provide a pin, PWMOut, or PWMChannel.") self._invert_pwm = invert_pwm self._current_color = (0, 0, 0) self.color = self._current_color
class Display: # pylint: disable=too-many-instance-attributes """This initializes a display and connects it into CircuitPython. Unlike other objects in CircuitPython, Display objects live until ``displayio.release_displays()`` is called. This is done so that CircuitPython can use the display itself. Most people should not use this class directly. Use a specific display driver instead that will contain the initialization sequence at minimum. """ def __init__(self, display_bus, init_sequence, *, width, height, colstart=0, rowstart=0, rotation=0, color_depth=16, grayscale=False, pixels_in_byte_share_row=True, bytes_per_cell=1, reverse_pixels_in_byte=False, set_column_command=0x2A, set_row_command=0x2B, write_ram_command=0x2C, set_vertical_scroll=0, backlight_pin=None, brightness_command=None, brightness=1.0, auto_brightness=False, single_byte_bounds=False, data_as_commands=False, auto_refresh=True, native_frames_per_second=60): # pylint: disable=unused-argument,too-many-locals """Create a Display object on the given display bus (`displayio.FourWire` or `displayio.ParallelBus`). The ``init_sequence`` is bitpacked to minimize the ram impact. Every command begins with a command byte followed by a byte to determine the parameter count and if a delay is need after. When the top bit of the second byte is 1, the next byte will be the delay time in milliseconds. The remaining 7 bits are the parameter count excluding any delay byte. The third through final bytes are the remaining command parameters. The next byte will begin a new command definition. Here is a portion of ILI9341 init code: .. code-block:: python init_sequence = ( b"\\xE1\\x0F\\x00\\x0E\\x14\\x03\\x11\\x07\\x31\ \\xC1\\x48\\x08\\x0F\\x0C\\x31\\x36\\x0F" b"\\x11\\x80\\x78" # Exit Sleep then delay 0x78 (120ms) b"\\x29\\x80\\x78" # Display on then delay 0x78 (120ms) ) display = displayio.Display(display_bus, init_sequence, width=320, height=240) The first command is 0xE1 with 15 (0x0F) parameters following. The second and third are 0x11 and 0x29 respectively with delays (0x80) of 120ms (0x78) and no parameters. Multiple byte literals (b”“) are merged together on load. The parens are needed to allow byte literals on subsequent lines. The initialization sequence should always leave the display memory access inline with the scan of the display to minimize tearing artifacts. """ self._bus = display_bus self._set_column_command = set_column_command self._set_row_command = set_row_command self._write_ram_command = write_ram_command self._brightness_command = brightness_command self._data_as_commands = data_as_commands self._single_byte_bounds = single_byte_bounds self._width = width self._height = height self._colstart = colstart self._rowstart = rowstart self._rotation = rotation self._auto_brightness = auto_brightness self._brightness = 1.0 self._auto_refresh = auto_refresh self._initialize(init_sequence) self._buffer = Image.new("RGB", (width, height)) self._subrectangles = [] self._bounds_encoding = ">BB" if single_byte_bounds else ">HH" self._current_group = None displays.append(self) self._refresh_thread = None if self._auto_refresh: self.auto_refresh = True self._colorconverter = ColorConverter() self._backlight_type = None if backlight_pin is not None: try: from pulseio import PWMOut # pylint: disable=import-outside-toplevel # 100Hz looks decent and doesn't keep the CPU too busy self._backlight = PWMOut(backlight_pin, frequency=100, duty_cycle=0) self._backlight_type = BACKLIGHT_PWM except ImportError: # PWMOut not implemented on this platform pass if self._backlight_type is None: self._backlight_type = BACKLIGHT_IN_OUT self._backlight = digitalio.DigitalInOut(backlight_pin) self._backlight.switch_to_output() self.brightness = brightness def _initialize(self, init_sequence): i = 0 while i < len(init_sequence): command = init_sequence[i] data_size = init_sequence[i + 1] delay = (data_size & 0x80) > 0 data_size &= ~0x80 self._write(command, init_sequence[i + 2:i + 2 + data_size]) delay_time_ms = 10 if delay: data_size += 1 delay_time_ms = init_sequence[i + 1 + data_size] if delay_time_ms == 255: delay_time_ms = 500 time.sleep(delay_time_ms / 1000) i += 2 + data_size def _write(self, command, data): self._bus.begin_transaction() if self._data_as_commands: if command is not None: self._bus.send(True, bytes([command]), toggle_every_byte=True) self._bus.send(command is not None, data) else: self._bus.send(True, bytes([command]), toggle_every_byte=True) self._bus.send(False, data) self._bus.end_transaction() def _release(self): self._bus._release() # pylint: disable=protected-access self._bus = None def show(self, group): """Switches to displaying the given group of layers. When group is None, the default CircuitPython terminal will be shown. """ self._current_group = group def refresh(self, *, target_frames_per_second=60, minimum_frames_per_second=1): # pylint: disable=unused-argument """When auto refresh is off, waits for the target frame rate and then refreshes the display, returning True. If the call has taken too long since the last refresh call for the given target frame rate, then the refresh returns False immediately without updating the screen to hopefully help getting caught up. If the time since the last successful refresh is below the minimum frame rate, then an exception will be raised. Set minimum_frames_per_second to 0 to disable. When auto refresh is on, updates the display immediately. (The display will also update without calls to this.) """ self._subrectangles = [] # Go through groups and and add each to buffer if self._current_group is not None: buffer = Image.new("RGBA", (self._width, self._height)) # Recursively have everything draw to the image self._current_group._fill_area(buffer) # pylint: disable=protected-access # save image to buffer (or probably refresh buffer so we can compare) self._buffer.paste(buffer) if self._current_group is not None: # Eventually calculate dirty rectangles here self._subrectangles.append( Rectangle(0, 0, self._width, self._height)) for area in self._subrectangles: self._refresh_display_area(area) def _refresh_loop(self): while self._auto_refresh: self.refresh() def _refresh_display_area(self, rectangle): """Loop through dirty rectangles and redraw that area.""" img = self._buffer.convert("RGB").crop(rectangle) img = img.rotate(self._rotation, expand=True) display_rectangle = self._apply_rotation(rectangle) img = img.crop(self._clip(display_rectangle)) data = numpy.array(img).astype("uint16") color = (((data[:, :, 0] & 0xF8) << 8) | ((data[:, :, 1] & 0xFC) << 3) | (data[:, :, 2] >> 3)) pixels = bytes( numpy.dstack( ((color >> 8) & 0xFF, color & 0xFF)).flatten().tolist()) self._write( self._set_column_command, self._encode_pos( display_rectangle.x1 + self._colstart, display_rectangle.x2 + self._colstart - 1, ), ) self._write( self._set_row_command, self._encode_pos( display_rectangle.y1 + self._rowstart, display_rectangle.y2 + self._rowstart - 1, ), ) if self._data_as_commands: self._write(None, pixels) else: self._write(self._write_ram_command, pixels) def _clip(self, rectangle): if self._rotation in (90, 270): width, height = self._height, self._width else: width, height = self._width, self._height if rectangle.x1 < 0: rectangle.x1 = 0 if rectangle.y1 < 0: rectangle.y1 = 0 if rectangle.x2 > width: rectangle.x2 = width if rectangle.y2 > height: rectangle.y2 = height return rectangle def _apply_rotation(self, rectangle): """Adjust the rectangle coordinates based on rotation""" if self._rotation == 90: return Rectangle( self._height - rectangle.y2, rectangle.x1, self._height - rectangle.y1, rectangle.x2, ) if self._rotation == 180: return Rectangle( self._width - rectangle.x2, self._height - rectangle.y2, self._width - rectangle.x1, self._height - rectangle.y1, ) if self._rotation == 270: return Rectangle( rectangle.y1, self._width - rectangle.x2, rectangle.y2, self._width - rectangle.x1, ) return rectangle def _encode_pos(self, x, y): """Encode a postion into bytes.""" return struct.pack(self._bounds_encoding, x, y) def fill_row(self, y, buffer): """Extract the pixels from a single row""" for x in range(0, self._width): _rgb_565 = self._colorconverter.convert( self._buffer.getpixel((x, y))) buffer[x * 2] = (_rgb_565 >> 8) & 0xFF buffer[x * 2 + 1] = _rgb_565 & 0xFF return buffer @property def auto_refresh(self): """True when the display is refreshed automatically.""" return self._auto_refresh @auto_refresh.setter def auto_refresh(self, value): self._auto_refresh = value if self._refresh_thread is None: self._refresh_thread = threading.Thread(target=self._refresh_loop, daemon=True) if value and not self._refresh_thread.is_alive(): # Start the thread self._refresh_thread.start() elif not value and self._refresh_thread.is_alive(): # Stop the thread self._refresh_thread.join() @property def brightness(self): """The brightness of the display as a float. 0.0 is off and 1.0 is full `brightness`. When `auto_brightness` is True, the value of `brightness` will change automatically. If `brightness` is set, `auto_brightness` will be disabled and will be set to False. """ return self._brightness @brightness.setter def brightness(self, value): if 0 <= float(value) <= 1.0: self._brightness = value if self._backlight_type == BACKLIGHT_IN_OUT: self._backlight.value = round(self._brightness) elif self._backlight_type == BACKLIGHT_PWM: self._backlight.duty_cycle = self._brightness * 65535 elif self._brightness_command is not None: self._write(self._brightness_command, round(value * 255)) else: raise ValueError("Brightness must be between 0.0 and 1.0") @property def auto_brightness(self): """True when the display brightness is adjusted automatically, based on an ambient light sensor or other method. Note that some displays may have this set to True by default, but not actually implement automatic brightness adjustment. `auto_brightness` is set to False if `brightness` is set manually. """ return self._auto_brightness @auto_brightness.setter def auto_brightness(self, value): self._auto_brightness = value @property def width(self): """Display Width""" return self._width @property def height(self): """Display Height""" return self._height @property def rotation(self): """The rotation of the display as an int in degrees.""" return self._rotation @rotation.setter def rotation(self, value): if value not in (0, 90, 180, 270): raise ValueError("Rotation must be 0/90/180/270") self._rotation = value @property def bus(self): """Current Display Bus""" return self._bus
## set up on-board LED led = DigitalInOut(board.LED) led.direction = Direction.OUTPUT ## set up serial UART # note UART(TX, RX, baudrate) uart = busio.UART(board.PI_TX, board.PI_RX, baudrate=115200, timeout=0.001) ## set up servo/motor outputs motor_direction = DigitalInOut(board.SERVO3) motor_direction.direction = Direction.OUTPUT motor_direction.value = False throttle_pwm = PWMOut(board.SERVO4, duty_cycle=motor_duty_cycle(1500), frequency=500) steering_pwm = PWMOut(board.SERVO2, duty_cycle=servo_duty_cycle(1500), frequency=60) # setup radio control channels throttle_channel = PulseIn(board.RCC3, maxlen=16, idle_state=0) steering_channel = PulseIn(board.RCC4, maxlen=16, idle_state=0) steering = Control("Steering", steering_pwm, steering_channel, 1500, servo_duty_cycle) throttle = Control("Throttle", throttle_pwm, throttle_channel, 1500, motor_duty_cycle) ## Set some other variables
""" FILE: main.py DESC: Motor controller obeys commands from sensors """ import board import busio from motor import DCMotor from time import sleep from pulseio import PWMOut uart = busio.UART(None, board.RX, baudrate=9600) left = PWMOut(board.D2) right = PWMOut(board.D0) left.duty_cycle = 30000 # int(0xffff * abs(0.5)) def stop(): print("Stopping!") try: left.duty_cycle = 0 right.duty_cycle = 0 except Exception as e: print("Exception in stop(): " + e.args[0]) pass while True: data = uart.read(1)
import board from pulseio import PWMOut from digitalio import DigitalInOut, Direction, Pull from adafruit_ble.uart import UARTServer from adafruit_bluefruit_connect.packet import Packet from adafruit_bluefruit_connect.color_packet import ColorPacket r = PWMOut(board.RGB_LED_RED, duty_cycle=0) g = PWMOut(board.RGB_LED_GREEN, duty_cycle=0) b = PWMOut(board.RGB_LED_BLUE, duty_cycle=0) uart_server = UARTServer() while True: uart_server.start_advertising() while not uart_server.connected: pass while uart_server.connected: packet = Packet.from_stream(uart_server) if isinstance(packet, ColorPacket): print(packet.color) dc = [-257 * c + 65535 for c in packet.color] r.duty_cycle, g.duty_cycle, b.duty_cycle = dc
import time import board from pulseio import PWMOut FADE_SPEED = 0.1 # Smaller number = faster FADE_INCREMENT = 4000 # How much to adjust the brightness per cycle PWM_FULL = 65535 # Setup LED led = PWMOut(board.LED1, frequency=5000, duty_cycle=0) # Fade infinitely direction = 1 brightness = 0 while True: brightness += FADE_INCREMENT * direction # Switch directions when we get to the limits if direction < 0 and brightness <= 0: brightness = 0 direction = 1 elif direction > 0 and brightness >= PWM_FULL: brightness = PWM_FULL direction = -1 # Set PWM value led.duty_cycle = brightness time.sleep(FADE_SPEED)
def __init__(self, pin, wait): self._servo = servo.Servo(PWMOut(pin, duty_cycle=2 ** 15, frequency=5)) self.wait = wait
self.servo = servo self.channel = channel self.value = value self.servo.duty_cycle = servo_duty_cycle(value) # set up on-board LED led = DigitalInOut(board.LED) led.direction = Direction.OUTPUT # set up serial UART to Raspberry Pi # note UART(TX, RX, baudrate) uart = busio.UART(board.TX1, board.RX1, baudrate=115200, timeout=0.001) # set up servos steering_pwm = PWMOut(board.SERVO2, duty_cycle=2 ** 15, frequency=60) throttle_pwm = PWMOut(board.SERVO1, duty_cycle=2 ** 15, frequency=60) # set up RC channels. NOTE: input channels are RCC3 & RCC4 (not RCC1 & RCC2) steering_channel = PulseIn(board.RCC4, maxlen=64, idle_state=0) throttle_channel = PulseIn(board.RCC3, maxlen=64, idle_state=0) # setup Control objects. 1500 pulse is off and center steering steering = Control("Steering", steering_pwm, steering_channel, 1500) throttle = Control("Throttle", throttle_pwm, throttle_channel, 1500) # Hardware Notification: starting logger.info("preparing to start...") for i in range(0, 2): led.value = True time.sleep(0.5)
print("[INFO] END - I2C Test") ### SERVO Test print("[INFO] START - SERVO Test") print("Initialising all servo Pins. There could be errors at this stage relating to timers. Swap pins to remove errors and note in documentation.") pins = [board.SERVO1, board.SERVO2, board.SERVO3, board.SERVO4, board.SERVO5, board.SERVO6, board.SERVO7, board.SERVO8] servos = [] # set up servos for pin in pins: print("[LOOP] Initialising...{0}".format(pin)) pwm = PWMOut(pin, duty_cycle=2 ** 15, frequency=50) servos.append(servo.Servo(pwm)) print("[INFO] Finished setting up all servo pins, without issue.") print("Now we will test each servo pin. Attach a servo to SERVO1 for the first test. As prompted each time, move the servo to the next pin for each test.") print("The servo will sweep all the way to one end, and then back. At which time, the test will be over and you must move the servo to the next pin.") print("Testing will begin in 5 seconds.") sleep(6) for servo in servos: for angle in range(0, 180, 5): # 0 - 180 degrees, 5 degrees at a time. servo.angle = angle sleep(0.05) for angle in range(180, 0, -5): # 180 - 0 degrees, 5 degrees at a time.
import board import time import neopixel from digitalio import DigitalInOut, Direction, Pull from analogio import AnalogIn from pulseio import PWMOut import audioio import touchio import simpleio 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]:
##INIT #INIT LIBRARIES import board from digitalio import DigitalInOut, Direction, Pull from busio import I2C from pulseio import PWMOut from adafruit_pcf8523 import PCF8523 from time import sleep, struct_time from math import sin, cos, pi, floor, asin, acos, sqrt print("SCRIPT START") #INIT MOTOR CONTROL PINS ON BOARD PWM_pin = PWMOut(board.D3, frequency=5000, duty_cycle=0) FW_pin = DigitalInOut(board.D1) FW_pin.direction = Direction.OUTPUT RV_pin = DigitalInOut(board.D4) RV_pin.direction = Direction.OUTPUT ##INIT I2C CONNECTION ON RTC AND GET CURRENT DATE i2c = I2C(board.SCL, board.SDA, frequency=400000) rtc = PCF8523(i2c) if 'i2c' in locals() and 'rtc' in locals(): now = rtc.datetime print(now) else: quit() #INIT VARIABLES #time calculation variables longitude = 4.00000 #West - precise your location
def __init__(self, r, g, b): self.r = PWMOut(r, frequency=5000, duty_cycle=0) self.g = PWMOut(g, frequency=5000, duty_cycle=0) self.b = PWMOut(b, frequency=5000, duty_cycle=0)
import time import neopixel from digitalio import DigitalInOut, Direction, Pull from analogio import AnalogIn from pulseio import PWMOut import audioio import touchio import simpleio 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 = []
def __init__(self, display_bus, init_sequence, *, width, height, colstart=0, rowstart=0, rotation=0, color_depth=16, grayscale=False, pixels_in_byte_share_row=True, bytes_per_cell=1, reverse_pixels_in_byte=False, set_column_command=0x2A, set_row_command=0x2B, write_ram_command=0x2C, set_vertical_scroll=0, backlight_pin=None, brightness_command=None, brightness=1.0, auto_brightness=False, single_byte_bounds=False, data_as_commands=False, auto_refresh=True, native_frames_per_second=60): # pylint: disable=unused-argument,too-many-locals """Create a Display object on the given display bus (`displayio.FourWire` or `displayio.ParallelBus`). The ``init_sequence`` is bitpacked to minimize the ram impact. Every command begins with a command byte followed by a byte to determine the parameter count and if a delay is need after. When the top bit of the second byte is 1, the next byte will be the delay time in milliseconds. The remaining 7 bits are the parameter count excluding any delay byte. The third through final bytes are the remaining command parameters. The next byte will begin a new command definition. Here is a portion of ILI9341 init code: .. code-block:: python init_sequence = ( b"\\xE1\\x0F\\x00\\x0E\\x14\\x03\\x11\\x07\\x31\ \\xC1\\x48\\x08\\x0F\\x0C\\x31\\x36\\x0F" b"\\x11\\x80\\x78" # Exit Sleep then delay 0x78 (120ms) b"\\x29\\x80\\x78" # Display on then delay 0x78 (120ms) ) display = displayio.Display(display_bus, init_sequence, width=320, height=240) The first command is 0xE1 with 15 (0x0F) parameters following. The second and third are 0x11 and 0x29 respectively with delays (0x80) of 120ms (0x78) and no parameters. Multiple byte literals (b”“) are merged together on load. The parens are needed to allow byte literals on subsequent lines. The initialization sequence should always leave the display memory access inline with the scan of the display to minimize tearing artifacts. """ self._bus = display_bus self._set_column_command = set_column_command self._set_row_command = set_row_command self._write_ram_command = write_ram_command self._brightness_command = brightness_command self._data_as_commands = data_as_commands self._single_byte_bounds = single_byte_bounds self._width = width self._height = height self._colstart = colstart self._rowstart = rowstart self._rotation = rotation self._auto_brightness = auto_brightness self._brightness = 1.0 self._auto_refresh = auto_refresh self._initialize(init_sequence) self._buffer = Image.new("RGB", (width, height)) self._subrectangles = [] self._bounds_encoding = ">BB" if single_byte_bounds else ">HH" self._current_group = None displays.append(self) self._refresh_thread = None if self._auto_refresh: self.auto_refresh = True self._colorconverter = ColorConverter() self._backlight_type = None if backlight_pin is not None: try: from pulseio import PWMOut # pylint: disable=import-outside-toplevel # 100Hz looks decent and doesn't keep the CPU too busy self._backlight = PWMOut(backlight_pin, frequency=100, duty_cycle=0) self._backlight_type = BACKLIGHT_PWM except ImportError: # PWMOut not implemented on this platform pass if self._backlight_type is None: self._backlight_type = BACKLIGHT_IN_OUT self._backlight = digitalio.DigitalInOut(backlight_pin) self._backlight.switch_to_output() self.brightness = brightness
def __init__(self, pwmPin, dirPin, updateCallback = None): self.update_fkt = updateCallback super().__init__(self.update) self.dir = DigitalInOut(dirPin) self.dir.direction = Direction.OUTPUT self.pwm = PWMOut(pwmPin, duty_cycle = self.duty_cycle, frequency = 1000)
led = DigitalInOut(board.D13) led.direction = Direction.OUTPUT led.value = True # Bipolar stepper -- the two coils are A0-A1 and B0-B1. pin_a0 = DigitalInOut(board.D8) pin_a0.direction = Direction.OUTPUT pin_a1 = DigitalInOut(board.D7) pin_a1.direction = Direction.OUTPUT pin_b0 = DigitalInOut(board.D5) pin_b0.direction = Direction.OUTPUT pin_b1 = DigitalInOut(board.D6) pin_b1.direction = Direction.OUTPUT # The h-bridge takes a PWM input, one for each of A and B. pin_pwm_a = PWMOut(board.D9, frequency=200000, duty_cycle=0) pin_pwm_b = PWMOut(board.D4, frequency=200000, duty_cycle=0) # SPI bus connected to the encoder. spi = SPI(board.SCK, MOSI=board.MOSI, MISO=board.MISO) spi.try_lock() spi.configure(baudrate=10000000, polarity=0, phase=1) spi.unlock() spi_cs = DigitalInOut(board.A2) spi_cs.direction = Direction.OUTPUT def read_encoder(): """ Returns averaged encoder value in the range (0,_MICROSTEPS_PER_REV). """
def __init__(self, Rpin, Gpin, Bpin): # the object (RGB LED) is initialized with a a red, green, and blue pins self.Rpin = PWMOut(Rpin, duty_cycle=65535, frequency=500) self.Gpin = PWMOut(Gpin, duty_cycle=65535, frequency=500) self.Bpin = PWMOut(Bpin, duty_cycle=65535, frequency=500)
import board from analogio import AnalogIn from digitalio import DigitalInOut, Direction from pulseio import PWMOut, PulseIn, PulseOut from adafruit_motor import servo from array import array # set up on-board LED led = DigitalInOut(board.LED) led.direction = Direction.OUTPUT # set up servos and radio control channels pwm1 = PWMOut(board.SERVO1, duty_cycle=2**15, frequency=50) pwm2 = PWMOut(board.SERVO2, duty_cycle=2**15, frequency=50) #steering_servo = servo.Servo(pwm1) #throttle_servo = servo.Servo(pwm2) steering_servo = PulseOut(pwm1) throttle_servo = PulseOut(pwm2) steering_channel = PulseIn(board.RCH1) throttle_channel = PulseIn(board.RCH2) # functions def get_voltage(pin): return (pin.value * 3.3) / 65536
def __init__(self, pin): """Setup LED and start first fade animation.""" self.led = PWMOut(pin, frequency=5000, duty_cycle=0) self.startRun()
# convert ms to 16 bit duty cycle return int(65535 * ms / 20) def angle2dc(angle): # convert 0 to 180 degree angle to 16 bit duty cycle ms = 1 + (angle / 180) return int(65535 * ms / 20) # Servo runs at 50Hz with the following duty cycle times: # Full forward: 2.0 ms -- old 180 # Stop: 1.5 ms -- old 90 -- 4915 # Full reverse: 1.0 ms -- old 0 leftServo = PWMOut(board.A3, duty_cycle=4915, frequency=50) rightServo = PWMOut(board.A6, duty_cycle=4915, frequency=50) def stop(): leftServo.duty_cycle = angle2dc(90) rightServo.duty_cycle = angle2dc(90) def go(t, spd=5): if spd in range(1, 7): lcspd = (spd * 10) + 120 rcspd = (spd * 10) + 120 leftServo.duty_cycle = angle2dc(lcspd) rightServo.duty_cycle = angle2dc(rcspd) else:
''' 实验名称:PWM 版本:v1.0 日期:2020.4 作者:01Studio 说明:输出PWM控制蜂鸣器发出不同频率声音 ''' #导入相关模块 import board from pulseio import PWMOut import time #PWM构建,蜂鸣器引脚A4. frequency值必须大于3,否则报错 PWM = PWMOut(board.A4, duty_cycle=32768, frequency=200, variable_frequency=True) #循环发出不同频率响声。 while True: PWM.frequency = 200 time.sleep(1) PWM.frequency = 400 time.sleep(1) PWM.frequency = 600 time.sleep(1) PWM.frequency = 800
def __init__(self, pwmPin, updateCallback = None): self.update_fkt = updateCallback super().__init__(self.update) self.pwm = PWMOut(pwmPin, duty_cycle = self.duty_cycle, frequency = 60)
# note UART(TX, RX, baudrate) uart = busio.UART(board.TX1, board.RX1, baudrate=115200, timeout=0.001) ## set up servo/motor outputs ## For differential you will be using two motors, no servos ## Pins are: motor_direction_left = DigitalInOut(board.SERVO3) motor_direction_left.direction = Direction.OUTPUT motor_direction_left.value = False motor_direction_right = DigitalInOut(board.SERVO4) motor_direction_right.direction = Direction.OUTPUT motor_direction_right.value = False left_motor = PWMOut(board.SERVO2, duty_cycle=motor_duty_cycle(1500), frequency=500) right_motor = PWMOut(board.SERVO1, duty_cycle=motor_duty_cycle(1500), frequency=500) # set up RC channels. NOTE: input channels are RCC3 & RCC4 (not RCC1 & RCC2) throttle_channel = PulseIn(board.RCC3, maxlen=64, idle_state=0) steering_channel = PulseIn(board.RCC4, maxlen=64, idle_state=0) # setup Control objects. 1500 pulse is off and center steering # ASSUMPTION - left motor is on steering, right motor on throttle (for code purposes) steering = Control("Steering", left_motor, steering_channel, 1500, motor_duty_cycle) throttle = Control("Throttle", right_motor, throttle_channel, 1500, motor_duty_cycle)
def __init__(self, pin1, pin2, updateCallback = None): self.update_fkt = updateCallback super().__init__(self.update) left_duty, right_duty = self.duty_cycle self.pin1 = PWMOut(pin1, duty_cycle = left_duty, frequency = 1000) self.pin2 = PWMOut(pin2, duty_cycle = right_duty, frequency = 1000)
def __init__(self, pins, dot): self.pwmList = [] for pin in pins: self.pwmList.append(PWMOut(pin, duty_cycle=0, frequency=5000)) self.dot = dot