def screen_saver(): #local switch screen_sw = pyb.Switch() #initiate values x1 = 0 y1 = 0 x2 = 0 y2 = 0 cycle = 0 while not screen_sw(): if cycle % 50 == 0: lcd.erase() #set color random color fg = lcd.rgb(randint(128, 255), randint(128, 255), randint(128, 255)) bg = lcd.rgb(randint(0, 128), randint(0, 128), randint(0, 128)) lcd.set_pen(fg, bg) #randomize values x1 = randint(0, lcd.w) y1 = randint(0, lcd.h) x2 = randint(0, lcd.w) y2 = randint(0, lcd.h) #draw line (.line if you don't know if inside display, .line_no_clip if certain) lcd.line_no_clip(x1, y1, x2, y2) #sleep(1) # pyboard also doesn't recognize input pyb.delay(1000) #alternative cycle += 1
def __init__(self): self.serial_ref = pyb.USB_VCP() self.buffer = "" self.paused = True self.who_i_am = "dummy" # put who_i_am ID here self.packet_end = "\n" self.accel = pyb.Accel() self.switch = pyb.Switch() self.switch.callback(lambda: self.write_switch()) self.should_write_switch = False self.leds = [pyb.LED(x + 1) for x in range(4)] self.led_colors = {'r': 0, 'g': 1, 'y': 2, 'b': 3} self.leds[0].on() self.py_version = sys.version self.upy_version = "%d.%d.%d" % sys.implementation[1] self.time0 = time.ticks_us() self.write_time0 = time.ticks_ms()
def DistIRloop(msdelay=20): red_led = pyb.LED(1) green_led = pyb.LED(2) orange_led = pyb.LED(3) blue_led = pyb.LED(4) orange_led.on() userswitch = pyb.Switch() while not userswitch(): pyb.delay(100) orange_led.off() green_led.on() pyb.delay(1000) datalogfilename = '/sd/distirlog.csv' log = open(datalogfilename, 'a') log.write("t (s), d (cm)\n") green_led.off() blue_led.on() initialtimems = pyb.millis() while not userswitch(): adcint = pyb.ADC(pyb.Pin('X4')).read() times = ((pyb.millis()) - initialtimems) / 1000 adcv = (adcint * 3.3 / 4095) dcm = (9.89703 / (adcv - 0.0189332))**(1 / 0.734319 ) # (A/(v-v0))^(1/B) print("%f s, %f cm" % (times, dcm)) log.write("%f, %f\n" % (times, dcm)) pyb.delay(msdelay) log.close() pyb.sync() blue_led.off() red_led.on()
def main(): import pyb serial = pyb.USB_VCP() midi = MidiOut(serial, channel=1) switch = pyb.Switch() if hasattr(pyb, 'Accel'): accel = pyb.Accel() SCALE = 1.27 else: from staccel import STAccel accel = STAccel() SCALE = 127 while True: while not switch(): pyb.delay(10) note = abs(int(accel.x() * SCALE)) velocity = abs(int(accel.y() * SCALE)) midi.note_on(note, velocity) while switch(): pyb.delay(50) midi.note_off(note)
def pass_through(usb, uart, debug=False, enforce_crlf=True): """ Forward any USB char to Serial (vice-versa) """ print( "Activating UART<->USB passthrough..." ) print( " debug = %s" % debug ) print( " enforce_crlf = %s" % enforce_crlf ) # Send CrLf on serial when Cr received on USB print( "press USR button while sending a byte to EXIT") print( "Ready!" ) button = pyb.Switch() usb.setinterrupt(-1) while not button(): select.select([usb, uart], [], []) if usb.any(): data = usb.read(256) if debug: print( 'USB >>> UART: %s' % data ) uart.write( data ) if enforce_crlf and (data[len(data)-1] == CR): data = b'\n' if debug: print( 'USB >>> UART: %s' % data ) uart.write( data ) if uart.any(): data = uart.read(256) if debug: print( 'USB <<< UART: %s' % data ) usb.write( data ) print( 'USR exit!' )
def run(self): self._display.fill(0) self.on() sw = pyb.Switch() while sw() == False: self.processmsg(motion.processdelay) pyb.delay(motion.processdelay) self.off()
def waitforbuttonorlcd(lcd): d = False while not d: d = pyb.Switch().value() if (lcd.is_touched()): d = True return True return False
def test_6(self): sw1 = pyb.Switch(1) sw1.callback(self.callbackTest) print("Please Press SW1 for checking callback.") to=5 while TestSwitches.flagPressed==False and to>0: pyb.delay(1000) to-=1 self.assertEqual(True,TestSwitches.flagPressed,"SW callback")
def test_5(self): flagInvalid=True try: sw = pyb.Switch(99) flagInvalid=False except: pass self.assertEqual(True,flagInvalid,"Invalid SW")
def main(): SystemObjects.getInstance().setHeartbeat(Heartbeat(pyb.LED(1))) s = pyb.Switch() s.callback(nextSystemState) loop = uasyncio.get_event_loop() loop.create_task(SystemObjects.getInstance().getHeartbeat().run()) loop.run_until_complete(killer(10)) loop.close() s.callback(None)
def __init__(self): # Initializing self.switch = pyb.Switch() self.start_led = pyb.LED(2) self.sensor_base = SensorBase.SensorBase() # Constants self.sampling_delay = 6 #ms delay self.standard_delay = 500 #ms self.test_time = 30000 #ms # Flicker to indicate start of test for i in range(3): self.start_led.on() pyb.delay(self.standard_delay) self.start_led.off() pyb.delay(self.standard_delay) while not self.switch(): pass log = open('/sd/06_02_17_raw_walk_random.csv', 'w') pyb.delay(self.standard_delay) self.start_time = pyb.millis() time = 0 self.start_led.on() while not self.switch() and time < self.test_time: # TODO Sample and record gravity ax, ay, az, gx, gy, gz, mx, my, mz, yaw, roll, pitch = self.sensor_base.sample_motion( ) fsr1, fsr2, fsr3 = self.sensor_base.sample_fsr() time = pyb.elapsed_millis(self.start_time) # ax = 0 if (abs(ax) < 1) else ax # ay = 0 if (abs(ay) < 1) else ay # az = 0 if (abs(az) < 1) else az # print("ax: {} \t ay: {} \t , az: {}".format(ax, ay, az)) # print("fsr1: {} \t fsr2: {} \t , fsr3: {}".format(fsr1, fsr2, fsr3)) log.write( '{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{}\n'.format( time, ax, ay, az, gx, gy, gz, mx, my, mz, roll, pitch, yaw, fsr1, fsr2, fsr3)) # log.write('{},{},{}, {}\n'.format(time, ax, ay, az)) pyb.delay(self.sampling_delay) log.close() # Flicker to indicate end of test # self.start_led.on() # pyb.delay(self.standard_delay) self.start_led.off()
def run(): loader = Loader() kabuki.poll_input(loader) sw = pyb.Switch() sw.callback(loader.queue_reload) while True: try: kabuki.run() except Exception as exc: sys.print_exception(exc) _install_police_lights(loader)
async def userLoop(): done = False while not done: ''' i.e. target=50; cmd = 2000 kp = int(cmd) / 1e6 = 0.002 pid.setProportionalConstants([kp]) output = 0.002*15000 = 30 ''' done = pyb.Switch().value() await uasyncio.sleep_ms(300)
def __init__(self): self.switch = pyb.Switch() self.imu_startup_procedure() #TODO thread # self.esp_init() #TODO Thread self.led = pyb.LED(1) self.start_led = pyb.LED(2) self.start_led.on() pyb.delay(500) self.start_led.off() self.static_delay = 10 #ms delay self.zero_count = 0 self.last_moving = False count = 0 log = open('/sd/13_01_17_accel_drift.csv', 'w') pyb.delay(1000) self.last_vel = {'x': 0, 'y': 0, 'z': 0} self.last_pos = {'x': 0, 'y': 0, 'z': 0} self.last_accel = {'x': 0, 'y': 0, 'z': 0} self.vel = {'x': 0, 'y': 0, 'z': 0} self.pos = {'x': 0, 'y': 0, 'z': 0} self.accel = {'x': 0, 'y': 0, 'z': 0} self.start_time = pyb.millis() # self.esp.udp_connect() time = 0 while not self.switch() and time < 20000: self.sample() time = pyb.elapsed_millis(self.start_time) # print("The IP address is: {}".format(struct.unpack('i', self.esp.IP))) # count = count + 1 if self.last_moving is True: self.led.on() else: self.led.off() log.write('{},{},{},{}\n'.format(time, self.last_accel['x'], self.last_accel['y'], self.last_accel['z'])) # self.esp.udp_send("t") pyb.delay(self.static_delay) # self.esp.udp_close() log.close() self.led.off() self.start_led.on() pyb.delay(1000) self.start_led.off()
def Light_Script_Ready(): flag = True while True: if flag: toggle_light(2, 6) flag = False sw = pyb.Switch() if sw.value(): toggle_light_stop(2) Light_Feedback_Button() pyb.delay(200) break
def run(self): self._display.fill(0) sw = pyb.Switch() lasttime = pyb.millis() while sw() == False: pyb.delay(DISPLAY_DELAY) distance = self._getdistance() thistime = pyb.millis() t = thistime - lasttime self.printdistance(distance) self._rangepoint.update(self._display, distance, t / 1000.0) lasttime = thistime
def main(): sw_state = False led = pyb.LED(1) switch = pyb.Switch() switch.callback(set_sw_state) accel = STAccel() hid = pyb.USB_HID() while True: if sw_state: x, y, z = accel.xyz() hid.send((0, int(x * MAG), int(-y * MAG), 0)) pyb.delay(int(1000 / FREQ))
def main(): print('rover main') for i in range(3): for led in leds: led.toggle() pyb.delay(50) led.toggle() for led in reversed(leds): led.toggle() pyb.delay(50) led.toggle() all_leds_off() usr_switch = pyb.Switch() usr_switch.callback(demo_motor) demo_motor()
def print_kirby(): #local switch kirby_sw = pyb.Switch() #set writing position continousely c_x = 0 c_y = 0 lcd.set_pos(c_x, c_y) while not kirby_sw(): lcd.set_pos(c_x, c_y) lcd.write('<(^^)>') c_y += 10 #sleep(1) # pyboard also doesn't recognize input pyb.delay(1000) #alternative
def touch_pos(): #local switch screen_sw = pyb.Switch() #initiate values #lcd.set_text_color(lcd.rgb(255, 0, 0), lcd.rgb(0, 0, 0)) # lcd.erase() #t,x,y = lcd.get_touch() #draw squares fg = lcd.rgb(255, 128, 128) bg = lcd.rgb(0, 0, 0) lcd.set_pen(fg, bg) #rect(x,y,w,h) lcd.rect(2, 2, 50, 80) #lcd.set_pos(3,2) #lcd.write('S 1') pyb.delay(1000) lcd.set_pen(fg, lcd.rgb(128, 128, 128)) lcd.rect(2, 82, 50, 78) #lcd. pyb.delay(1000) lcd.set_pen(fg, lcd.rgb(96, 96, 96)) lcd.rect(53, 2, 50, 80) pyb.delay(1000) lcd.set_pen(fg, lcd.rgb(64, 64, 64)) lcd.rect(53, 82, 50, 78) pyb.delay(5000) while not screen_sw(): #lcd.erase() t, x, y = lcd.get_touch() lcd.set_pos(15, 150) lcd.write(str(t)) lcd.set_pos(45, 150) lcd.write(' ') lcd.set_pos(45, 150) lcd.write(str(x)) lcd.set_pos(75, 150) lcd.write(' ') lcd.set_pos(75, 150) lcd.write(str(y)) #sleep(1) # pyboard also doesn't recognize input pyb.delay(1000) #alternative pyb.delay(3000)
def osc(n, d): for i in range(n): hid.send((0, int(20 * math.sin(i / 10)), 0, 0)) pyb.delay(d) osc(100, 50) # Connect to accel - NOTE you will need to use safe mode to stop - see webapge import pyb switch = pyb.Switch() accel = pyb.Accel() hid = pyb.USB_HID() while not switch(): hid.send((0, accel.x(), accel.y(), 0)) pyb.delay(20)
def button_control(press_delay): # commonly, the delay is in millisecond ms_time_before = 0 ms_time_after = 0 sw_button = pyb.Switch() if sw_button.value(): ms_time_before = utime.ticks_ms() while True: if (utime.ticks_ms() - ms_time_before) > press_delay: lighting.turnon_light(2) if sw_button.value() is False: ms_time_after = utime.ticks_ms() break if (ms_time_after - ms_time_before) > press_delay: lighting.Light_Feedback_Button_Long() return "L" else: lighting.Light_Feedback_Button_Short() return "S"
def up_check(): return True global button MAX_TIME = const(10000) # 10 seconds DELAY_TIME = const(10) # 10 ms WINK_FREQ = 10 # Hz sw = pyb.Switch() sw.callback(cb_switch) counter = 0 while button is False and counter < MAX_TIME: if ((counter * WINK_FREQ) // 2000) % 2 == 0: pyb.LED(1).on() else: pyb.LED(1).off() pyb.delay(DELAY_TIME) counter += DELAY_TIME sw.callback(None) return button
def screen_saver_touch(): #local switch screen_sw = pyb.Switch() lcd.write('TEST') #initiate values #lcd.set_text_color(lcd.rgb(255, 0, 0), lcd.rgb(0, 0, 0)) # x1 = 0 y1 = 0 x2 = 0 y2 = 0 cycle = 0 #touch = 0 fg = lcd.rgb(255, 255, 255) bg = lcd.rgb(0, 0, 0) while not screen_sw(): if cycle % 50 == 0: lcd.erase() if not lcd.is_touched(): #set lines to green fg = lcd.rgb(255, 0, 0) #background black bg = lcd.rgb(0, 0, 0) if lcd.is_touched(): #set lines to something else fg = lcd.rgb(0, 255, 0) #background white bg = lcd.rgb(128, 128, 128) lcd.set_pen(fg, bg) x1 = randint(0, lcd.w) y1 = randint(0, lcd.h) x2 = randint(0, lcd.w) y2 = randint(0, lcd.h) #draw line (.line if you don't know if inside display, .line_no_clip if certain) lcd.line_no_clip(x1, y1, x2, y2) #sleep(1) # pyboard also doesn't recognize input pyb.delay(100) #alternative cycle += 1
def DistIRloop(msdelay=20): red_led = pyb.LED(1) green_led = pyb.LED(2) orange_led = pyb.LED(3) blue_led = pyb.LED(4) orange_led.on() fbuf.fill(0) fbuf.text('Tecle USR', 25, 20, lcd.rgb(255, 255, 0)) lcd.show_framebuf(fbuf) userswitch = pyb.Switch() while not userswitch(): pyb.delay(100) orange_led.off() green_led.on() fbuf.text('Preparando...', 10, 50, lcd.rgb(0, 255, 0)) lcd.show_framebuf(fbuf) pyb.delay(1000) datalogfilename = '/sd/distirlog.csv' log = open(datalogfilename, 'a') log.write("t (s), d (cm)\n") green_led.off() blue_led.on() fbuf.text('Medindo...', 15, 80, lcd.rgb(0, 255, 255)) lcd.show_framebuf(fbuf) # pyb.delay(3000) gc.collect() initialtimems = pyb.millis() while not userswitch(): adcint = pyb.ADC(pyb.Pin('X4')).read() times = ((pyb.millis()) - initialtimems) / 1000 adcv = (adcint * 3.3 / 4095) dcm = (9.89703 / (adcv - 0.0189332))**(1 / 0.734319 ) # (A/(v-v0))^(1/B) #print("%f s, %f cm" % (times, dcm)) log.write("%f, %f\n" % (times, dcm)) pyb.delay(msdelay) log.close() pyb.sync() blue_led.off() red_led.on() fbuf.text('Fim !', 35, 110, lcd.rgb(255, 0, 0)) lcd.show_framebuf(fbuf)
def init_buttons(q): sw = pyb.Switch() sw.callback(q.on_press) # sw.callback(lambda:print('press!')) pins = ['A' + str(i) for i in range(1, 8, 2)] # pins = ['D' + str(i) for i in range(0, 7, 2)] # pins = ['A7'] print('Initializing buttons:', pins) q.on_btn_press = {} q.btns = [] bs = [] mapper = range(len(pins)) # bs.append(lambda x: print(mapper[0], ': line', x)) # bs.append(lambda x: print(mapper[1], ': line', x)) # bs.append(lambda x: print(mapper[2], ': line', x)) # bs.append(lambda x: print(mapper[3], ': line', x)) def on_arrow_button(mapped, line): shared_globals.move_arrow_pressed = mapped # print('on_arrow_button=', mapped) # print('mapped var', mapped, ': line', line) bs.append(lambda x: on_arrow_button(mapper[0], x)) bs.append(lambda x: on_arrow_button(mapper[1], x)) bs.append(lambda x: on_arrow_button(mapper[2], x)) bs.append(lambda x: on_arrow_button(mapper[3], x)) for i, pin_id in enumerate(pins): new_callback = bs[i] new_btn = pyb.ExtInt(pin_id, pyb.ExtInt.IRQ_FALLING, pyb.Pin.PULL_UP, new_callback) q.btns.append(new_btn)
def userinput(prompt, lcd, letters="default", auto=None): clear(lcd) do = True sel = 0 text = [] if (letters == "default"): letters = listfromletters("abcdefghijklmnopqrstuvwxyz ") letters.append("GO") letters.append("<<") while do: printlcd(lcd, 0, "Press USR to switch letters", True) printlcd(lcd, 0, "Touch Screen to type letter") printlcd(lcd, 0, "letter:'" + letters[sel] + "'") printlcd(lcd, 0, prompt + listtotext(text)) waitforlcdorbuttonnowait(lcd) if (lcd.is_touched()): if (letters[sel] == "<<" or letters[sel] == "GO"): if (letters[sel] == "<<"): if (not len(text) == 0): text.pop(len(text) - 1) else: do = False else: text.append(letters[sel]) d = True while d: d = lcd.is_touched() else: try: tmp = letters[sel + 1] del tmp sel += 1 except: sel = 0 d = True while d: d = pyb.Switch().value() return listtotext(text)
def main(): a = pyb.Accel() pitches = [a.x, a.y] servos = [pyb.Servo(sn) for sn in servoNums] curangles = [-100, -100] # mn, mx, _, a, s = s1.calibration() # s1.calibration(mn, mx, servoCenter, a, s) # s1.speed(0) l = pyb.LED(ledNum) sw = pyb.Switch() while (1): if sw(): break for i in range(len(pitches)): p = pitches[i]() if curangles[i] != p: curangles[i] = p setservo(servos[i], p) pyb.delay(20)
def run_light_sword_test(spi_bus=1, led_count=30, wait_ms=50): global PATTERN_SWITCH sw = pyb.Switch() led_strip_count = 1 led_strips = tuple(WS2813(1, 64) for _ in range(led_strip_count)) pattern_funcs = ( pattern_rainbow_flow, pattern_rainbow_glow, ) pattern_idx = -1 pattern_func_cnt = len(pattern_funcs) data = [( 0, 0, 0, )] * led_count sw.callback(shift_pattern_func) try: while True: PATTERN_SWITCH = False pattern_idx += 1 pattern_func = pattern_funcs[pattern_idx % pattern_func_cnt] try: pattern_func(led_strips, data, wait_ms) except StopIteration: pass gc.collect() except KeyboardInterrupt: print('Disabling switch callback') sw.callback(None)
def toggle_breathing(freq): """breath forever if don't push the button""" presis = 1000 # toggle one time in one second freq = freq / 2 # freq for function 'sin()', because of 'fabs()' t0 = 1 / freq # period of the 'sin()', the whole time of the 'sin()' t00 = t0 / presis # division of the period, more detailed t00 = 0.002 i = 0 led4 = pyb.LED(4) while True: index = math.floor((255 * math.sin(i / presis * 2 * math.pi))) if index <= 0: index = 0 led4.intensity(index) pyb.delay(math.floor( t00 * 1000)) # delay of each cycle for t00 milliseconds\ i += 1 sw = pyb.Switch() if sw.value(): toggle_light(3, 4) pyb.delay(1500) toggle_light_stop(3) break