rtc.stop() def send_temp(timer_id): global notif_enabled global char_temp if notif_enabled: # measure chip temperature temp = Temp.read() temp = temp * 100 char_temp.write(bytearray([temp & 0xFF, temp >> 8])) # start off with LED(1) off LED(1).off() # use RTC1 as RTC0 is used by bluetooth stack # set up RTC callback every 5 second rtc = RTC(1, period=5, mode=RTC.PERIODIC, callback=send_temp) notif_enabled = False uuid_env_sense = UUID("0x181A") # Environmental Sensing service uuid_temp = UUID("0x2A6E") # Temperature characteristic serv_env_sense = Service(uuid_env_sense) temp_props = Characteristic.PROP_NOTIFY | Characteristic.PROP_READ temp_attrs = Characteristic.ATTR_CCCD char_temp = Characteristic(uuid_temp, props=temp_props, attrs=temp_attrs)
# STM32のプログラム import pyb from pyb import LED from pyb import UART uart = UART(6, 115200) uart.init(115200, bits=8, parity=None, stop=1) led = LED(1) pull = 0 speed_1 = 0 speed_2 = 0 speed_3 = 0 speed_4 = 0 dir1 = pyb.Pin('PB3', pyb.Pin.OUT_PP) dir2 = pyb.Pin('PB5', pyb.Pin.OUT_PP) dir3 = pyb.Pin('PA8', pyb.Pin.OUT_PP) dir4 = pyb.Pin('PA10', pyb.Pin.OUT_PP) tim2 = pyb.Timer(2, freq=20000) tim3 = pyb.Timer(3, freq=20000) tim4 = pyb.Timer(4, freq=20000) leg1 = tim3.channel(1, pyb.Timer.PWM, pin=pyb.Pin('PB4')) leg2 = tim2.channel(3, pyb.Timer.PWM, pin=pyb.Pin('PB10')) leg3 = tim3.channel(2, pyb.Timer.PWM, pin=pyb.Pin('PA7')) leg4 = tim4.channel(1, pyb.Timer.PWM, pin=pyb.Pin('PB6')) dir1.high() dir2.high() dir3.low()
''' 实验名称:按键 版本:v2.0 日期:2019.4 作者:01Studio ''' from pyb import LED, Switch sw = Switch() #定义按键对象名字为sw sw.callback(lambda: LED(4).toggle()) #当按键被按下时,LED(4)状态反转
# maxA, minB, maxB),LAB的值在图像左侧三个坐标图中选取。如果是灰度图,则只需 #设# 问吴老师 模板是什么?置(min, max)两个数字即可。 sensor.reset() # 初始化摄像头 sensor.set_pixformat(sensor.RGB565) # 格式为 RGB565. sensor.set_framesize(sensor.QQVGA) # 使用 QQVGA 速度快一些 sensor.skip_frames(10) # 跳过10帧,使新设置生效 sensor.set_auto_whitebal(False) # 问吴老师 模板是什么? #关闭白平衡。白平衡是默认开启的,在颜色识别中,一定要关闭白平衡。 clock = time.clock() # 追踪帧率 turn_threshold = 15 # rotate threshold turn = Pin('P0', Pin.OUT_PP) turnDone = Pin('P1', Pin.OUT_PP) red = LED(1) green = LED(2) blue = LED(3) blue.on() time.sleep(2) blue.off() arduino = UART(3, 19200) while (True): clock.tick() # Track elapsed milliseconds between snapshots(). img = sensor.snapshot() # 从感光芯片获得一张图像 img = img.lens_corr(2.5, 1.0) blobs = img.find_blobs([green_threshold],
''' ------------------------------------------- Name: Strawbretty ------------------------------------------- Using the OLED driver and IMU ------------------------------------------- ''' import pyb from pyb import LED, ADC, Pin from oled_938 import OLED_938 from mpu6050 import MPU6050 # Create peripheral objects b_led = LED(4) imu = MPU6050(1, False) # 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() width = 128
from pyb import LED, Timer, Pin, Switch, UART, USB_VCP from Basic.Car_Driver import Car_Driver as Car from Basic.Wifi_Driver import Wifi_Driver as Wifi from Basic.ComHelper import ComHelper sw = Switch() led1 = LED(1) led2 = LED(2) led3 = LED(3) led4 = LED(4) usb_uart = USB_VCP() car = Car(['Y1', 'Y2', 'Y3', 'Y4']) wifi = Wifi() getter = ComHelper() 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)
import pyb from pyb import LED, DAC, ADC, Pin from oled_938 import OLED_938 from mpu6050 import MPU6050 # Define various ports, pins and peripherals a_out = DAC(1, bits=12) pot = ADC(Pin('X11')) b_LED = LED(4) # Use OLED to say what it is doing oled = OLED_938(pinout={'sda': 'Y10', 'scl': 'Y9', 'res': 'Y8'}, height=64, external_vcc=False, i2c_devid=61) oled.poweron() oled.init_display() oled.draw_text(0, 0, 'Measure pitch and pitch_dot') oled.draw_text(0,20, 'CCW: pitch (deg)') oled.draw_text(0,30, 'CW: pitch_dot (deg/s)') oled.display() # IMU connected to X9 and X10 imu = MPU6050(1, False) # Pitch angle calculation using complementary filter def pitch_estimate(pitch, dt, alpha): theta = imu.pitch() pitch_dot = imu.get_gy() pitch = alpha*(pitch + pitch_dot*dt) + (1-alpha)*theta return (pitch, pitch_dot) ''' Main program loop
#API/Guide #https://docs.micropython.org/en/latest/pyboard/pyboard/quickref.html ## You need to setup the touch sensor using ADC here ## You need to setup the external LED using GPIO here #Setup pins for motor motorForward = Pin('X2', Pin.OUT_PP) motorBackward = Pin('X3', Pin.OUT_PP) ## Setup PWM pin for the motor on pin X1 #Setup internal LED pins internalLEDR = LED(1) internalLEDY = LED(3) internalLEDG = LED(2) def turnOnMotor(sensorValue): ch.pulse_width_percent(math.fabs(sensorValue / 2)) # control the speed based on the absolute value read from sensor if(sensorValue < -2): ## Turn the external LED on ## Turn only the internal green LED on ## Make motor go backward elif(sensorValue > 2): ## Turn the external LED on ## Turn only the internal red LED on ## Make motor go forward else: ## Turn the external LED on
def __init__(self, mic, beam, deck): self.mic = mic self.beam = beam self.deck = deck self.leds = [LED(1), LED(2), LED(3), LED(4)]
#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 # #########################
import sensor, time, image from pyb import LED # Reset sensor sensor.reset() # Sensor settings sensor.set_contrast(3) sensor.set_gainceiling(16) # HQVGA and GRAYSCALE are the best for face tracking. sensor.set_framesize(sensor.HQVGA) sensor.set_pixformat(sensor.GRAYSCALE) # LEDs red_led = LED(1) green_led = LED(2) # Load Haar Cascade # By default this will use all stages, lower satges is faster but less accurate. face_cascade = image.HaarCascade("frontalface", stages=25) print(face_cascade) # FPS clock clock = time.clock() while (True): clock.tick() # Capture snapshot img = sensor.snapshot()
import maf.eventloop as ev import maf.defs as defs import maf.mainloop_timer as mt from pyb import LED BLINK_INTERVALS = [83, 115, 237, 543] leds = [LED(1), LED(2), LED(3), LED(4)] blink_timers = [None] * len(leds) def blink_callback(arg): ndx = arg leds[ndx].toggle() mt.schedule(blink_timers[ndx], BLINK_INTERVALS[ndx]) for ndx in range(len(leds)): blink_timers[ndx] = mt.new(blink_callback, ndx) mt.schedule(blink_timers[ndx], BLINK_INTERVALS[ndx]) while True: ev.dispatch()
# Untitled - By: range - Wed Apr 1 2020 import sensor, image, time from pyb import LED, UART EXPOSURE_TIME_SCALE = 0.06 #Sensor settings sensor.reset() sensor.set_pixformat(sensor.RGB565) sensor.set_framesize(sensor.QVGA) sensor.skip_frames(time=2000) sensor.set_auto_gain(False) # must be turned off for color tracking sensor.set_auto_whitebal(False) # must be turned off for color tracking led = LED(2) led.on() current_exposure_time_in_microseconds = sensor.get_exposure_us() sensor.set_auto_exposure(False, \ exposure_us = int(current_exposure_time_in_microseconds * EXPOSURE_TIME_SCALE)) clock = time.clock() uart = UART(3, 57600) #main loop while (True): clock.tick() img = sensor.snapshot() for blob in img.find_blobs([(15, 40, -70, -8, -20, 60)], pixels_threshold=200,
from time import sleep import sys ######################### # 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()
# https://github.com/hmaerki/micropython/tree/master/canbus_example from pyb import CAN from pyb import LED import micropython ledBlue = LED(1) IDs = (122, 123, 124, 125) # 50kBaud can = CAN(1, CAN.NORMAL, extframe=False, prescaler=40, sjw=1, bs1=14, bs2=6) can.setfilter(0, CAN.LIST16, 0, IDs) def my_handler_mainloop(reason): (id, isRTR, filterMatchIndex, telegram) = can.recv(0) print("received:", telegram) if telegram == b'on': ledBlue.on() else: ledBlue.off() def my_canbus_interrupt(bus, reason): # Don't handle code in the interrupt service routine. # Schedule a task to be handled soon if reason == 0: # print('pending') micropython.schedule(my_handler_mainloop, reason) return
# romiserver.py for Micropython on Pyboard # # This module is a reads command on the UART of the Pyboard to drive a Romi chassis. # The commands are sent on the serial link by an ESP32 which runs an HTTP and a # WebSocket server to receive commands from the user. # # © Frédéric Boulanger <*****@*****.**> # 2020-04-02 -- 2020-05-24 # This software is licensed under the Eclipse Public License 2.0 ############ from pyb import UART, Pin, LED from romipyb import RomiPlatform # UART(1) is on TX=X9/RX=X10 uart = UART(1, baudrate=115200, timeout=1000) led = LED(4) # the blue LED romp = RomiPlatform() lm = romp.leftmotor rm = romp.rightmotor def sendStatus(): status = "UPDATE %d %d %f %d %f\r\n" % \ (led.intensity(), lm.count_a, lm.get_rpms(), rm.count_a, rm.get_rpms() ) uart.write(status.encode())
# ||| EXPOSURE ||| curr_exposure = sensor.get_exposure_us() sensor.set_auto_exposure(False, exposure_us = int(curr_exposure)) # ||| WHITE BAL ||| sensor.set_auto_whitebal(False, rgb_gain_db=curr_wbal) # ||| SET VALUES & WINDOWING ||| sensor.set_windowing(vwin_val) sensor.set_saturation(3) sensor.set_brightness(-3) sensor.set_contrast(3) # ||| INDICATOR LED ||| LED(1).on() time.sleep(100) LED(1).off() # ||| SCANS FOR BIGGEST BLOB ||| def BiggestBlob(bBlob): if not bBlob: return None maxBlob = bBlob[0] for blob in bBlob: if blob.area() > maxBlob.area(): maxBlob = blob return maxBlob # ||| MAIN LOOP ||| while(True):
def has_pressed(self): """ Check if the button as been pressed somehow """ if self.counter > 0: self.counter = 0 # reset the counter return True return False # CTRL-C / Copy will be wired to X9 pin_S11 = Pin("S11", Pin.IN, Pin.PULL_UP) btn_copy = Btn(pin_S11) # CTRL-C / Paste will be wired to X10 pin_S13 = Pin("S13", Pin.IN, Pin.PULL_UP) btn_paste = Btn(pin_S13) # Switch RED LED on = Keyboard is running LED(1).on() try: # Reading the keys while True: btn_copy.update() if btn_copy.has_pressed: sendchr('c', hid, kmap, modifiers=[CTRL]) btn_paste.update() if btn_paste.has_pressed: sendchr('v', hid, kmap, modifiers=[CTRL]) except: LED(1).off() # Switch of Keyboard is no more running LED(4).on() # Light blue LED in case of trouble raise #forward exception
sensor.__write_reg(0x3025, 0x00) sensor.__write_reg(0x3026, 0x00) sensor.__write_reg(0x3027, 0x00) sensor.__write_reg(0x3028, 0x00) sensor.__write_reg(0x3029, 0x7f) sensor.__write_reg(0x3000, 0x00) while (True): result = sensor.__read_reg(0x3029) print('FW_STATUS: %X' % result) if result != 0x7F: break sleep(500) blue_led = LED(1) KEY = Pin('C13', Pin.IN, Pin.PULL_DOWN) sensor.reset() sensor.set_pixformat(sensor.RGB565) sensor.set_framesize(sensor.QVGA) if sensor.get_id() != sensor.OV5640: print('Only run for ov5640') sys.exit(0) print('ov5640 AF Firmware Init ...') OV5640AF_Init() clock = time.clock()
from pyb import CAN from pyb import LED red_led = LED(1) can = CAN(2, CAN.LOOPBACK) #can.setfilter(0, CAN.LIST16, 0, (123, 124, 125, 126)) # set a filter to receive messages with id=123, 124, 125 and 126 can.send('message!', 123) # send a message with id 123 value = can.recv(0) # receive message on FIFO 0 if value[0] == 123: red_led.LED.on() print(value[3])
''' ------------------------------------------------------- Name: main Creator: Higor Alves ------------------------------------------------------- ''' import pyb from pyb import Pin, LED # Configure X2:4, X7 as setting input pin - pull_up to receive switch settings s0=Pin('Y3',pyb.Pin.IN,pyb.Pin.PULL_UP) s1=Pin('X6',pyb.Pin.IN,pyb.Pin.PULL_UP) r_LED = LED(1) g_LED = LED(2) y_LED = LED(3) b_LED = LED(4) ''' Define various test functions ''' def read_sw(): value = 3 - (s0.value() + 2*s1.value()) if (not s0.value()): y_LED.on() if (not s1.value()): g_LED.on() return value if read_sw() == 0: print('Running Milestone 1: BLE Control')
###if False then lane is White, else Yellow ### Imports import sensor, pyb, math, time, mjpeg from pyb import LED, Pin, Timer ### constants steering_direction = -1 # use this to revers the steering if your car goes in the wrong direction steering_gain = 1.7 # calibration for your car's steering sensitivity steering_center = 53 # set to your car servo's center point kp = 0.8 # P term of the PID ki = 0.0 # I term of the PID kd = 0.4 # D term of the PID set_angle = 90 # this is the desired steering angle (straight ahead) radians_degrees = 57.3 # constant to convert from radians to degrees blue_led = LED(3) ### parameters Yellow = True MAG_THRESHOLD = 3 #magnitude of line in hough transform THD_WHITE = (240, 255) #threshold for both yellow and white THD_YELLOW = (180, 255) THD = THD_YELLOW if Yellow else THD_WHITE old_error = 0 measured_angle = 0 p_term = 0 i_term = 0 d_term = 0 old_time = pyb.millis() record_time = 50000 #in ms cruise_speed = 30 # we dont change it
thresholds = [(30, 100, 15, 127, 15, 127), # generic_red_thresholds (0, 83, -128, 15, -128, 127), # generic_green_thresholds (0, 100, -128, -10, -128, 51)] # generic_blue_thresholds # You may pass up to 16 thresholds above. However, it's not really possible to segment any # scene with 16 thresholds before color thresholds start to overlap heavily. cruise_speed = 0 # how fast should the car drive, range from 1000 to 2000 steering_direction = -1 # use this to revers the steering if your car goes in the wrong direction steering_gain = 1.1 # calibration for your car's steering sensitivity steering_center = 80 # set to your car servo's center point kp = 0.4 # P term of the PID ki = 0.0 # I term of the PID kd = 0.3 # D term of the PID red_led = LED(1) green_led = LED(2) blue_led = LED(3) ir_led = LED(4) old_error = 0 measured_angle = 0 set_angle = 90 # this is the desired steering angle (straight ahead) p_term = 0 i_term = 0 d_term = 0 old_time = pyb.millis() def led_control(x): if (x&1)==0: red_led.off() elif (x&1)==1: red_led.on()
buf = ESP_UART.read().decode().replace('\r','').replace('\n','').replace(' ','') print(buf) if buf.find('busyp') > -1 or buf.find('ERROR') > -1: # AT指令执行失败 # 结束程序排查原因 break elif buf.find('ATOK') > -1: # 说明AT指令执行成功 #if 'ATOK' in buf: # 成功进入AT指令模式 # 设置WIFI模式 sendToUart(CWMODE_CUR) elif buf.find(CWMODE_CUR) > -1: # 设置sta模式成功,连接AP sendToUart(CWJAP_CUR) LED(1).on() elif buf.find('WIFIGOTIP') > -1: # 连接AP成功 # 连接TCP Server成功,发送数据 pyb.delay(150) sendToUart(CIPSTART) LED(2).on() elif buf.find(CIPSTART) > -1: # 连接TCP Server成功,发送数据 CIPSEND = CIPSEND % str(len(msg)) sendToUart(CIPSEND) LED(3).on() elif buf.find('>') > -1: # 发送数据 sendToUart(msg) LED(4).on()
oled = OLED_938(pinout={ 'sda': 'Y10', 'scl': 'Y9', 'res': 'Y8' }, height=64, external_vcc=False, i2c_devid=61) oled.poweron() oled.init_display() # define ports for microphone, LEDs and trigger out (X5) mic = ADC(Pin('Y11')) MIC_OFFSET = 1523 # ADC reading of microphone for silence dac = pyb.DAC(1, bits=12) # Output voltage on X5 (BNC) for debugging b_LED = LED(4) # flash for beats on blue LED N = 160 # size of sample buffer s_buf[] s_buf = array('H', 0 for i in range(N)) # reserve buffer memory ptr = 0 # sample buffer index pointer buffer_full = False # semaphore - ISR communicate with main program def flash(): # routine to flash blue LED when beat detected b_LED.on() pyb.delay(20) b_LED.off() def energy(buf): # Compute energy of signal in buffer sum = 0
# Untitled - By: Deer - 周三 11月 29 2017 import sensor import time from pyb import LED from pyb import UART sensor.reset() sensor.set_pixformat(sensor.GRAYSCALE) #设定采集图像回灰度 sensor.set_framesize(sensor.QVGA) #设定画面大小 sensor.skip_frames(10) grayscale_thres = (110, 255) #设定二值化阈值 thing_thres = (0, 70) #设定查找颜色范围 red_led = LED(1) #端口控制 LED亮500ms red_led.on() time.sleep(500) red_led.off() uart = UART(3, 9600, timeout_char=1000) #串口控制,第一个参数为默认,第二个是波特率,第三个是超时设定 def find_max(blobs): #函数查找最大的色块 max_size = 0 for blob in blobs: if blob.pixels() > max_size: max_blob = blob max_size = blob.pixels() return max_blob
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.
''' 实验名称:点亮LED(4)蓝灯 版本:v1.0 日期:2020.12 作者:01Studio ''' from pyb import LED LED(4).on()
from pyb import UART ## One time setup sensor.reset() sensor.set_pixformat(sensor.RGB565) sensor.set_framesize(sensor.QVGA) sensor.skip_frames(time=2000) clock = time.clock() uart = UART(3, 115200, timeout_char=1000) img = sensor.snapshot() SIZE = (img.width(), img.height()) CENTER = (img.width() / 2, img.height() / 2) AREA = img.size() green_led = LED(1) blue_led = LED(2) #broken1_led = LED(3) #broken2_led = LED(4) appleRoi = () #apple_th = (30, 75, 50, 70 ,0, 40) apple_th = (30, 75, 40, 70, 20, 60) #apple_th = (60, 90, 20, 60, -20, 10) #maxRatio = 1.5 #minDensity = 0.4 #maxPixelCnt = deltaXPixPerCycle = 2 deltaYPixPerCycle = 2
# Untitled - By: Gehaha - 周四 11月 29 2018 from pyb import LED led = LED(3) led.toggle() led.on() led.off()