def log_gps(uart, read_delay=100): led = LED(4) with open('/sd/gps.nmea', 'a') as f: print(file=f) try: while True: led.on() while uart.any(): line = str(uart.readline(), 'utf-8').rstrip() print(line, file=f) parse(line) led.toggle() f.flush() led.off() wfi() #delay(read_delay) finally: led.off() LED(2).off() LED(3).off() os.sync() LED(1).on()
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()
async def main(loop): rtc = RTC() red = LED(1) red.on() grn = LED(2) sta_if = network.WLAN() sta_if.active(True) sta_if.connect(SSID, PW) while sta_if.status() in ( 1, 2): # https://github.com/micropython/micropython/issues/4682 await asyncio.sleep(1) grn.toggle() if sta_if.isconnected(): red.off() grn.on() await asyncio.sleep(1) # 1s of green == success. grn.off() # Conserve power Latency(2000) count = 0 while True: publish(ujson.dumps([count, rtc.datetime()])) count += 1 await asyncio.sleep(120) # 2 mins else: # Fail to connect red.on() grn.off()
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
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)
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()
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)
#boolean variable to manage main loop finished = False ######################### # Main Loop # ######################### while finished == False: #if start command is received if hc12.any(): orange.off() #for local use only for i in range(0,2): blue.toggle() sleep(0.4) blue.toggle() sleep(0.4) #X second loop, get data every half second and write to backup.csv, and also transmit to ground station for tag in range(1,61): green.off() temp = bmp180.temperature pres = bmp180.pressure alt = bmp180.altitude #if there is gps data to be read while uart.any():
Name: Lab 4 Exercise 4 ----------------------------------------------------------- Learning to use rhe OLED deisplay driver ----------------------------------------------------------- ''' import pyb from pyb import LED, ADC, Pin # Pyboard basic library from oled_938 import OLED_938 # Use various class libraries in pyb # Create peripheral objects b_LED = LED(4) pot = ADC(Pin('X11')) # I2C connected to Y9, Y10 (I2C bus 2) and Y11 is reset low active oled = OLED_938(pinout = {'sda': 'Y10', 'scl': 'Y9', 'res': 'Y8'}, height = 64, external_vcc = False, i2c_devid = 61) oled.poweron() oled.init_display() # Simple Hello world message oled.draw_text(0, 0, 'Hello, world!') # each character is 6x8 pixels tic = pyb.millis() # store starting time while True: b_LED.toggle() toc = pyb.millis() # read elapsed time oled.draw_text(0, 20, 'Delayed time:{:6.3f}sec'.format((toc-tic)*0.001)) oled.draw_text(0, 40, 'POT5K reading:{:5d}'.format(pot.read())) tic = pyb.millis() # start time oled.display() delay = pyb.rng()%1000 # Generate a random number btw 0 and 999 pyb.delay(delay) # Delay in milliseconds
shut_down() # Core code that routes activities if machine.reset_cause() == machine.DEEPSLEEP_RESET: # This should be the primary function called when logging - keep at top of if statements # Alarm trigger - Log and go back to sleep write_line('DEEPSLEEP') run() elif machine.reset_cause() == machine.PWRON_RESET: # Power turned on (battery plugged it) - start cycling write_line('PWRON') for x in range(0, 5): led_G.toggle() sleep(.5) led_G.off() led_B.on() sleep(1) shut_down() elif machine.reset_cause() == machine.HARD_RESET: # Button pressed - start wifi so can get into pyboard write_line('HARD') import Wifi Wifi.connect() elif machine.reset_cause() == machine.SOFT_RESET: # CTL-D entered from the prompt - used for clearing memory while testing code write_line('SOFT')
#select the cut flag uartClass = 3 green_led.on() else: # lost the frame: extend the area, and backward appleRoi = [] #if appleRoi: #appleRoi = extendRoi(appleRoi) #img.draw_rectangle(appleRoi, color = (0, 0, 255)) # select the backwards flag uartClass = 2 print("obj not found!") blue_led.toggle() #continue #print('\n') # get the info of density and ratio of target #density = objBlob.density() #ratio = objBlob.w() / objBlob.h() #pixelCnt = objBlob.pixels() #area = objBlob.area() #img.draw_string(appleRoi[0], appleRoi[1], str(density), color = (255, 255, 0)) #print("pix: %d, area: %d, width: %d, height: %d"%(pixelCnt, area, objBlob.w(), objBlob.h())) # send the flag #uartFlag:
def car_control(ret): if ret == 'w': car.Right_move(1) car.Left_move(1) elif ret == 's': car.Right_move(2) car.Left_move(2) elif ret == 'a': car.Right_move(1) car.Left_move(2) elif ret == 'd': car.Right_move(2) car.Left_move(1) elif ret == 'x': car.Right_move(3) car.Left_move(3) while True: led1.toggle() getter.add_string(wifi.receive_char()) getter.add_string(usb_uart.readline()) ret = getter.get_char() if ret is not None: print(ret) car_control(ret) pyb.delay(100)
#boolean variable to manage main loop finished = False ######################### # Main Loop # ######################### while finished == False: #if start command is received if hc12.any(): orange.off() #for local use only for i in range(0, 2): blue.toggle() sleep(0.4) blue.toggle() sleep(0.4) #X second loop, get data every half second and write to backup.csv, and also transmit to ground station for tag in range(1, 61): green.off() temp = bmp180.temperature pres = bmp180.pressure alt = bmp180.altitude #if there is gps data to be read while uart.any():
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)
from Display import Display sensor = Sensor(4, 9600) display = Display(6, 9600) dht11 = Dht11('X7') l1 = LED(1) l2 = LED(2) l3 = LED(3) l4 = LED(4) cnt = 10 n4 = 0 n5 = 0 while True: a = display.read_disp() l1.toggle() if a != 0: sensor.state = a n0, n1, n2, n3 = sensor.read_s() l2.toggle() cnt = cnt - 1 if cnt == 0: n4, n5 = dht11.read_temps() cnt = 10 # n4,n5=25,50 l3.toggle() display.write_d(n0, n1, n2, n3, n4, n5) l4.toggle()
clock = time.clock() led2 = LED(2)#green,get x,y dispaly led3 = LED(3)#run display # Only blobs that with more pixels than "pixel_threshold" and more area than "area_threshold" are # returned by "find_blobs" below. Change "pixels_threshold" and "area_threshold" if you change the # camera resolution. "merge=True" merges all overlapping blobs in the image. while(True): clock.tick() img = sensor.snapshot() threshold_index = 3 #chose color for blob in img.find_blobs([thresholds[threshold_index]], pixels_threshold=200, area_threshold=200, merge=True): led2.toggle() img.draw_rectangle(blob.rect()) img.draw_cross(blob.cx(), blob.cy()) if threshold_index == 0: color_bar=(255,0,0) #red color_text="red" elif threshold_index == 1: color_bar=(0,255,0) #green color_text="green" elif threshold_index == 2: color_bar=(0,255,0) #blue color_text="blue" elif threshold_index == 3: color_bar=(0,0,0) #black color_text="black" img.draw_string(blob.x() - 2, blob.y() - 8, color_text,color=color_bar)
INIT_ARM_SPEED = 15000 # default 15000 TRACKING_ARM_SPEED = 1000 # default 1000 # higher value -> larger arm movement in every step. 10 is default. (this affects target distance, not speed) STEP_SIZE = 10 # ms to wait after init before recording the tracked item reference. Good to give the arm time to move to position. INIT_WAIT = 5000 # -------------------------------------------------- INIT #initial the uarm led_err = LED(1) #red led_ok = LED(2) # green led_start = LED(3) # Blue led led_start.toggle() if MODE == "arm": #initial the uart uart = UART(3, 115200) #test if the connection is active by a status query uart.write("P2500\r\n") utime.sleep_ms(100) response = uart.readline() if response != b'ok\n': # wait for the arm to get ready (probably needs to switch active uart, send "M2500" command to it from outside) while(response != b'ok\n'): print(response) response = uart.readline() utime.sleep_ms(100)
#hardware platform: pyboard V1.1 from pyb import LED import time led1 = LED(1) led1.toggle() #turn on led led2 = LED(2) led2.toggle() led3 = LED(3) led3.toggle() led4 = LED(4) led4.toggle() while 1: time.sleep(0.5) led1.on() time.sleep(0.5) led1.off() time.sleep(0.5) led3.on() time.sleep(0.5) led3.off() time.sleep(0.5) led2.on() time.sleep(0.5) led2.off() time.sleep(0.5) led4.on() time.sleep(0.5) led4.off()
async def heartbeat(): led = LED(2) # Green while True: await asyncio.sleep_ms(500) led.toggle()
async def red_handler(evt_rx): led = LED(1) for x in range(20): await evt_rx.wait() print(x) led.toggle()
class LEDController: def __init__(self): self.LED_GREEN = 2 self.LED_RED = 1 self.LED_IR = 4 self.LED_BLUE = 3 self.ledRed = LED(self.LED_RED) self.ledGreen = LED(self.LED_GREEN) self.ledBlue = LED(self.LED_BLUE) self.ledIR = LED(self.LED_IR) self.ledGreen.off() self.ledRed.off() self.ledIR.off() self.ledBlue.off() # blink var self.lastTime = 500 def allOff(self): self.ledGreen.off() self.ledRed.off() self.ledIR.off() self.ledBlue.off() def on(self, led): if (led == self.LED_RED): self.ledRed.on() elif (led == self.LED_GREEN): self.ledGreen.on() elif (led == self.LED_IR): self.ledIR.on() elif (led == self.LED_BLUE): self.ledBlue.on() def off(self, led): if (led == self.LED_RED): self.ledRed.off() elif (led == self.LED_GREEN): self.ledGreen.off() elif (led == self.LED_IR): self.ledIR.off() elif (led == self.LED_BLUE): self.ledBlue.off() def toggle(self, led): if (led == self.LED_RED): self.ledRed.toggle() elif (led == self.LED_GREEN): self.ledGreen.toggle() elif (led == self.LED_IR): self.ledIR.toggle() elif (led == self.LED_BLUE): self.ledBlue.toggle() def blink(self): currentTime = millis() if currentTime > (self.lastTime): self.ledGreen.toggle() self.lastTime = currentTime + 500
# Object tracking with keypoints example. # Show the camera an object and then run the script. A set of keypoints will be extracted # once and then tracked in the following frames. If you want a new set of keypoints re-run # the script. NOTE: see the docs for arguments to tune find_keypoints and match_keypoints. import sensor, time, image, utime from pyb import UART from pyb import LED #initial the uarm led = LED(3) # Blue led led.toggle() #initial the uart uart = UART(3, 115200) #get the command first, since the arm should change the communication port from main uart to second port flag = uart.readline() while (flag != b'ok\n'): flag = uart.readline() utime.sleep_ms(100) print(flag) #print("done") #set the uarm to the default position utime.sleep_ms(500) uart.write("G0 X250 Y0 Z") uart.write("160 F15000\r\n") utime.sleep_ms(8000) #finish the initialization
Red = LED(1) Blue = LED(3) Green = LED(2) s = pyb.Servo(2) INB = pyb.Pin("P3",pyb.Pin.OUT_PP) INA = pyb.Pin("P4",pyb.Pin.OUT_PP) INA.low() INB.high() p = Pin('P5') Motor_Timer = Timer(2,freq=1000) ch = Motor_Timer.channel(4,Timer.PWM, pin=p) ch.pulse_width_percent(0) for x in range(50): Red.toggle() pyb.delay(50) # Tracks a black line. Use [(128, 255)] for a tracking a white line. GRAYSCALE_THRESHOLD = [(0, 60)] # Each roi is (x, y, w, h). The line detection algorithm will try to find the # centroid of the largest blob in each roi. The x position of the centroids # will then be averaged with different weights where the most weight is assigned # to the roi near the bottom of the image and less to the next roi and so on. ROIS = [ # [ROI, weight] (0, 100, 160, 10, 0.1), # You'll need to tweak the weights for your app (0, 50, 160, 10, 0.7), # depending on how your robot is setup. (0, 20, 160, 20, 0.2) ]
DISP.write('{:3.1f}°C'.format(highLowValues[i][1])) elif i == 1: DISP.set_pos(64, 88 + i * 16) DISP.write('{:3.1f}hPa'.format(highLowValues[i][0])) DISP.set_pos(8, 88 + i * 16) DISP.write('{:3.1f}hPa'.format(highLowValues[i][1])) elif i == 2: DISP.set_pos(64, 88 + i * 16) DISP.write('{:3.1f}%'.format(highLowValues[i][0])) DISP.set_pos(8, 88 + i * 16) DISP.write('{:3.1f}%'.format(highLowValues[i][1])) DISP.set_brightness(31) for i in range(3, 0, -1): GLED.toggle() time.sleep(1) print(i) highLowValues = [[-100, 100], [300, 1100], [0, 100] ] #[high, low], init to values guaranteed to be lower/higher _ = sensor_read() # scrap first reading values = sensor_read() measurementTimer = time.ticks_ms() # initial timer value lcdTimeOut = measurementTimer lcdOn = False lcd_init(DISP) GLED.on() with open('tph', 'a') as f: #write header f.write("#temperature, pressure, humidity\n") #print("header written")