def event_handler(id, handle, data): global rtc global periph global serv_env_sense global notif_enabled if id == constants.EVT_GAP_CONNECTED: # indicated 'connected' LED(1).on() elif id == constants.EVT_GAP_DISCONNECTED: # stop low power timer rtc.stop() # indicate 'disconnected' LED(1).off() # restart advertisment periph.advertise(device_name="micr_temp", services=[serv_env_sense]) elif id == constants.EVT_GATTS_WRITE: # write to this Characteristic is to CCCD if int(data[0]) == 1: notif_enabled = True # start low power timer rtc.start() else: notif_enabled = False # stop low power timer rtc.stop()
def test_btn(suppress=False, lf=True, df=True): s = ''' press pulses red release pulses green double click pulses yellow long press pulses blue ''' print('Test of pushbutton scheduling coroutines.') print(helptext) print(s) pin = Pin('X1', Pin.IN, Pin.PULL_UP) red = LED(1) green = LED(2) yellow = LED(3) blue = LED(4) pb = Pushbutton(pin, suppress) pb.press_func(pulse, (red, 1000)) pb.release_func(pulse, (green, 1000)) if df: print('Doubleclick enabled') pb.double_func(pulse, (yellow, 1000)) if lf: print('Long press enabled') pb.long_func(pulse, (blue, 1000)) run()
def turnonlights(): lightsoff = False if (lightson == False): LED(1).on() LED(2).on() LED(3).on() LED(4).on()
def found_line(img): singleline_check.flager = img.get_regression([(255,255)], robust = True) if (singleline_check.flager): #print(clock.fps()) singleline_check.rho_err = abs(singleline_check.flager.rho())-0 #if singleline_check.flager.theta()>90: # singleline_check.theta_err = singleline_check.flager.theta()-0 #else: # singleline_check.theta_err = singleline_check.flager.theta()-0 position = singleline_check.flager.line() pos_x1 = abs((position[0] - position[2]) / 2) + min(position[0], position[2]) pos_y1 = abs((position[1] - position[3]) / 2) + min(position[1], position[3]) LED(3).on() #亮灯 pos_x2 = 0 pos_y2 = pos_y1 pos_x3 = 80 pos_y3 = pos_y1 y_send = int(pos_y1) singleline_check.rho_err = y_send #.to_bytes(8, byteorder='little', signed=True) line_new = (int(pos_x3), int(pos_y3), int(pos_x2), int(pos_y2)) img.draw_line(line_new, color = 127) img.draw_line(singleline_check.flager.line(), color = 127) print("y: %d"%(pos_y1)) else: LED(3).off() #亮灯
def DotCheck(): img = sensor.snapshot(line_filter=LineFilter) #拍一张图像 red_blobs = img.find_blobs([Red_threshold], pixels_threshold=3, area_threshold=3, merge=True, margin=5) #识别红色物体 max_blob = FindMax(red_blobs) #找到最大的那个 if max_blob: img.draw_cross(max_blob.cx(), max_blob.cy()) #物体中心画十字 img.draw_rectangle(max_blob.rect()) #画圈 #获取坐标并转换为+-200 Dot.x = max_blob.cx() - 80 Dot.y = max_blob.cy() - 60 Dot.flag = 1 #LED灯闪烁 LED(3).toggle() #LED灯闪烁 LED(2).toggle() else: Dot.flag = 0 LED(2).off() LED(3).off() Message.UartSendData( Message.DotDataPack(Dot.color, Dot.flag, Dot.x, Dot.y, Message.Ctr.T_ms)) return Dot.flag
async def main(): if ESP32: # Pins for IR LED gate pin = (Pin(23, Pin.OUT, value=0), Pin(21, Pin.OUT, value=0)) else: pin = Pin('X1') irb = MCE(pin) # verbose=True) # Uncomment the following to print transmit timing # irb.timeit = True b = [] # Rbutton instances px3 = Pin(18, Pin.IN, Pin.PULL_UP) if ESP32 else Pin( 'X3', Pin.IN, Pin.PULL_UP) px4 = Pin(19, Pin.IN, Pin.PULL_UP) if ESP32 else Pin( 'X4', Pin.IN, Pin.PULL_UP) b.append(Rbutton(irb, px3, 0x1, 0x7)) b.append(Rbutton(irb, px4, 0xe, 0xb)) if ESP32: while True: print('Running') await asyncio.sleep(5) else: led = LED(1) while True: await asyncio.sleep_ms(500) # Obligatory flashing LED. led.toggle()
async def main(proto): # Test uses a 38KHz carrier. if ESP32: # Pins for IR LED gate pin = (Pin(23, Pin.OUT, value=0), Pin(21, Pin.OUT, value=0)) else: pin = Pin('X1') classes = (NEC, SONY_12, SONY_15, SONY_20, RC5, RC6_M0) irb = classes[proto](pin, 38000) # My decoder chip is 38KHz # Uncomment the following to print transmit timing # irb.timeit = True b = [] # Rbutton instances px3 = Pin(18, Pin.IN, Pin.PULL_UP) if ESP32 else Pin( 'X3', Pin.IN, Pin.PULL_UP) px4 = Pin(19, Pin.IN, Pin.PULL_UP) if ESP32 else Pin( 'X4', Pin.IN, Pin.PULL_UP) b.append(Rbutton(irb, px3, 0x1, 0x7, proto)) b.append(Rbutton(irb, px4, 0x10, 0xb, proto)) if ESP32: while True: print('Running') await asyncio.sleep(5) else: led = LED(1) while True: await asyncio.sleep_ms(500) # Obligatory flashing LED. led.toggle()
def turnofflights(): #lightson = False #if (lightsoff == False): LED(1).off() LED(2).off() LED(3).off() LED(4).off() lightsoff = True
def __init__(self): self.led = { 'r': LED(1), 'g': LED(2), 'b': LED(3), } self.wlan = WLAN()
def init(cls): cls._gps = Pin('X5', mode=Pin.OUT_PP, pull=Pin.PULL_DOWN) cls._gsm = Pin('X6', mode=Pin.OUT_PP, pull=Pin.PULL_DOWN) cls._gps.value(True) cls._gsm.value(True) cls._red = LED(1) cls._blue = LED(4) cls._batt = ADC('X7') # create an analog object from a pin
def initalize_robot(): oled = init_oled() A1, A2, B1, B2, motorA, motorB = init_motors() # Define LEDs b_LED = LED(4) b_LED.toggle() # IMU connected to X9 and X10 imu = MPU6050(1, False) # Use I2C port 1 on Pyboard return imu, oled, A1, A2, B1, B2, motorA, motorB
def run_tests(): results_str = "Decoder;Format;CPU;AHB;APB1;APB2;Average time in ms\n" freqs_test = [[56000000, 56000000, 14000000, 28000000], [84000000, 84000000, 42000000, 84000000]] # Switch on LEDs to show start for led in [LED(i) for i in range(1, 3)]: led.on() for freqs in freqs_test: fr_cols = ';'.join(str(int(f / 1000000)) for f in freqs) pyb.freq(freqs[0], freqs[1], freqs[2], freqs[3]) avg_dt_jpg = display_jpeg("images/test3.jpg") results_str += "{};{};{};{}\n".format("jpeg", "RGB565", fr_cols, avg_dt_jpg) avg_dt_bmp24 = display_bmp("images/test24.bmp") results_str += "{};{};{};{}\n".format("bmp", "RGB565", fr_cols, avg_dt_bmp24) #avg_dt_bmp256 = display_bmp("images/test256.bmp") #results_str += "{};{};{};{}\n".format("bmp", "PAL256", fr_cols, avg_dt_bmp256) #avg_dt_bmp16 = display_bmp("images/test16.bmp") #results_str += "{};{};{};{}\n".format("bmp", "PAL16", fr_cols, avg_dt_bmp16) #avg_dt_gif = display_gif("images/test256.gif") #results_str += "{};{};{};{}\n".format("gif", "RGB565", fr_cols, avg_dt_gif) avg_dt_p16 = display_p16("images/test.p16") results_str += "{};{};{};{}\n".format("p16", "PAL16", fr_cols, avg_dt_p16) avg_dt_p16_py = display_p16_py("images/test.p16") results_str += "{};{};{};{}\n".format("p16_py", "PAL16", fr_cols, avg_dt_p16_py) avg_dt_p256 = display_p256("images/test.p256") results_str += "{};{};{};{}\n".format("p256", "PAL256", fr_cols, avg_dt_p256) avg_dt_p256_py = display_p256_py("images/test.p256") results_str += "{};{};{};{}\n".format("p256_py", "PAL256", fr_cols, avg_dt_p256_py) print(results_str) with open("fileread.csv", "w") as text_file: print("{}".format(results_str), file=text_file) # Switch off LEDs to show end for led in [LED(i) for i in range(1, 3)]: led.off()
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 test_sw(): print('Test of switch scheduling coroutines.') print(helptext) pin = Pin('X1', Pin.IN, Pin.PULL_UP) red = LED(1) green = LED(2) sw = Switch(pin) # Register a coro to launch on contact close sw.close_func(pulse, (green, 1000)) sw.open_func(pulse, (red, 1000)) loop = asyncio.get_event_loop() loop.run_until_complete(killer())
def readloop(enc): oldval = 0 while True: val = enc.value if oldval != val: print(val) oldval = val sleep_ms(50) LED(1).intensity(val) LED(2).intensity(val) LED(3).intensity(val) LED(4).intensity(val)
def test_swcb(): print('Test of switch executing callbacks.') print(helptext) pin = Pin('X1', Pin.IN, Pin.PULL_UP) red = LED(1) green = LED(2) sw = Switch(pin) # Register a coro to launch on contact close sw.close_func(toggle, (red, )) sw.open_func(toggle, (green, )) loop = asyncio.get_event_loop() loop.run_until_complete(killer())
def check_whether_verticle_lines(img, lines, first_time_vertical): global old_cross_x, old_cross_y if first_time_vertical: first_time_vertical = False img = lines = None else: lines = img.find_lines(threshold=2000, theta_margin=50, rho_margin=50, roi=mid_roi) #roi=(5, 5, 150,110) for line in lines: pass #img.draw_line(line.line(), color = (255, 0, 0)) # 如果画面中有两条直线 if len(lines) >= 2: (line1, line2) = find_verticle_lines(lines) if (line1 == None or line2 == None): # 没有垂直的直线 draw_cross_point(old_cross_x, old_cross_y) LED(2).off() #熄灯 LED(3).off() #熄灯 no_vertical_angle = 1 return False LED(2).toggle() #亮灯 no_vertical_angle = 0 # 画线 img.draw_line(line1.line(), color=127) img.draw_line(line2.line(), color=127) # 计算交点 (cross_x, cross_y) = calculate_intersection(line1, line2) print("cross_x: %d, cross_y: %d" % (old_cross_x, old_cross_y)) if cross_x != -1 and cross_y != -1: if abs(cross_x - old_cross_x) < move_threshold and abs( cross_y - old_cross_y) < move_threshold: # 小于移动阈值, 不移动 pass else: old_cross_x = int(old_cross_x * (1 - forget_ratio) + cross_x * forget_ratio) old_cross_y = int(old_cross_y * (1 - forget_ratio) + cross_y * forget_ratio) draw_cross_point(old_cross_x, old_cross_y)
def check_line(img): global muti_lines_err_cnt, first_time_vertical fine_border(img, up, up_roi) fine_border(img, down, down_roi) fine_border(img, left, left_roi) fine_border(img, righ, righ_roi) fine_border(img, mid, mid_roi) # line.flag = 0 if up.ok: line.flag = line.flag | 0x01 if down.ok: line.flag = line.flag | 0x02 if left.ok: line.flag = line.flag | 0x04 if righ.ok: line.flag = line.flag | 0x08 if mid.ok: line.flag = line.flag | 0x10 # #print(line.flag) up.ok = down.ok = left.ok = righ.ok = mid.ok = 0 up.num = down.num = left.num = righ.num = mid.num = 0 up.pixels = down.pixels = left.pixels = righ.pixels = mid.pixels = 0 [Flag, lines] = check_whether_muti_lines(img) if Flag: #检测是否有两条以上的线 muti_lines_err_cnt = muti_lines_err_cnt + 1 if muti_lines_err_cnt < 100: return False muti_lines_err_cnt = 0 #time.sleep(50) #延时150ms #LED(2).off() ctr.work_mode = 0x03 #换到直角检测模式 img_to_vertical = img lines_to_vertical = lines first_time_vertical = True return (img_to_vertical, lines_to_vertical) #check_whether_verticle_lines(img, lines) # 寻找直角 else: LED(2).off() LED(3).toggle() #亮灯 #time.sleep(50) #延时150ms #LED(3).off() found_line(img) #巡线 #发送数据 uart.write(pack_line_data())
def test_btncb(): print('Test of pushbutton executing callbacks.') print(helptext) pin = Pin('X1', Pin.IN, Pin.PULL_UP) red = LED(1) green = LED(2) yellow = LED(3) blue = LED(4) pb = Pushbutton(pin) pb.press_func(toggle, (red, )) pb.release_func(toggle, (green, )) pb.double_func(toggle, (yellow, )) pb.long_func(toggle, (blue, )) loop = asyncio.get_event_loop() loop.run_until_complete(killer())
def test_btn(): print('Test of pushbutton scheduling coroutines.') print(helptext) pin = Pin('X1', Pin.IN, Pin.PULL_UP) red = LED(1) green = LED(2) yellow = LED(3) blue = LED(4) pb = Pushbutton(pin) pb.press_func(pulse, (red, 1000)) pb.release_func(pulse, (green, 1000)) pb.double_func(pulse, (yellow, 1000)) pb.long_func(pulse, (blue, 1000)) loop = asyncio.get_event_loop() loop.run_until_complete(killer())
def parse(line): try: sentence, *data, checksum = line.split(',') except ValueError: return if sentence == '$GPGGA': t, lat, lat_part, lng, lng_part, fix, sat_cnt, hdil, alt, _, geoid_height, _, _ = data if fix == '0': LED(2).off() LED(3).on() else: LED(3).off() LED(2).on()
def test_sw(): s = ''' close pulses green open pulses red ''' print('Test of switch scheduling coroutines.') print(helptext) print(s) pin = Pin('X1', Pin.IN, Pin.PULL_UP) red = LED(1) green = LED(2) sw = Switch(pin) # Register coros to launch on contact close and open sw.close_func(pulse, (green, 1000)) sw.open_func(pulse, (red, 1000)) run()
def disco(): ''' disco() Starts the LEDs on the device in disco fashion. Neat way to check that you are ready to start your experiment. Press Ctrl+C to stop. Parameters ---------- None Returns ------- None ''' leds = [LED(i) for i in range(1, 5)] n = 0 while True: try: n = (n + 1) % 4 leds[n].toggle() delay(50) except KeyboardInterrupt: for led in leds: led.off() break
def runLedStartNoBlock(flag=True, tim_num=14, tim_freq=0.3, led_num=4): """ """ if flag: tim = Timer(tim_num, freq=tim_freq) tim.callback(lambda cb_fun: LED(led_num).toggle()) else: pass
def test_swcb(): s = ''' close toggles red open toggles green ''' print('Test of switch executing callbacks.') print(helptext) print(s) pin = Pin('X1', Pin.IN, Pin.PULL_UP) red = LED(1) green = LED(2) sw = Switch(pin) # Register a coro to launch on contact close sw.close_func(toggle, (red,)) sw.open_func(toggle, (green,)) run()
def __init__(self): self._timer = Timer(8, freq=1) self._leds = [LED(i) for i in range(1, 5)] self._color = 'yellow' self._timer.callback(self._callback_) self._mode = False #'deterministic' self._led = self._leds[0] self._status = False
async def heartbeat(tms): if platform == 'pyboard': # V1.x or D series from pyb import LED led = LED(1) elif platform == 'esp8266': from machine import Pin led = Pin(2, Pin.OUT, value=1) elif platform == 'linux': return # No LED else: raise OSError('Unsupported platform.') while True: if platform == 'pyboard': led.toggle() elif platform == 'esp8266': led(not led()) await asyncio.sleep_ms(tms)
def test_led(): led = LED(1) # 红色led led1 = LED(2) # 红色led led2 = LED(3) # 红色led count = 0 while True: led.toggle() led1.toggle() led2.toggle() count += 1 print(count) if count > 10: break pyb.delay(1000)
def __init__(self): ''' Constructor ''' self._ledMatrix = None self._buzzer = None self._sequencer = None #TODO: 20200917 DPM Get heartbeat led from settings self._heartbeatLed = LED(1) self._heartbeat = Heartbeat(self._heartbeatLed) self._testUserInterface() self._running = False self._activity = None self._activities = [] self._activityIndex = 0 self._loop = get_event_loop()
def btn_dynamic(): s = ''' press pulses red release pulses green double click pulses yellow long press changes button functions. ''' print('Test of pushbutton scheduling coroutines.') print(helptext) print(s) pin = Pin('X1', Pin.IN, Pin.PULL_UP) red = LED(1) green = LED(2) yellow = LED(3) blue = LED(4) pb = Pushbutton(pin) setup(pb, red, green, yellow, None) pb.long_func(setup, (pb, blue, red, green, yellow, 2000)) run()
async def monitor(loop, button): leds = [LED(x) for x in (1, 2, 3)] # Create list of LED's and times tims = [200, 700, 1200] coros = start(loop, leds, tims) while True: if button.pressed(): if running: stop(leds, coros) else: coros = start(loop, leds, tims) await asyncio.sleep_ms(0)
# along with this program. If not, see <http://www.gnu.org/licenses/>. # ## 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)
######################### # Prerequisites # ######################### #set up transceiver to receive data to from cansat x3_pin = Pin('X3', Pin.OUT_PP) x3_pin.high() #create transceiver object on UART4 hc12 = UART(4, 9600) #feedback-pyboard on and working green = LED(2) green.on() #feedback-waiting for user to press button orange = LED(3) orange.on() ######################### # Sub Programs # ######################### def start(): hc12.write('1') orange.off()
#create GPS object my_gps = MicropyGPS() #set up transceiver to send data to ground station x3_pin = Pin('X3', Pin.OUT_PP) x3_pin.high() #create transceiver object on UART4 hc12 = UART(4, 9600) #create gps object on UART3 uart = UART(3, 9600) #feedback-pyboard on and working green = LED(2) green.on() #feedback-received start command blue = LED(4) #feedback-waiting for user to press button orange = LED(3) orange.on() #boolean variable to manage main loop finished = False ######################### # Main Loop # #########################
def console( derivative_fix=0 ): print( '-'*20 ) print( 'MotorSkin Interactive Console') print( 'q: quit to REPL - quitter vers REPL') print( '') print( '8: increase speed - accelerer' ) print( '2: decrease speed - ralentir' ) print( '7: going left - aller a gauche') print( '9: going right - aller a droite') print( '4: turn left - tourner à gauche') print( '6: turn right - tourner à droite') print( '5: HALT - ARRET') print( '-'*20) print( 'INIT MOTORSKIN') l = LED(4) # LED Bleue / Blue LED l.off() r2 = Robot2Wheel( derivative_fix=derivative_fix ) r2.halt() print( 'READY') l.on() # User standard input to read instruction via the REPL connection. # Utiliser l'entrée standard pout lire les insctruction via la connexion REPL stdin = sys.stdin cmd = '' speed = 0 # Difference of speed between wheel - to have a bend turning # Difference de vitesse entre les roues - pour prendre un virage speed_delta = 0 while cmd!='q': # Blocking read 1 char from stdin # Lecture bloquante de 1 caractere sur stdin cmd = stdin.read(1) if cmd == 'q': pass elif cmd == '5': # Halt r2.halt() speed = 0 speed_delta = 0 print('halted') elif cmd == '8': # Increase Speed if abs(speed_delta)>0: # abort bending speed_delta = 0 speed = speed_control( r2, speed, +0 ) if r2.state in [Robot2Wheel.RIGHT_ROTATE, Robot2Wheel.LEFT_ROTATE]: # stop the rotation... keep current speed speed = speed_control( r2, speed, +0 ) else: speed = speed_control( r2, speed, +10 ) print( 'speed:%i' % speed ) elif cmd == '2': # Decrease speed if abs(speed_delta) >0: # abord bending speed_delta = 0 speed = speed_control( r2, speed, 0 ) else: speed = speed_control( r2, speed, -10 ) print( 'speed:%i' % speed ) elif cmd == '9': # Bending (turning) on right if speed<50: print( 'bending:speed-too-low!') else: speed_delta = speed_delta_control( r2, speed, speed_delta, +10 ) print( 'bending:%i @ %i' %(speed, speed_delta) ) elif cmd == '7': # Bending (turning) on left if speed<50: print( 'bending:speed-too-low!') else: speed_delta = speed_delta_control( r2, speed, speed_delta, -10 ) print( 'bending:%i @ %i' %(speed, speed_delta) ) elif cmd == '6': # Turning right r2.right( speed ) print( 'right:%i' % speed ) elif cmd == '4': # turning left r2.left( speed ) print( 'left:%i' % speed ) # End of software r2.halt() l.off() del(r2) print( 'BYE' )
import time from pyb import LED l = LED("left:amber") print(l.get()) while 1: # l.on() l.toggle() print(l.get()) time.sleep(1) # l.off() # print(l.get()) # time.sleep(1)