def __init__(self): self.rled = pwmio.PWMOut(board.LED_R, frequency=1000) self.gled = pwmio.PWMOut(board.LED_G, frequency=1000) self.bled = pwmio.PWMOut(board.LED_B, frequency=1000) self.state = False self.r = 255 self.g = 255 self.b = 255
def tone(pin, frequency, duration=1, length=100): """ Generates a square wave of the specified frequency on a pin :param ~microcontroller.Pin pin: Pin on which to output the tone :param float frequency: Frequency of tone in Hz :param int length: Variable size buffer (optional) :param int duration: Duration of tone in seconds (optional) """ if length * frequency > 350000: length = 350000 // frequency try: # pin with PWM # pylint: disable=no-member with pwmio.PWMOut(pin, frequency=int(frequency), variable_frequency=False) as pwm: pwm.duty_cycle = 0x8000 time.sleep(duration) # pylint: enable=no-member except ValueError: # pin without PWM sample_length = length square_wave = array.array("H", [0] * sample_length) for i in range(sample_length / 2): square_wave[i] = 0xFFFF square_wave_sample = audiocore.RawSample(square_wave) square_wave_sample.sample_rate = int(len(square_wave) * frequency) with AudioOut(pin) as dac: if not dac.playing: dac.play(square_wave_sample, loop=True) time.sleep(duration) dac.stop()
def __init__( self, led_pins, brightness=30, brightness_step=5, brightness_limit=100, ): self._leds = [] for led in led_pins: try: self._leds.append(pwmio.PWMOut(led)) except Exception as e: print(e) raise InvalidExtensionEnvironment( 'Unable to create pulseio.PWMOut() instance with provided led_pin' ) self._led_count = len(self._leds) self.brightness = brightness self._layer_last = -1 self.brightness_step = brightness_step self.brightness_limit = brightness_limit make_key(names=('SLED_INC', ), on_press=self._key_led_inc) make_key(names=('SLED_DEC', ), on_press=self._key_led_dec)
def tone(pin, frequency, duration=1, length=100): """ Generates a square wave of the specified frequency on a pin :param ~microcontroller.Pin Pin: Pin on which to output the tone :param float frequency: Frequency of tone in Hz :param int length: Variable size buffer (optional) :param int duration: Duration of tone in seconds (optional) """ try: with pwmio.PWMOut(pin, frequency=int(frequency), variable_frequency=False) as pwm: pwm.duty_cycle = 0x8000 time.sleep(duration) except ValueError: sample_length = length square_wave = array.array("H", [0] * sample_length) for i in range(sample_length / 2): square_wave[i] = 0xFFFF sample_tone = audioio.AudioOut(pin, square_wave) sample_tone.frequency = int(len(square_wave) * frequency) if not sample_tone.playing: sample_tone.play(loop=True) time.sleep(duration) sample_tone.stop()
def gpio_pwm(output): pwm = pwmio.PWMOut(board.D26, frequency = 10000, duty_cycle=output) pwm.direction = digitalio.Direction.OUTPUT time.sleep(.5) print("in gpio_pwm funct") return
def pwm_init(pins, duty_cycle=0): pwms = [] for p in pins: if p in PWMAUDIO_CLASH_PINS: pwms.append(FakePWMOut(p, duty_cycle=duty_cycle)) else: pwms.append(pwmio.PWMOut(p, frequency=PWM_LED_FREQUENCY, duty_cycle=duty_cycle)) return pwms
def __init__( self, pwm_pin, duty_cycle=constants.STIR_DUTY_CYCLE, frequency=constants.STIR_FREQUENCY, debug=False, ): self.motor = pwmio.PWMOut(pwm_pin, duty_cycle=duty_cycle, frequency=frequency) self.debug = False
def __init__(self, led_pin, config): self.led = pwmio.PWMOut(led_pin) self.brightness_step = const(config['brightness_step']) self.brightness_limit = const(config['brightness_limit']) self.animation_mode = const(config['animation_mode']) self.animation_speed = const(config['animation_speed']) self.breathe_center = const(config['breathe_center']) if config.get('user_animation'): self.user_animation = config['user_animation']
def play_note(note): if note[0] != 0: pwm = pwmio.PWMOut(board.D12, duty_cycle=0, frequency=note[0]) # Hex 7FFF (binary 0111111111111111) is half of the largest value for a 16-bit int, # i.e. 50% pwm.duty_cycle = 0x7FFF time.sleep(note[1]) if note[0] != 0: pwm.deinit()
def burn(self, burn_num, dutycycle=0, freq=1000, duration=1): """ Operate burn wire circuits. Wont do anything unless the a nichrome burn wire has been installed. IMPORTANT: See "Burn Wire Info & Usage" of https://pycubed.org/resources before attempting to use this function! burn_num: (string) which burn wire circuit to operate, must be either '1' or '2' dutycycle: (float) duty cycle percent, must be 0.0 to 100 freq: (float) frequency in Hz of the PWM pulse, default is 1000 Hz duration: (float) duration in seconds the burn wire should be on """ # convert duty cycle % into 16-bit fractional up time dtycycl = int((dutycycle / 100) * (0xFFFF)) print('----- BURN WIRE CONFIGURATION -----') print( '\tFrequency of: {}Hz\n\tDuty cycle of: {}% (int:{})\n\tDuration of {}sec' .format(freq, (100 * dtycycl / 0xFFFF), dtycycl, duration)) # create our PWM object for the respective pin # not active since duty_cycle is set to 0 (for now) if '1' in burn_num: burnwire = pwmio.PWMOut(board.BURN1, frequency=freq, duty_cycle=0) elif '2' in burn_num: burnwire = pwmio.PWMOut(board.BURN2, frequency=freq, duty_cycle=0) else: return False # Configure the relay control pin & open relay self._relayA.drive_mode = digitalio.DriveMode.PUSH_PULL self._relayA.value = 1 self.RGB = (255, 0, 0) # Pause to ensure relay is open time.sleep(0.5) # Set the duty cycle over 0% # This starts the burn! burnwire.duty_cycle = dtycycl time.sleep(duration) # Clean up self._relayA.value = 0 burnwire.duty_cycle = 0 self.RGB = (0, 0, 0) burnwire.deinit() self._relayA.drive_mode = digitalio.DriveMode.OPEN_DRAIN return True
def play( pin, rtttl: str, octave: Optional[int] = None, duration: Optional[int] = None, tempo: Optional[int] = None, ) -> None: """Play notes to a digialio pin using ring tone text transfer language (rtttl). :param ~digitalio.DigitalInOut pin: the speaker pin :param str rtttl: string containing rtttl :param int octave: represents octave number (default 6 starts at middle c) :param int duration: length of notes (default 4 quarter note) :param int tempo: how fast (default 63 beats per minute) """ _, defaults, tune = rtttl.lower().split(":") for default in defaults.split(","): if default[0] == "d" and not duration: duration = int(default[2:]) elif default[0] == "o" and not octave: octave = default[2:] elif default[0] == "b" and not tempo: tempo = int(default[2:]) if not octave: octave = 6 if not duration: duration = 4 if not tempo: tempo = 63 base_tone = None min_freq = 440 if AUDIOIO_AVAILABLE: wave, min_freq = _get_wave(tune, octave) try: # AudioOut interface changed in CP 3.x; a waveform if now pass # directly to .play(), generated for each note in _play_to_pin() if sys.implementation.version[0] >= 3: base_tone = audioio.AudioOut(pin) else: base_tone = audioio.AudioOut(pin, wave) except ValueError: # No DAC on the pin so use PWM. pass # Fall back to PWM if not base_tone: base_tone = pwmio.PWMOut(pin, duty_cycle=0, variable_frequency=True) _play_to_pin(tune, base_tone, min_freq, duration, octave, tempo) base_tone.deinit()
def beep(count, duration, interstitial, freq): """Make some noise :param int count: the number of beeps to make :param float duration: the length (in seconds) of each beep :param float interstitial: the length (in seconds) of the silence between beeps :param int freq: the frequency of the beeps """ pwm = pwmio.PWMOut(board.D12, duty_cycle=0, frequency=freq) for _ in range(count): pwm.duty_cycle = 0x7FFF time.sleep(duration) pwm.duty_cycle = 0 time.sleep(interstitial) pwm.deinit()
def fade(pin): led = pwmio.PWMOut(pin, frequency=5000, duty_cycle=0) # LED setup for QT Py M0: # led = pwmio.PWMOut(board.SCK, 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)
def __init__(self, button_index, button_pin, led_pin, repeat=True, repeat_time=0.075, first_repeat_time=0.5): self.number = button_index self.button = digitalio.DigitalInOut(button_pin) self.button.direction = digitalio.Direction.INPUT self.button.pull = digitalio.Pull.UP self.led = pwmio.PWMOut(led_pin, frequency=1000, duty_cycle=0) self.last_pressed = 0 self.triggered = False self.on_press = None self.on_release = None self.repeat = repeat self.repeat_time = repeat_time self.first_repeat_time = first_repeat_time self.first_repeat = True self.time_of_last_press = time.monotonic()
def button2_handler(): global buzzer buzzer.deinit() LED[18].deinit() LR_FILENAME = "L-R.wav" data = open(LR_FILENAME, "rb") wav = audiocore.WaveFile(data) dac = audiopwmio.PWMAudioOut(board.GP18, right_channel=board.GP19) initialize_OLED() if I2C: oled.text('GP21 PRESSED', 30, 10, 1) oled.text('CHECK AUDIO', 32, 25, 1) oled.text('LEFT RIGHT CHANNEL', 10, 40, 1) deinitialize_OLED() dac.play(wav) time.sleep(3) dac.stop() initialize_OLED() if I2C: oled.text('GP21 PRESSED', 30, 20, 1) oled.text('CHECK RGB', 37, 40, 1) deinitialize_OLED() RGB.value = False neopixel_write(RGB, pixel_red) time.sleep(0.5) neopixel_write(RGB, pixel_green) time.sleep(0.5) neopixel_write(RGB, pixel_blue) time.sleep(0.5) neopixel_write(RGB, pixel_white) time.sleep(0.5) neopixel_write(RGB, pixel_off) time.sleep(0.5) dac.deinit() LED[18] = digitalio.DigitalInOut(board.GP19) LED[18].direction = digitalio.Direction.OUTPUT buzzer = pwmio.PWMOut(board.GP18, variable_frequency=True)
recover_time = 0.04 # Solenoid test def solenoid_test(loops): print("solenoid test") for _ in range(loops): solenoid.value = True time.sleep(strike_time) solenoid.value = False time.sleep(recover_time) time.sleep(0.1) # Servo setup pwm_servo = pwmio.PWMOut(board.GP0, duty_cycle=2**15, frequency=50) servo1 = servo.Servo(pwm_servo, min_pulse=500, max_pulse=2200) # tune pulse for specific servo # Servo test def servo_direct_test(): print("servo test: 90") servo1.angle = 90 time.sleep(2) print("servo test: 0") servo1.angle = 0 time.sleep(2) print("servo test: 90") servo1.angle = 90 time.sleep(2)
for pin in pins: digout = digitalio.DigitalInOut(pin) digout.direction = digitalio.Direction.OUTPUT LED.append(digout) # RGB Pin RGB = LED[25] # RGB Colors pixel_off = bytearray([0, 0, 0]) pixel_red = bytearray([0, 10, 0]) pixel_green = bytearray([10, 0, 0]) pixel_blue = bytearray([0, 0, 10]) pixel_white = bytearray([10, 10, 10]) # Initialize buzzer buzzer = pwmio.PWMOut(board.GP18, variable_frequency=True) # Melody mario = [ 'E7', 'E7', '0', 'E7', '0', 'C7', 'E7', '0', 'G7', '0', '0', '0', 'G6', '0', '0', '0', 'C7', '0', '0', 'G6', '0', '0', 'E6', '0', '0', 'A6', '0', 'B6', '0', 'AS6', 'A6', '0', 'G6', 'E7', '0', 'G7', 'A7', '0', 'F7', 'G7', '0', 'E7', '0', 'C7', 'D7', 'B6', '0', '0', '0', '0', '0' ] up = ['E4', 'D4', 'C4'] # Global variables button1_pressed = False button2_pressed = False button3_pressed = False button_pressed_flag = True
href (microcontroller.Pin): The href signal from the OV7670, \ sometimes inaccurately called hsync. shutdown (Optional[microcontroller.Pin]): If not None, the shutdown signal to the camera, also called the powerdown or enable pin. reset (Optional[microcontroller.Pin]): If not None, the reset signal to the camera. mclk (Optional[microcontroller.Pin]): The pin on which to create a master clock signal, or None if the master clock signal is already being generated. mclk_frequency (int): The frequency of the master clock to generate, \ ignored if mclk is None, requred if it is specified i2c_address (int): The I2C address of the camera. """ # Initialize the master clock if mclk: self._mclk_pwm = pwmio.PWMOut(mclk, frequency=mclk_frequency) self._mclk_pwm.duty_cycle = 32768 else: self._mclk_pwm = None if shutdown: self._shutdown = digitalio.DigitalInOut(shutdown) self._shutdown.switch_to_output(True) time.sleep(0.001) self._shutdown.switch_to_output(False) time.sleep(0.3) else: self._shutdown = None if reset: self._reset = digitalio.DigitalInOut(reset)
# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries # SPDX-License-Identifier: MIT import time import board import pwmio from adafruit_motor import servo # create a PWMOut object on the control pin. pwm = pwmio.PWMOut(board.D5, duty_cycle=0, frequency=50) # To get the full range of the servo you will likely need to adjust the min_pulse and max_pulse to # match the stall points of the servo. # This is an example for the Sub-micro servo: https://www.adafruit.com/product/2201 # servo = servo.Servo(pwm, min_pulse=580, max_pulse=2350) # This is an example for the Micro Servo - High Powered, High Torque Metal Gear: # https://www.adafruit.com/product/2307 # servo = servo.Servo(pwm, min_pulse=500, max_pulse=2600) # This is an example for the Standard servo - TowerPro SG-5010 - 5010: # https://www.adafruit.com/product/155 # servo = servo.Servo(pwm, min_pulse=400, max_pulse=2400) # This is an example for the Analog Feedback Servo: https://www.adafruit.com/product/1404 # servo = servo.Servo(pwm, min_pulse=600, max_pulse=2500) # This is an example for the Micro servo - TowerPro SG-92R: https://www.adafruit.com/product/169 # servo = servo.Servo(pwm, min_pulse=500, max_pulse=2400) # The pulse range is 750 - 2250 by default. This range typically gives 135 degrees of # range, but the default is to use 180 degrees. You can specify the expected range if you wish: # servo = servo.Servo(board.D5, actuation_range=135) servo = servo.Servo(pwm)
# Demo angles angles = [0, 180, 0, 45, 180] # Pin setup SERVO_PIN = board.A1 FEEDBACK_PIN = board.A5 # Calibration setup CALIB_MIN = 18112 CALIB_MAX = 49408 ANGLE_MIN = 0 ANGLE_MAX = 180 # Setup servo pwm = pwmio.PWMOut(SERVO_PIN, duty_cycle=2**15, frequency=50) servo = servo.Servo(pwm) servo.angle = None # Setup feedback feedback = AnalogIn(FEEDBACK_PIN) def get_position(): return map_range(feedback.value, CALIB_MIN, CALIB_MAX, ANGLE_MIN, ANGLE_MAX) def seek_position(position, tolerance=2): servo.angle = position
import time import board import pwmio # PWM (fading) LEDs are connected on D0, D2 (PWM not avail on D1) pwm_leds = board.D2 pwm = pwmio.PWMOut(pwm_leds, frequency=1000, duty_cycle=0) pwm2_leds = board.D0 pwm2 = pwmio.PWMOut(pwm2_leds, frequency=1000, duty_cycle=0) brightness = 0 # how bright the LED is fade_amount = 1285 # 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 pwm2.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
UNO RESET -> CircuitPython D5 (or change the init() below to change it!) Drag "optiboot_atmega328.hex" onto the CircuitPython disk drive, then open REPL! """ import board import busio import pwmio 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 = pwmio.PWMOut(board.D9, frequency=6000000, duty_cycle=65536 // 2) # pylint: enable-msg=no-member # Each chip has to have a definition so the script knows how to find it atmega328p = avrprog.Boards.ATmega328p def error(err): """ Helper to print out errors for us and then halt """ print("ERROR: " + err) avrprog.end() while True: pass while input("Ready to GO, type 'G' here to start> ") != "G":
motor_label = label.Label(terminalio.FONT, text="Motor off", color=0xFF0000, max_glyphs=9) motor_label.x = 4 motor_label.y = 74 text_group.append(motor_label) clue_display.append(text_group) board.DISPLAY.show(clue_display) motor = DigitalInOut(board.P2) motor.direction = Direction.OUTPUT buzzer = pwmio.PWMOut(board.SPEAKER, variable_frequency=True) buzzer.frequency = 1000 sense_pin = board.P1 analog = AnalogIn(board.P1) def read_and_average(ain, times, wait): asum = 0 for _ in range(times): asum += ain.value time.sleep(wait) return asum / times time.sleep(5)
import time import board import pwmio led = pwmio.PWMOut(board.D18, 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)
"""CircuitPython Essentials Servo standard servo example""" import time import board import pwmio from adafruit_motor import servo # create a PWMOut object on Pin A2. pwm = pwmio.PWMOut(board.A2, duty_cycle=2**15, 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)
import time import board import pwmio import simpleio from digitalio import DigitalInOut, Direction, Pull import adafruit_fancyled.adafruit_fancyled as fancy import neopixel NEOPIXEL_PIN = board.D6 NEOPIXEL_NUM = 31 pixels = neopixel.NeoPixel(NEOPIXEL_PIN, NEOPIXEL_NUM, auto_write=False) # Since its common anode, 'off' is max duty cycle red_led = pwmio.PWMOut(board.D9, frequency=5000, duty_cycle=65535) green_led = pwmio.PWMOut(board.D10, frequency=5000, duty_cycle=65535) blue_led = pwmio.PWMOut(board.D11, frequency=5000, duty_cycle=65535) switch = DigitalInOut(board.D12) switch.direction = Direction.INPUT switch.pull = Pull.UP colorways = [ fancy.CRGB(1.0, 1.0, 1.0), # White fancy.CRGB(1.0, 0.0, 0.0), # Red fancy.CRGB(0.5, 0.5, 0.0), # Yellow fancy.CRGB(0.0, 1.0, 0.0), # Green fancy.CRGB(0.0, 0.5, 0.5), # Cyan fancy.CRGB(0.0, 0.0, 1.0), # Blue fancy.CRGB(0.5, 0.0, 0.5), # Magenta # you can also make lists of colors to cycle through, like red/green/blue: [
from adafruit_hid.keyboard_layout_us import KeyboardLayoutUS as KeyboardLayout from adafruit_hid.keycode import Keycode # uncomment these lines for non_US keyboards # replace LANG with appropriate language #from keyboard_layout_win_LANG import KeyboardLayout #from keycode_win_LANG import Keycode import supervisor import time import digitalio from board import * import pwmio led = pwmio.PWMOut(LED, frequency=5000, duty_cycle=0) def led_pwm_up(led): for i in range(100): # PWM LED up and down if i < 50: led.duty_cycle = int(i * 2 * 65535 / 100) # Up time.sleep(0.01) def led_pwm_down(led): for i in range(100): # PWM LED up and down if i >= 50: led.duty_cycle = 65535 - int((i - 50) * 2 * 65535 / 100) # Down
#PiPi-GHERKIN - Raspberry Pi PICO #Rpi pico keyboard keymap, I used the gherkin keymap as a example :) print("Starting") #run the led import board import pwmio import time led = pwmio.PWMOut(board.GP25, frequency=60, duty_cycle=1024, variable_frequency=True) import board from kmk.kmk_keyboard import KMKKeyboard from kmk.keys import KC from kmk.matrix import DiodeOrientation from kmk.modules.layers import Layers from kmk.keys import KC, make_key envkb = KMKKeyboard() envkb.col_pins = (board.GP18, board.GP19, board.GP20, board.GP21) envkb.row_pins = (board.GP4, board.GP11, board.GP15) envkb.diode_orientation = DiodeOrientation.COLUMNS rollover_cols_every_rows = 4 envkb.diode_orientation = DiodeOrientation.COLUMNS envkb.debug_enabled = False layers = Layers()
import digitalio import pwmio pixel_pin = board.D18 fan_pin = board.D23 tumbler_pin = board.D25 ORDER = neopixel.GRB num_pixels = 8 pixels = neopixel.NeoPixel(pixel_pin, num_pixels, brightness=0.2, auto_write=False, pixel_order=ORDER) fan = digitalio.DigitalInOut(fan_pin) fan.direction = digitalio.Direction.OUTPUT tumbler = pwmio.PWMOut(tumbler_pin, frequency=1000, duty_cycle=0) #tumbler.direction = digitalio.Direction.OUTPUT #tumbler.value = False oncycle = 49000 # Create the I2C bus i2c = busio.I2C(board.SCL, board.SDA) # Create the ADC object using the I2C bus ads = ADS.ADS1015(i2c) bme280 = adafruit_bme280.Adafruit_BME280_I2C(i2c, 0x76) # Create single-ended input on channel 0 solar = AnalogIn(ads, ADS.P0) batt = AnalogIn(ads, ADS.P1) while True: try:
import time import board import pwmio piezo = pwmio.PWMOut(board.A2, duty_cycle=0, frequency=440, variable_frequency=True) while True: for f in (262, 294, 330, 349, 392, 440, 494, 523): piezo.frequency = f piezo.duty_cycle = 65536 // 2 # On 50% time.sleep(0.25) # On for 1/4 second piezo.duty_cycle = 0 # Off time.sleep(0.05) # Pause between notes time.sleep(0.5)