def main(): micropython.alloc_emergency_exception_buf(100) print('simp here') beam = LaserBeam('X1', 'X11') deck = CL1('X17', 'X18', 'X19', 'X20', 'X21', 'X22') piano = Piano(beam) lights = Lights(beam, deck) pushbutton = Switch() verbose = False def show(): lights.update() if not verbose: return print('{}: laser {}'.format(ticks_ms(), beam.interrupted()), end=' ') sleep(0.1) print('deck %s' % deck.status(), end=' ') if piano.playing(): print('Piano being played', end='') print() sleep(1) # stabilize while True: show() if piano.playing() and not deck.recording(): deck.record() print("record") while piano.playing(): show() deck.stop() print("stop")
def tmp_loop(num): sw = Switch() state = sw() while not state: print_tmp() delay(num) state = sw()
def main(): # Initialize UART for MIDI uart = UART(2, baudrate=31250) midi = MidiOut(uart) button1 = Switch() button2 = Pin('PC0', Pin.IN, Pin.PULL_UP) button3 = Pin('PC1', Pin.IN, Pin.PULL_UP) led1 = LED(1) led2 = LED(2) led3 = LED(3) tune = program = 0 # send a PROGRAM CHANGE to set instrument to #0 (Grand Piano) midi.program_change(program) while True: if button1(): # When button 1 is pressed, play the current tune play(midi, TUNES[TUNENAMES[tune]], led1) led1.off() if not button2(): # When button 2 is pressed, select the next of the tunes led2.on() tune = (tune + 1) % len(TUNENAMES) delay(BLINK_DELAY) led2.off() if not button3(): # When button 3 is pressed, change to next program (instrument) led3.on() program = (program + 1) % len(PROGRAMS) midi.program_change(PROGRAMS[program]) delay(BLINK_DELAY) led3.off() delay(200)
async def _comain(mc): print("Press user switch to start.") userSwitch = Switch() while not userSwitch.value(): await sleep_ms(200) print("Starting") await sleep_ms(1000) try: print("Go!") mc.goForwards() await sleep_ms(5000) mc.stop() await sleep_ms(1000) mc.goBackwards() await sleep_ms(5000) mc.stop() await sleep_ms(1000) mc.turnRight() await sleep_ms(2000) mc.stop() await sleep_ms(1000) mc.turnLeft() await sleep_ms(2000) finally: print("Stopping") mc.stop()
def set_point_tune(): global set_point trigger = Switch() oled.clear() while not trigger(): time.sleep(0.001) set_point = 0.5 + ((pot.read() / 4095)) * 2 oled.draw_text(0, 10, "set point: {}".format(set_point)) oled.display() oled.clear()
def tilt_tune(): global tilt trigger = Switch() oled.clear() while not trigger(): time.sleep(0.001) tilt = 0 + ((pot.read() / 4095)) * 2 oled.draw_text(0, 10, "Tilt: {}".format(tilt)) oled.display() oled.clear()
def tmp_wfi(): sw = Switch() sw.callback(f) global i while True: if (i == 1): read_tmp() i = 0 else: pyb.wfi()
def main(): switch = Switch() while not switch(): delay(200) # Initialize UART for MIDI uart = UART(2, baudrate=31250) midi = MidiOut(uart) seq = Sequencer(midi, bpm=124) seq.play(Pattern(PATTERN), kit=9)
async def serve(esp): esp.initServer(EchoConnection) #esp.initServer(LedToggleConnection) print("Waiting for connections...") sw = Switch() while not sw.value(): await ua_sleep_ms(200) esp.stopServer() print("Server stopped.")
def _toggleActivity(self): # First at all try to debounce self.getBuzzer().buzz(440, E) if Switch().value(): if self._activity == None or self._activity.isRunning(): schedule(Robot._stopActivity, self) else: schedule(Robot._runActivity, self)
async def mainTask(mc, count): print("Press user switch to start.") userSwitch = Switch() while not userSwitch.value(): await sleep_ms(200) print("Starting") await sleep_ms(1000) await mc.goForwardsTo(count) await sleep_ms(1000) await mc.goBackwardsTo(count)
def tmp_loop_avg(num, wait): temps = [0] * num sw = Switch() state = sw() read_tmp() while not state: for i in range(num): temps.insert(0, read_tmp()) temps.pop() delay(wait) tot = sum(temps) avg = tot / num print(avg, '°C average over ', num, ' readings.\n') delay(1000) state = sw()
async def mainTask(motion): print("Press user switch to start.") userSwitch = Switch() while not userSwitch.value(): await sleep_ms(200) print("Starting") await sleep_ms(1000) print("turning counter clockwise") await motion.turn(radians(-30)) await sleep_ms(1000) print("turning clockwise") await motion.turn(radians(60)) print("finished")
def tune_k(tune_p=False,tune_i=False,tune_d=False,s_point=False): global kp global kd global ki global set_point trigger = Switch() oled.clear() if tune_p: while not trigger(): kp = 0 + (pot.read() * 20 /4095) oled.draw_text(0,10,"kp: {}" .format(kp)) oled.display() while trigger(): pass if tune_i: while not trigger(): ki = 0 + (pot.read() * 0.5 /4095) oled.draw_text(0,10,"ki: {}" .format(ki)) oled.display() while trigger(): pass if tune_d: while not trigger(): kd = -1 + (pot.read() * 2 /4095) oled.draw_text(0,10,"Kd: {}" .format(kd)) oled.display() while trigger(): pass if s_point: while not trigger(): set_point = -0.5 + (pot.read() * 2 /4095) oled.draw_text(0,10,"set point: {}" .format(set_point)) oled.display() oled.clear() oled.draw_text(0,10,"Kp: {}" .format(kp)) oled.draw_text(0,20,"Ki: {}" .format(ki)) oled.draw_text(0,30,"Kd: {}" .format(kd)) oled.draw_text(0,40,"set point: {}" .format(set_point)) oled.display() time.sleep(1) oled.clear()
def _selectActivity(self, button): ''' Selects the activity and sets the robot into the ready mode ''' button.cleanup() self.getBuzzer().buzz(440, S) self.getBuzzer().buzz(440, S) self._activity = self._activities[self._activityIndex] self._activity.setDeviceProvider(self) Switch().callback(self._toggleActivity) self._heartbeat.setState(Heartbeat.States.Waiting) self._loop.create_task(self._heartbeat.run())
def cleanup(self): ''' Finalizes and releases the used resources ''' Switch().callback(None) self._heartbeatLed.off() if self._activity != None: self._activity.cleanup() if self._ledMatrix != None: self._ledMatrix.cleanup() #20200526 DPM Note that the sequencer's cleanup-method calls the buzzer's already if self._sequencer != None: self._sequencer.cleanup() elif self._buzzer != None: self._buzzer.cleanup()
async def mainTask(mc): print("Press user switch to start.") userSwitch = Switch() while not userSwitch.value(): await sleep_ms(200) print("Starting") await sleep_ms(1000) await mc.turnTo(radians(30)) await sleep_ms(1000) await mc.turnTo(0) await sleep_ms(1000) await mc.turnTo(radians(330)) await sleep_ms(1000) await mc.turnTo(0) await sleep_ms(1000) await mc.turn(radians(15)) await sleep_ms(1000) await mc.turn(radians(15)) await sleep_ms(1000) await mc.turn(radians(-30))
#hardware platform: pyboard V1.1 from pyb import Switch from pyb import LED def mycallback(): led.toggle() #Toggle the LED between on and off. led = LED(1) led.off() userButton = Switch() #Create and return a switch object. #userButton.callback(lambda:led.toggle()) userButton.callback(mycallback) while True: pass
def main(): micropython.alloc_emergency_exception_buf(100) print('simp here') beam = LaserBeam('X1', 'X11') mic = Mic('X12') deck = CL1('X17', 'X18', 'X19', 'X20', 'X21', 'X22') piano = Piano(mic, beam) lights = Lights(mic, beam, deck) pushbutton = Switch() verbose = False def was_show(): # BAD lights.update() #if pushbutton(): if True: print('laser {}, mic {}'.format(beam.interrupted(), mic.excited()), end=' ') print('deck %s' % deck.status(), end=' ') if piano.playing(): print('Piano being played', end='') print() def show(): lights.update() print('laser {}'.format(beam.interrupted()), end=' ') print('deck %s' % deck.status(), end=' ') if piano.playing(): print('Piano being played', end='') print() def s11(): # BAD mic.excited() print('deck %s' % deck.status()) def s12(): # ok mic.excited() sleep(0.1) print('deck %s' % deck.status()) def s13(): # BAD mic.excited() sleep(0.001) print('deck %s' % deck.status()) def s14(): # BAD: prints "deck" (or maybe "deck ") only mic.excited() sleep(0.01) print('deck %s' % deck.status()) def s15(): # BAD mic.excited() gc.collect() print('deck %s' % deck.status()) def foo(): # ok print('deck %s' % deck.status(), end=' ') sleep(1) # stabilize while True: show() if piano.playing() and not deck.recording(): deck.record() print("record") while piano.playing(): show() deck.stop() print("stop")
# push the USR button on the pyboard to flash the LEDs! # try using the reset button on the pyboard to quit this script! from time import sleep_ms from pyb import LED, Switch last = i =1 print("Demo start ... Press button") while True: if Switch().value(): # USR button pressed ? LED(i).on() last=i i=i%4 +1 # choose next internal led # 1-4 print("Switch pressed...",i) else: LED(last).off() sleep_ms(50) # sleep for while
from pyb import Switch, Pin led = Pin('LED_BLUE', Pin.OUT_PP) btn = Switch() def cb(): state = btn.value() led.value(not led.value()) print('ON' if led.value() else 'OFF') btn.callback(cb) led.on()
def tune_k(tune_p=True, tune_i=True, tune_d=True): global kp global kd global ki trigger = Switch() oled.clear() kp_saved = open('kp_store.txt', 'r') last_kp = kp_saved.read() last_kp = float(last_kp[:]) kp_saved.close() ki_saved = open('ki_store.txt', 'r') last_ki = ki_saved.read() last_ki = float(last_ki[:]) ki_saved.close() kd_saved = open('kd_store.txt', 'r') last_kd = kd_saved.read() last_kd = float(last_kd[:]) kd_saved.close() print(last_kp) print(last_ki) print(last_kd) if tune_p: while not trigger(): time.sleep(0.001) kp = float(last_kp) + ((pot.read() / 4095) - 0.5) * 0.5 oled.draw_text(0, 10, "kp: {}".format(kp)) oled.display() while trigger(): pass if tune_i: while not trigger(): time.sleep(0.001) ki = float(last_ki) + ((pot.read() / 4095) - 0.5) * 0.5 oled.draw_text(0, 10, "ki: {}".format(ki)) oled.display() while trigger(): pass if tune_d: while not trigger(): time.sleep(0.001) kd = float(last_kd) + ((pot.read() / 4095) - 0.5) * 0.5 oled.draw_text(0, 10, "Kd: {}".format(kd)) oled.display() while trigger(): pass kp_store = open('kp_store.txt', 'w') kp_store.write(str(kp)) kp_store.close() ki_store = open('ki_store.txt', 'w') ki_store.write(str(ki)) ki_store.close() kd_store = open('kd_store.txt', 'w') kd_store.write(str(kd)) kd_store.close() #print(kp) #print(ki) #print(kd) oled.clear() oled.draw_text(0, 10, "Kp: {}".format(kp)) oled.draw_text(0, 20, "Ki: {}".format(ki)) oled.draw_text(0, 30, "Kd: {}".format(kd)) oled.display() time.sleep(0.5) oled.clear()
#feedback-waiting for user to press button orange = LED(3) orange.on() ######################### # Sub Programs # ######################### def start(): hc12.write('1') orange.off() #create switch object big_red_button = Switch() big_red_button.callback(start) finished = False ######################### # Main Loop # ######################### while finished == False: #While loop that loops forever if hc12.any(): data = hc12.readline() data = data.decode('utf-8') dataArray = data.split(',') #Split it into an array called dataArray
# SETUP # ############################################################################################################# uart = UART(4, 9600) #UART for ESP communication uart.init(9600, bits=8, parity=None, stop=1, read_buf_len=64) dacA.write(init_dacA) dacB.write(init_dacB) motor_relay_L.high() motor_relay_R.high() motor1_switch.high() motor2_switch.high() motor_L_brake.high() motor_R_brake.high() setSpeedR(0) setSpeedL(0) Switch().callback(lambda: forward(2000)) tim.callback(speedCorrection) ExtInt('Y1', ExtInt.IRQ_RISING_FALLING, Pin.PULL_NONE, cfreq_R) #hall sensors as inperrupts ExtInt('Y2', ExtInt.IRQ_RISING_FALLING, Pin.PULL_NONE, cfreq_L) ExtInt(Pin('Y3'), ExtInt.IRQ_RISING, Pin.PULL_DOWN, brake_intr) # external intrupt to have sudden brake pyb.Timer(4, freq=33.33).callback(isr_speed_timer) ############################################################################################################# # LOOP # ############################################################################################################# while True: if (brake_status and status): motor1_switch.high() motor2_switch.high()
hcsr_c = 343 elif platform.find('PYBv1.1 with STM32F405RG')>-1: # Board-specific definitions: Pyboard v1.1 print('Loading definitions for PYBv1.1') from machine import Pin, UART from pyb import Switch board='PBDv1.1' p_pwr1 = Pin('X19', Pin.OUT) # Pin X19 is power supplied to the DS18B20, V+ p_pwr2 = Pin('X18', Pin.OUT) # Pin X18 is power supplied to the GPS, V+ p_pwr3 = Pin('X3', Pin.OUT) # Pin X3 is power supplied to the GPS, V+ p_pwr4 = Pin('X4', Pin.OUT) # Pin X4 is power supplied to the GPS, V+ p_DS18B20 = Pin('X20', Pin.IN) # Pin X20 is the data pin for DS18B20 temperature sensors uartGPS= UART(4, 9600) uartAQ= UART(3, 9600) uartAQ.init(9600, bits=8, parity=None, stop=1) button = Switch() # use onboard USR button #p_batt=14 #p_sens=4 # Define default I2C pins p_I2Cscl_lbl='X9' p_I2Csda_lbl='X10' ''' (sysname='pyboard', nodename='pyboard', release='1.13.0', version='v1.13-53-gc20075929-dirty on 2020-09-21', machine='Adafruit Feather STM32F405 with STM32F405RG') (sysname='esp8266', nodename='esp8266', release='2.2.0-dev(9422289)', version='v1.9.4-701-g10bddc5c2 on 2019-01-17', machine='ESP module with ESP8266') (sysname='pyboard', nodename='pyboard', release='1.13.0', version='v1.13 on 2020-09-02', machine='PYBv1.1 with STM32F405RG') '''
def main(): print('Traffic lights running ...') class Events: RED_TIMEOUT = 1 AMBER_TIMEOUT = 2 GREEN_TIMEOUT = 3 ERROR = 4 START = 5 start = State( ident='start' ) # Special start state to allow for initialization before operation. timer0 = 10 class FlashingRed(State): # Special fault state that should never exit. def __init__(self): super().__init__(ident='error') self.timer = Timer(timer0 + 4) self.led = LED(1) # noinspection PyUnusedLocal def toggle_with_arg( not_used ): # Toggle func that accepts an arg, because ``schedule`` *needs* an arg. self.led.toggle() self.led_tog_ref = toggle_with_arg # Store the function reference locally to avoid allocation in interrupt. def __enter__(self): self.timer.init( freq=2, callback=lambda _: schedule(self.led_tog_ref, None)) return self def __exit__(self, exc_type, exc_val, exc_tb): self.led.off() self.timer.deinit() flashing_red = FlashingRed() traffic_lights = Machine(initial_state=start) # The traffic light machine. traffic_lights.actions[ Events.RED_TIMEOUT] = flashing_red.action # Catch anything unexpected. traffic_lights.actions[Events.AMBER_TIMEOUT] = flashing_red.action traffic_lights.actions[Events.GREEN_TIMEOUT] = flashing_red.action traffic_lights.actions[Events.ERROR] = flashing_red.action traffic_lights.actions[Events.START] = flashing_red.action tl_fire_ref = traffic_lights.fire # Store the function reference locally to avoid allocation in interrupt. error = Switch() error.callback(lambda: schedule(tl_fire_ref, Events.ERROR)) class LEDState( State ): # Output is determined by ``__enter__`` and ``__exit__`` (common in embedded machines). def __init__(self, led_num, time_on, event): super().__init__(ident=led_num) # Use the LED num as the ident. self.led = LED(self.ident) # The LED to use. self.timer = Timer(timer0 + self.ident) # The timer to use. self.timeout = time_on # Time to wait before firing event. self.event = event # Event to fire at end of time_on. def __enter__(self): self.led.on() self.timer.init( freq=1 / self.timeout, callback=lambda _: schedule(tl_fire_ref, self.event)) return self def __exit__(self, exc_type, exc_value, traceback): self.led.off() self.timer.deinit() return False red = LEDState(led_num=1, time_on=3, event=Events.RED_TIMEOUT) green = LEDState(led_num=2, time_on=3, event=Events.GREEN_TIMEOUT) amber = LEDState(led_num=3, time_on=0.5, event=Events.AMBER_TIMEOUT) red.actions[Events.RED_TIMEOUT] = green.action green.actions[Events.GREEN_TIMEOUT] = amber.action amber.actions[Events.AMBER_TIMEOUT] = red.action start.actions[Events.START] = red.action with traffic_lights: _ = traffic_lights.fire( event=Events.START ) # Start the machine once all the setup is complete. while True: # Keep running timers (and other peripherals), but otherwise do nothing. wfi()
''' 实验名称:按键 版本:v2.0 日期:2020.12 作者:01Studio ''' from pyb import LED, Switch sw = Switch() #定义按键对象名字为sw sw.callback(lambda: LED(4).toggle()) #当按键被按下时,LED(4)状态反转
# ## from pyb import delay, LED, Switch from r2wheel import Robot2Wheel from ultrasonic import Ultrasonic # Broche pour déclencher le senseur TRIGGER_PIN = pyb.Pin.board.Y5 # Broche pour attendre le retour d'echo ECHO_PIN = pyb.Pin.board.Y6 r2 = Robot2Wheel( reverse_mot2 = True ) u = Ultrasonic( TRIGGER_PIN, ECHO_PIN ) l = LED(4) # LED Bleue btn = Switch() # Button utilisateur (User) MIN_DISTANCE = 20 # Minimum distance def drive_robot(): r2.forward() # Tant que pas bouton User --> Continuer while btn() == False: #DEBUG: print( 'Running' ) if u.distance_in_cm() < MIN_DISTANCE: r2.halt() delay(100) r2.right() delay( 2500 ) r2.halt() delay(100)
#构建语音模块对象 wm = audio.WM8978() record_flag = 0 #录音标志位 ###################### # 开始录音 USR按键 ###################### def rec_begin(): global record_flag record_flag = 1 sw = Switch() sw.callback(rec_begin) ###################### # 停止录音 A0按键 ###################### KEY_A = Pin('A0', Pin.IN, Pin.PULL_UP) #构建按键A0 def rec_stop(KEY_A): global record_flag #消除按键抖动 if KEY_A.value() == 0: time.sleep_ms(5) if KEY_A.value() == 0:
# pbaudio_syn.py VS1053b driver demo/test for Pyboard # (C) Peter Hinch 2020 # Released under the MIT licence from vs1053_syn import * from machine import SPI, Pin from pyb import Switch # For cancellation import time import os switch = Switch() # 128K conversion # ffmpeg -i yellow.flac -acodec libmp3lame -ab 128k yellow.mp3 # VBR conversion # ffmpeg -i yellow.flac -acodec libmp3lame -qscale:a 0 yellow.mp3 # Yeah, I know. I like Coldplay... spi = SPI(2) # 2 MOSI Y8 MISO Y7 SCK Y6 reset = Pin('Y5', Pin.OUT, value=1) # Active low hardware reset xcs = Pin('Y4', Pin.OUT, value=1) # Labelled CS on PCB, xcs on chip datasheet sdcs = Pin('Y3', Pin.OUT, value=1) # SD card CS xdcs = Pin('Y2', Pin.OUT, value=1) # Data chip select xdcs in datasheet dreq = Pin('Y1', Pin.IN) # Active high data request player = VS1053(spi, reset, dreq, xdcs, xcs, sdcs=sdcs, mp='/fc',