class lcd(): def __init__(self,uart=3): #UART serial self.lcd = UART(uart, 115200) # init with given baudrate #set lcd to same baudrate b = bytearray(3) b[0] = 0x7C b[1] = 0x07 b[2] = 0x36 self.lcd.write(b) #set background duty b = bytearray(3) b[0] = 0x7C b[1] = 0x02 b[2] = 80 self.lcd.write(b) def clear(self): b = bytearray(2) b[0] = 0x7c b[1] = 0x00 self.lcd.write(b) def send(self,string): self.lcd.write(string) def replace(self,string): self.clear() self.lcd.write(string)
def __init__(self,uart=3): #UART serial self.lcd = UART(uart, 115200) # init with given baudrate #set lcd to same baudrate b = bytearray(3) b[0] = 0x7C b[1] = 0x07 b[2] = 0x36 self.lcd.write(b) #set background duty b = bytearray(3) b[0] = 0x7C b[1] = 0x02 b[2] = 80 self.lcd.write(b)
def init(): print ("Initializing") # Initialize GPS # UART(1) is on PB: # (TX, RX) # (X9, X10) # (PB6, PB7) uart = UART(1, 9600) # Maybe add read_buf_len=128? # Maybe add timeout_char=200 uart.init(9600, bits=8, stop=1, parity=None, timeout=5000) # Initialize Radio (RFM69) # SPI(1) is on PA: # (DIO0, RESET, NSS, SCK, MISO, MOSI) # (X3, X4, X5, X6, X7, X8) # (PA2, PA3, PA4, PA5, PA6, PA7) rfm69 = RFM69.RFM69() sleep(1) # Check version if (rfm69.getVersion() == 0x24): print ("RFM69 Version Valid: 0x24") else: print ("RFM69 Version Invalid!") return "FAULT" return "GPS_ACQ"
def uart_hash(): # initialize UART(6) to output TX on Pin Y1 uart = UART(6) while True: uart.init(9600, bits=8, parity = 0, stop = 2) uart.writechar(ord('#')) # letter '#' pyb.delay(5) # delay by 5ms
class MTC(): def __init__(self): self.clock = {'frames':0, 'seconds':0, 'mins':0, 'hours':0, 'mode':0} self.frame_count = 1 self.uart1 = UART(1) self.message = [-1] * 8 self.uart1.init(31250, parity=None, stop=1,read_buf_len=1) print(dir(self.uart1)) def saveClock(self): self.clock['frames'] = (self.message[1] << 4) + self.message[0] # 2 half bytes 000f ffff self.clock['seconds'] = (self.message[3] << 4) + self.message[2] # 2 half bytes 00ss ssss self.clock['mins'] = (self.message[5] << 4) + self.message[4] # 2 half bytes 00mm mmmm self.clock['hours'] = ((self.message[7] & 1) << 4) + self.message[6] # 2 half bytes 0rrh hhhh the msb has to be masked as it contains the mode self.clock['mode'] = ((self.message[7] & 6) >> 1) # get the fps mode by masking 0rrh with 0110 (6) def getMs(self): self.readFrame() mins = ((self.clock['hours'] * 60) + self.clock['mins']) seconds = (mins * 60) + self.clock['seconds'] frames = (seconds * 25) + self.clock['frames'] milliseconds = frames * 40 return milliseconds def readFrame(self): indice = 0 self.message = [-1] * 8 while True: data = self.uart1.read(1) if data != None: if ord(data) == 241: # if Byte for quater frame message try: mes = ord(self.uart1.read(1)) # Read next byte except: continue piece = mes >> 4 # Get which part of the message it is (e.g seconds mins) if piece == indice: self.message[piece] = mes & 15 # store message using '&' to mask the bit type indice += 1 if indice > 7: self.saveClock() break #self.uart1.deinit() return self.clock
class ESP8266(object): def __init__(self): self.uart = UART(6, 115200) def write(self, command): self.uart.write(command) count = 5 while count >= 0: if self.uart.any(): print(self.uart.readall().decode('utf-8')) time.sleep(0.1) count-=1
class UART_Port: """Implements a port which can send or receive commands with a bioloid device using the pyboard UART class. This particular class takes advantage of some features which are only available on the STM32F4xx processors. """ def __init__(self, uart_num, baud): self.uart = UART(uart_num) self.baud = 0 self.set_baud(baud) base_str = 'USART{}'.format(uart_num) if not hasattr(stm, base_str): base_str = 'UART{}'.format(uart_num) self.uart_base = getattr(stm, base_str) # Set HDSEL (bit 3) in CR3 - which puts the UART in half-duplex # mode. This connects Rx to Tx internally, and only enables the # transmitter when there is data to send. stm.mem16[self.uart_base + stm.USART_CR3] |= (1 << 3) def any(self): return self.uart.any() def read_byte(self): """Reads a byte from the bus. This function will return None if no character was read within the designated timeout (set when we call self.uart.init). """ byte = self.uart.readchar() if byte >= 0: return byte def set_baud(self, baud): """Sets the baud rate. Note, the pyb.UART class doesn't have a method for setting the baud rate, so we need to reinitialize the uart object. """ if self.baud != baud: self.baud = baud # The max Return Delay Time is 254 * 2 usec = 508 usec. The default # is 500 usec. So using a timeout of 2 ensures that we wait for # at least 1 msec before considering a timeout. self.uart.init(baudrate=baud, timeout=2) def write_packet(self, packet_data): """Writes an entire packet to the serial port.""" _write_packet(self.uart_base, packet_data, len(packet_data))
def __init__(self, uart_port): self.sbus = UART(uart_port, 100000) self.sbus.init(100000, bits=8, parity=0, stop=2, timeout_char=3, read_buf_len=250) # constants self.START_BYTE = b'0f' self.END_BYTE = b'00' self.SBUS_FRAME_LEN = 25 self.SBUS_NUM_CHAN = 18 self.OUT_OF_SYNC_THD = 10 self.SBUS_NUM_CHANNELS = 18 self.SBUS_SIGNAL_OK = 0 self.SBUS_SIGNAL_LOST = 1 self.SBUS_SIGNAL_FAILSAFE = 2 # Stack Variables initialization self.validSbusFrame = 0 self.lostSbusFrame = 0 self.frameIndex = 0 self.resyncEvent = 0 self.outOfSyncCounter = 0 self.sbusBuff = bytearray(1) # single byte used for sync self.sbusFrame = bytearray(25) # single SBUS Frame self.sbusChannels = array.array('H', [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) # RC Channels self.isSync = False self.startByteFound = False self.failSafeStatus = self.SBUS_SIGNAL_FAILSAFE
def __init__(self): self.clock = {'frames':0, 'seconds':0, 'mins':0, 'hours':0, 'mode':0} self.frame_count = 1 self.uart1 = UART(1) self.message = [-1] * 8 self.uart1.init(31250, parity=None, stop=1,read_buf_len=1) print(dir(self.uart1))
def __init__(self, uart_num, pin_rw, dev_id): self.error = [] self.uart = UART(uart_num) self.uart.init(57600, bits=8, parity=0, timeout=10, read_buf_len=64) self.pin_rw = Pin(pin_rw) self.pin_rw.init(Pin.OUT_PP) self.pin_rw.value(0) self.dev_id = dev_id self.file_parts = 0 self.file_parts_i = 1 self.file_is_open = False
def __init__(self, uart_num, baud): self.uart = UART(uart_num) self.baud = 0 self.set_baud(baud) base_str = 'USART{}'.format(uart_num) if not hasattr(stm, base_str): base_str = 'UART{}'.format(uart_num) self.uart_base = getattr(stm, base_str) # Set HDSEL (bit 3) in CR3 - which puts the UART in half-duplex # mode. This connects Rx to Tx internally, and only enables the # transmitter when there is data to send. stm.mem16[self.uart_base + stm.USART_CR3] |= (1 << 3)
def init(self, type=BLE_SHIELD): self.deinit() if type==self.BLE_SHIELD: self.rst=Pin("P7",Pin.OUT_OD,Pin.PULL_NONE) self.uart=UART(3,115200,timeout_char=1000) self.type=self.BLE_SHIELD self.rst.low() sleep(100) self.rst.high() sleep(100) self.uart.write("set sy c m machine\r\nsave\r\nreboot\r\n") sleep(1000) self.uart.readall() # clear
def uart_hashtag(): the_word = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' # initialize X5 as trigger output uart = UART(6) uart.init(9600, bits=8, parity = None, stop = 2) while True: # initialize UART(6) to output TX on Pin Y1 for i in range(36): uart.writechar(ord(the_word[i])) uart.writechar(13) uart.writechar(10) pyb.delay(1000)
def remote(): #initialise UART communication uart = UART(6) uart.init(9600, bits=8, parity = None, stop = 2) # define various I/O pins for ADC adc_1 = ADC(Pin('X19')) adc_2 = ADC(Pin('X20')) # set up motor with PWM and timer control A1 = Pin('Y9',Pin.OUT_PP) A2 = Pin('Y10',Pin.OUT_PP) pwm_out = Pin('X1') tim = Timer(2, freq = 1000) motor = tim.channel(1, Timer.PWM, pin = pwm_out) # Motor in idle state A1.high() A2.high() speed = 0 DEADZONE = 5 # Use keypad U and D keys to control speed while True: # loop forever until CTRL-C while (uart.any()!=10): #wait we get 10 chars n = uart.any() command = uart.read(10) if command[2]==ord('5'): if speed < 96: speed = speed + 5 print(speed) elif command[2]==ord('6'): if speed > - 96: speed = speed - 5 print(speed) if (speed >= DEADZONE): # forward A1.high() A2.low() motor.pulse_width_percent(speed) elif (speed <= -DEADZONE): A1.low() # backward A2.high() motor.pulse_width_percent(-speed) else: A1.low() # idle A2.low()
class WIFI: """docstring for wifi""" def __init__(self, uart, baudrate = 115200): """ uart = uart #1-6, baudrate must match what is set on the ESP8266. """ self._uart = UART(uart, baudrate) def write( self, aMsg ) : self._uart.write(aMsg) res = self._uart.readall() if res: print(res.decode("utf-8")) def read( self ) : return self._uart.readall().decode("utf-8") def _cmd( self, cmd ) : """ Send AT command, wait a bit then return results. """ self._uart.write("AT+" + cmd + "\r\n") udelay(500) return self.read() @property def IP(self): return self._cmd("CIFSR") @property def networks( self ) : return self._cmd("CWLAP") @property def baudrate(self): return self._cmd("CIOBAUD?") @baudrate.setter def baudrate(self, value): return self._cmd("CIOBAUD=" + str(value)) @property def mode(self): return self._cmd("CWMODE?") @mode.setter def mode(self, value): self._cmd("CWMODE=" + str(value)) def connect( self, ssid, password = "" ) : """ Connect to the given network ssid with the given password """ constr = "CWJAP=\"" + ssid + "\",\"" + password + "\"" return self._cmd(constr) def disconnect( self ) : return self._cmd("CWQAP") def reset( self ) : return self._cmd("RST")
def keypad(): key = ('1','2','3','4','U','D','L','R') uart = UART(6) uart.init(9600, bits=8, parity = None, stop = 2) while True: while (uart.any()!=10): #wait we get 10 chars n = uart.any() command = uart.read(10) key_index = command[2]-ord('1') if (0 <= key_index <= 7) : key_press = key[key_index] if command[3]==ord('1'): action = 'pressed' elif command[3]==ord('0'): action = 'released' else: action = 'nothing pressed' print('Key',key_press,' ',action)
import ustruct # #white_threshold_01 = ((95, 100, -18, 3, -8, 4)); #白色阈值 light_threshold = [(59, 100, 26, 127, -128, 127),(59, 100, -128, -40, -128, 127)]; #1红灯 2绿灯 road_threshold = [(23, 0, -45, 19, -31, 28)]; #黑线道路 ROI = (0, 100, 320, 40) 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 clock = time.clock() uart = UART(3,115200) #定义串口3变量 uart.init(115200, bits=8, parity=None, stop=1) # init with given parameters #寻找红绿灯 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 sending_data(LED_color,ratio): global uart; #frame=[0x2C,18,cx%0xff,int(cx/0xff),cy%0xff,int(cy/0xff),0x5B];
(21, 84, 22, 90, -18, 58), # 橙红色块 (30, 100, -64, -8, -32, 32), # generic_green_thresholds (0, 30, 0, 64, -128, 0) ] # generic_blue_thresholds sensor.reset() # 传感器复位 sensor.set_pixformat( sensor.RGB565 ) # RGB565即一个彩色图像点由RGB三个分量组成,总共占据2Byte,高5位为R分量,中间6位为G分量,低5位为B分量 sensor.set_framesize(sensor.QQVGA) # 320*240 sensor.skip_frames(time=500) # 跳过,等待摄像头稳定 sensor.set_auto_gain(False) # 自动增益在颜色识别中一般关闭,不然会影响阈值 sensor.set_auto_whitebal(False) # 白平衡在颜色识别中一般关闭,不然会影响阈值 clock = time.clock() # 构造时钟对象 uart = UART(3, 115200) uart.init(115200, bits=8, parity=None, stop=1, timeout_char=1000) # 使用给定参数初始化 timeout_char是以毫秒计的等待字符间的超时时长 class ctrl_info(object): WorkMode = 0x03 # 色块检测模式 0x01为固定单颜色识别 0x02为自主学习颜色识别 0x03 巡线 Threshold_index = 0x00 # 阈值编号 ctrl = ctrl_info() # 定义控制信息类 single_blob.InitSuccess_LED() # 初始化完成 Green LED 快闪2下 '''-----------------------------------------------初始化分割线------------------------------------------------''' while (True):
class uart_tmcl_interface(tmcl_module_interface, tmcl_host_interface): def __init__(self, port=3, data_rate=9600, host_id=2, module_id=1, debug=False): tmcl_module_interface.__init__(self, host_id, module_id, debug) tmcl_host_interface.__init__(self, host_id, module_id, debug) self.__uart = UART(port, data_rate) self.__uart.init(baudrate=data_rate, bits=8, parity=None, stop=1, timeout=10000, timeout_char=10000) def __enter__(self): return self def __exit__(self, exitType, value, traceback): del exitType, value, traceback self.close() def close(self): self.__uart.deinit() return 0 def data_available(self, hostID=None, moduleID=None): del hostID, moduleID return self.__uart.any() def _send(self, hostID, moduleID, data): del hostID, moduleID self.__uart.write(data) def _recv(self, hostID, moduleID): del hostID, moduleID read = self.__uart.read(9) return read def printInfo(self): pass def enableDebug(self, enable): self._debug = enable @staticmethod def supportsTMCL(): return True @staticmethod def supportsCANopen(): return False @staticmethod def available_ports(): return set([2, 3, 4])
y = 0 last_dot = 0 class receive(object): #串口接收类 uart_buf = [] _data_len = 0 _data_cnt = 0 state = 0 #创建对象 Receive = receive() clock = time.clock() dot = Dot() uart = UART(3, 115200) uart.init(115200, timeout_char=1000) #Global variables End # Init Function Start # @param # is_debug: 选则debug or release模式 # pixformat: 图像模式选则 # delay_time:初始化延时时间 # @note 相机初始化,设定一些参数,注意加上延时,否则会影响自动曝光 def init(is_debug, pixformat, delay_time): uart.deinit() sensor.reset() if pixformat == "GRAY":
class SBUSReceiver: def __init__(self): self.sbus = UART(3, 100000) self.sbus.init(100000, bits=8, parity=0, stop=2, timeout_char=3, read_buf_len=250) # constants self.START_BYTE = b'0f' self.END_BYTE = b'00' self.SBUS_FRAME_LEN = 25 self.SBUS_NUM_CHAN = 18 self.OUT_OF_SYNC_THD = 10 self.SBUS_NUM_CHANNELS = 18 self.SBUS_SIGNAL_OK = 0 self.SBUS_SIGNAL_LOST = 1 self.SBUS_SIGNAL_FAILSAFE = 2 # Stack Variables initialization self.validSbusFrame = 0 self.lostSbusFrame = 0 self.frameIndex = 0 self.resyncEvent = 0 self.outOfSyncCounter = 0 self.sbusBuff = bytearray(1) # single byte used for sync self.sbusFrame = bytearray(25) # single SBUS Frame self.sbusChannels = array.array('H', [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) # RC Channels self.isSync = False self.startByteFound = False self.failSafeStatus = self.SBUS_SIGNAL_FAILSAFE # logger.info("SBUS Stack Started") def get_rx_channels(self): return self.sbusChannels def get_rx_channel(self, num_ch): return self.sbusChannels[num_ch] def get_failsafe_status(self): return self.failSafeStatus def get_rx_report(self): rep = {} rep['Valid Frames'] = self.validSbusFrame rep['Lost Frames'] = self.lostSbusFrame rep['Resync Events'] = self.resyncEvent return rep def decode_frame(self): # TODO: DoubleCheck if it has to be removed for i in range(0, self.SBUS_NUM_CHANNELS - 2): self.sbusChannels[i] = 0 # counters initialization byte_in_sbus = 1 bit_in_sbus = 0 ch = 0 bit_in_channel = 0 for i in range(0, 175): # TODO Generalization if self.sbusFrame[byte_in_sbus] & (1 << bit_in_sbus): self.sbusChannels[ch] |= (1 << bit_in_channel) bit_in_sbus += 1 bit_in_channel += 1 if bit_in_sbus == 8: bit_in_sbus = 0 byte_in_sbus += 1 if bit_in_channel == 11: bit_in_channel = 0 ch += 1 # Decode Digitals Channels # Digital Channel 1 if self.sbusFrame[self.SBUS_FRAME_LEN - 2] & (1 << 0): self.sbusChannels[self.SBUS_NUM_CHAN - 2] = 1 else: self.sbusChannels[self.SBUS_NUM_CHAN - 2] = 0 # Digital Channel 2 if self.sbusFrame[self.SBUS_FRAME_LEN - 2] & (1 << 1): self.sbusChannels[self.SBUS_NUM_CHAN - 1] = 1 else: self.sbusChannels[self.SBUS_NUM_CHAN - 1] = 0 # Failsafe self.failSafeStatus = self.SBUS_SIGNAL_OK if self.sbusFrame[self.SBUS_FRAME_LEN - 2] & (1 << 2): self.failSafeStatus = self.SBUS_SIGNAL_LOST if self.sbusFrame[self.SBUS_FRAME_LEN - 2] & (1 << 3): self.failSafeStatus = self.SBUS_SIGNAL_FAILSAFE def get_sync(self): if self.sbus.any() > 0: if self.startByteFound: if self.frameIndex == (self.SBUS_FRAME_LEN - 1): self.sbus.readinto(self.sbusBuff, 1) # end of frame byte if self.sbusBuff[0] == 0: # TODO: Change to use constant var value self.startByteFound = False self.isSync = True self.frameIndex = 0 else: self.sbus.readinto(self.sbusBuff, 1) # keep reading 1 byte until the end of frame self.frameIndex += 1 else: self.frameIndex = 0 self.sbus.readinto(self.sbusBuff, 1) # read 1 byte if self.sbusBuff[0] == 15: # TODO: Change to use constant var value self.startByteFound = True self.frameIndex += 1 def get_new_data(self): if self.isSync: if self.sbus.any() >= self.SBUS_FRAME_LEN: self.sbus.readinto(self.sbusFrame, self.SBUS_FRAME_LEN) # read the whole frame if (self.sbusFrame[0] == 15 and self.sbusFrame[ self.SBUS_FRAME_LEN - 1] == 0): # TODO: Change to use constant var value self.validSbusFrame += 1 self.outOfSyncCounter = 0 self.decode_frame() else: self.lostSbusFrame += 1 self.outOfSyncCounter += 1 if self.outOfSyncCounter > self.OUT_OF_SYNC_THD: self.isSync = False self.resyncEvent += 1 else: self.get_sync()
(input_x, input_y, input_w, input_h)) img.draw_rectangle((input_x, input_y, input_w, input_h), 127) return blobs def overlap_check(blob1, blob2): if ((blob1[0].y() + 8) < blob2[0].y()) or (blob1[0].y() > (blob2[0].y() + 8)) or ( (blob1[0].x() + 8) < blob2[0].x()) or (blob1[0].x() > (blob2[0].x() + 8)): return True else: return False uart = UART(3, 115200) count1 = 0 count2 = 0 theta = None rho = None intersection = None thetas = [] rhos = [] last = [] last_list = [999, 999, 0] mask_straight = True mask_none = False output_str = " " while (True): clock.tick() src_img = sensor.snapshot()
'sda': 'Y10', 'scl': 'Y9', 'res': 'Y8' }, height=64, external_vcc=False, i2c_devid=61) # LED and Potentiometer Pins pot = ADC(Pin('X11')) # IMU connected to X9 and X10 imu = MPU6050(1, False) # Use I2C port 1 on Pyboard # Start Bluetooth uart = UART(6) uart.init(9600, bits=8, parity=None, stop=2) # Starting Program oled.poweron() oled.init_display() oled.draw_text(0, 0, 'Group 7') oled.draw_text(0, 10, 'Self Balance BlueTooth') oled.draw_text(0, 20, 'Press USR button') oled.display() print('Self balance Bluetooth') print('Waiting for button press') # Button Press to resume trigger = pyb.Switch() while not trigger():
# main.py -- put your code here! from pyb import UART, SPI, Pin, Timer import random #liste ennemy ennemy = [] #tableau pour stocker les robots ennemy nb_missile = [] #tableau pour stocker les missiles #init uart2, 115200 bauds, 8bits numero_uart = 2 uart = UART(numero_uart) uart.init(115200, bits=8, parity=None, stop=1) #init timer t = Timer(4, freq = 1) t1 = Timer(2, freq = 2) #init chip select CS = Pin("PE3", Pin.OUT_PP) #init spi SPI_1 = SPI( 1, # SPI1: PA5, PA6, PA7 SPI.MASTER, baudrate=50000, polarity=0, phase=0,)
def readgps(uart): u2 = UART(uart, 115200) u2.init(115200, timeout=100) u2.write('AT+GPSPWR=1\r\n') u2.write('AT+GPSRST=2,0\r\n') u2.write('AT+GPSLOC=1\r\n') pyb.delay(1000) _dataRead = u2.read() u2.write('AT+GPSLOC=0\r\n') pyb.delay(1000) _dataRead = u2.read() if _dataRead != None: if 60 < len(_dataRead) < 70: _dataRead = _dataRead.decode('utf-8') _dataRead1 = _dataRead.split(',') if len(_dataRead1) > 4: #*******************纬度计算******************** weidu = _dataRead1[1] WD = DataConver(weidu, 0) #*******************经度计算******************** jingdu = _dataRead1[2] JD = DataConver(jingdu, 1) return JD, WD return None
import sensor, image, time,pyb from pyb import UART uart = UART(3, 115200) BLUE_LED_PIN = 3 thresholds = (40, 130) #灰度值设置 ROI = (74,23,198,205) #开窗大小 sensor.reset() # 初始化摄像头 sensor.set_pixformat(sensor.GRAYSCALE) # 格式为 RGB565. sensor.set_framesize(sensor.QVGA) # 使用 QQVGA 速度快一些 sensor.set_windowing(ROI) sensor.skip_frames(10) # 跳过10帧,使新设置生效 sensor.set_auto_whitebal(False) clock = time.clock() # 追踪帧率 while(True): clock.tick() # Track elapsed milliseconds between snapshots(). img = sensor.snapshot() # 从感光芯片获得一张图像 pyb.LED(BLUE_LED_PIN).on() blobs = img.find_blobs([thresholds],pixel_threshold=3,threshold=3) if blobs: for b in blobs: img.draw_rectangle(b[0:4])
import char_lcd import binascii from pyb import UART from pyb import Pin, ADC i2c2 = I2C(2, I2C.MASTER, baudrate=20000) i2c2.mem_write(0xFF, 0x20, 0x0C) #Enable pull-ups i2c2.mem_write(0xFF, 0x20, 0x00) #Set pins as inputs i2c2.mem_write(0x00, 0x20, 0x14) #Drive outputs low d = char_lcd.HD44780(i2c2) #row1 DF, row2 FE, row3 FD, row4 F7 #Reading COL1.. ??? #VALO JUTTUJA i2 = I2C(1, I2C.MASTER, baudrate=50000) ser = UART(6, 115200) ser.init(115200, bits=8, parity=None, stop=1) adc = ADC(Pin('X1')) temp1 = 0 text = "" aika = "" x = "" typing = False kaksoispiste = False buttonpressed = False alarm = False lux = 300 def Valolampo():
#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, area_threshold=100, merge=True): # These values are stable all the time. img.draw_rectangle(blob.rect()) img.draw_cross(blob.cx(), blob.cy()) uart.write(str(blob.cx()) + "\n")
from pyb import UART # test we can correctly create by id or name for bus in (-1, 0, 1, 2, 3, 4, 5, 6, 7, "XA", "XB", "YA", "YB", "Z"): try: UART(bus, 9600) print("UART", bus) except ValueError: print("ValueError", bus) uart = UART(1) uart = UART(1, 9600) uart = UART(1, 9600, bits=8, parity=None, stop=1) print(uart) uart.init(2400) print(uart) print(uart.any()) print(uart.write('123')) print(uart.write(b'abcd')) print(uart.writechar(1)) # make sure this method exists uart.sendbreak() # non-blocking mode uart = UART(1, 9600, timeout=0) print(uart.write(b'1')) print(uart.write(b'abcd')) print(uart.writechar(1))
SPI = pyb.SPI(1) #DIN=>X8-MOSI/CLK=>X6-SCK #DIN =>SPI(1).MOSI 'X8' data flow (Master out, Slave in) #CLK =>SPI(1).SCK 'X6' SPI clock RST = pyb.Pin('X20') CE = pyb.Pin('X19') DC = pyb.Pin('X18') LIGHT = pyb.Pin('X17') lcd_5110 = upcd8544.PCD8544(SPI, RST, CE, DC, LIGHT) N2 = Pin('Y3', Pin.OUT_PP) N1 = Pin('Y6', Pin.OUT_PP) N1.low() pyb.delay(2000) N1.high() pyb.delay(10000) u2 = UART(4, 115200, timeout=100) while True: N2.low() if u2.any() > 0: _dataRead = u2.read() if _dataRead != None: print('原始数据=', _dataRead) print('原始数据长度:', len(_dataRead)) print('123', _dataRead[2:6]) RING = _dataRead[2:6] print('111', _dataRead[18:29]) HM = _dataRead[18:29] if (RING == b'RING'): N2.high() lcd_5110.lcd_write_string('Phone Number:', 0, 0)
######################### from pyb import UART, LED, Pin, Switch 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():
import time from pyb import UART import ujson import ubinascii import pyb import urequests as requests # client_id 为官网获取的AK, client_secret 为官网获取的SK host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=【官网获取的AK】&client_secret=【官网获取的SK】' response = requests.get(host) if response: print(response.json()) uart = UART(3, 19200) while(True): uart.write("Hello World!\n") if (uart.any()): img = uart.read() # client_id 为官网获取的AK, client_secret 为官网获取的SK host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=6kbvF4gXOvO3xuQplt3RSk7G&client_secret=taSQngCaay48FG3LTqZ4dyMm7qekZydf' response = requests.get(host) request_url = "https://aip.baidubce.com/rest/2.0/image-classify/v1/driver_behavior" # 二进制方式打开图片文件 #f = open('example.jpg', 'rb') params = {"image":img} access_token = response.json() request_url = request_url + "?access_token=" + access_token headers = {'content-type': 'application/x-www-form-urlencoded'} response = requests.post(request_url, data=params, headers=headers) if response: print (response.json())
from pyb import UART sensor.reset() sensor.set_contrast(1) sensor.set_gainceiling(16) sensor.set_framesize(sensor.QQVGA) sensor.set_pixformat(sensor.GRAYSCALE) template1 = image.Image("LorR1left.pgm") template2 = image.Image("LorR2right.pgm")#camera rotate 90 degrees clockwise uart = UART(3, 9600) clock = time.clock() #Run template matching while (True): clock.tick() inp = 1 #inp = uart.read() if inp: img = sensor.snapshot()
tim = Timer(2, freq = 1000) ch1 = tim.channel(1, Timer.PWM, pin = motor1) ch2 = tim.channel(2, Timer.PWM, pin = motor2) # Ultrasound Echo Initialising ----------------------------------- Trigger = Pin('X3', Pin.OUT_PP) Echo = Pin('X4',Pin.IN) # Create a microseconds counter. micros = pyb.Timer(5, prescaler=83, period=0x3fffffff) micros.counter(0) start = 0 # timestamp at rising edge of echo end = 0 # timestamp at falling edge of echo # ----------------------------------------------------------------- # initialise UART communication uart = UART(6) uart.init(9600, bits=8, parity = None, stop = 2) # ----------------------------------------------------------------- # initialise recording and traceback isFirstCommand = True # used for when recording first starts isRecording = False # helps to control pod previousTime = 0 # init a previous time variable to store in between commands durationList = [] # list of durations related to commandList commandList = [] # list of commands start = pyb.millis() # init a timer before operation begins def record(command): global isFirstCommand
def t_callback(timer): for flicker in flickers: flicker.update() tim = pyb.Timer(1, freq=timer_freq) # 2000Hz对应定时间隔0.5ms tim.callback(t_callback) # 上位机通过串口发送ascii码来指示pyboard显示当前ssvep的分类结果和当前执行的任务 # '0','1','2'.... 对应实际的0,1,2...LED, 指示其常亮 # '10','11',... 对应指示相关的LED闪烁表示执行该命令,指示其闪烁 led = pyb.LED(1) c = 0 uart = UART(1, 9600) while True: n = uart.any() if n > 0: buf = uart.read(n)[-1] #丢弃历史命令 cmd = int(buf) for i in range(5): flickers[i].set_mode(0, False) #全部复位 if cmd < 5: flickers[cmd].set_mode(0, True) else: flickers[cmd - 10].set_mode(1, 400) else: time.sleep_ms(50) c += 1
# ---------------------------------------------------- # Task 9: Use phone to control motor via Bluethooth import pyb from pyb import Pin, Timer, ADC, UART print('Task 9: Keypad controlling motor') #initialise UART communication uart = UART(6) uart.init(9600, bits=8, parity = None, stop = 2) # define various I/O pins for ADC adc_1 = ADC(Pin('X19')) adc_2 = ADC(Pin('X20')) # set up motor with PWM and timer control A1 = Pin('Y9',Pin.OUT_PP) A2 = Pin('Y10',Pin.OUT_PP) pwm_out = Pin('X1') tim = Timer(2, freq = 1000) motor = tim.channel(1, Timer.PWM, pin = pwm_out) # Motor in idle state A1.high() A2.high() speed = 0 DEADZONE = 5 # Use keypad U and D keys to control speed while True: # loop forever until CTRL-C while (uart.any()!=10): #wait we get 10 chars
oled = OLED_938(pinout={ 'sda': 'Y10', 'scl': 'Y9', 'res': 'Y8' }, height=64, external_vcc=False, i2c_devid=61) oled.poweron() oled.init_display() # IMU connected to X9 and X10 imu = MPU6050(1, False) # initialize UART on Y1 and Y2 uart = UART(6) uart.init(9600, bits=8, parity = None, stop = 2)\ # create motor class to drive motors motor = DRIVE() # Create the samples in sine array N_samp = 128 sig_freq = 1000 sine_array = array('H', 0 for i in range(N_samp)) # reserve space for array data_array = array('H', 0 for i in range(128)) # reserve space for data array for i in range(N_samp): sine_array[i] = int(2048 + 1800 * math.sin(2 * math.pi * i / N_samp)) ''' Define various test functions '''
from pyb import UART uart = UART(1) uart = UART(1, 9600) uart = UART(1, 9600, bits=8, stop=1, parity=None) print(uart) uart.init(1200) print(uart) uart.any() uart.send(1, timeout=500)
class SBUSReceiver: def __init__(self, uart_port): self.sbus = UART(uart_port, 100000) self.sbus.init(100000, bits=8, parity=0, stop=2, timeout_char=3, read_buf_len=250) # constants self.START_BYTE = b'0f' self.END_BYTE = b'00' self.SBUS_FRAME_LEN = 25 self.SBUS_NUM_CHAN = 18 self.OUT_OF_SYNC_THD = 10 self.SBUS_NUM_CHANNELS = 18 self.SBUS_SIGNAL_OK = 0 self.SBUS_SIGNAL_LOST = 1 self.SBUS_SIGNAL_FAILSAFE = 2 # Stack Variables initialization self.validSbusFrame = 0 self.lostSbusFrame = 0 self.frameIndex = 0 self.resyncEvent = 0 self.outOfSyncCounter = 0 self.sbusBuff = bytearray(1) # single byte used for sync self.sbusFrame = bytearray(25) # single SBUS Frame self.sbusChannels = array.array('H', [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) # RC Channels self.isSync = False self.startByteFound = False self.failSafeStatus = self.SBUS_SIGNAL_FAILSAFE def get_rx_channels(self): """ Used to retrieve the last SBUS channels values reading :return: an array of 18 unsigned short elements containing 16 standard channel values + 2 digitals (ch 17 and 18) """ return self.sbusChannels def get_rx_channel(self, num_ch): """ Used to retrieve the last SBUS channel value reading for a specific channel :param: num_ch: the channel which to retrieve the value for :return: a short value containing """ return self.sbusChannels[num_ch] def get_failsafe_status(self): """ Used to retrieve the last FAILSAFE status :return: a short value containing """ return self.failSafeStatus def get_rx_report(self): """ Used to retrieve some stats about the frames decoding :return: a dictionary containg three information ('Valid Frames','Lost Frames', 'Resync Events') """ rep = {} rep['Valid Frames'] = self.validSbusFrame rep['Lost Frames'] = self.lostSbusFrame rep['Resync Events'] = self.resyncEvent return rep def decode_frame(self): # TODO: DoubleCheck if it has to be removed for i in range(0, self.SBUS_NUM_CHANNELS - 2): self.sbusChannels[i] = 0 # counters initialization byte_in_sbus = 1 bit_in_sbus = 0 ch = 0 bit_in_channel = 0 for i in range(0, 175): # TODO Generalization if self.sbusFrame[byte_in_sbus] & (1 << bit_in_sbus): self.sbusChannels[ch] |= (1 << bit_in_channel) bit_in_sbus += 1 bit_in_channel += 1 if bit_in_sbus == 8: bit_in_sbus = 0 byte_in_sbus += 1 if bit_in_channel == 11: bit_in_channel = 0 ch += 1 # Decode Digitals Channels # Digital Channel 1 if self.sbusFrame[self.SBUS_FRAME_LEN - 2] & (1 << 0): self.sbusChannels[self.SBUS_NUM_CHAN - 2] = 1 else: self.sbusChannels[self.SBUS_NUM_CHAN - 2] = 0 # Digital Channel 2 if self.sbusFrame[self.SBUS_FRAME_LEN - 2] & (1 << 1): self.sbusChannels[self.SBUS_NUM_CHAN - 1] = 1 else: self.sbusChannels[self.SBUS_NUM_CHAN - 1] = 0 # Failsafe self.failSafeStatus = self.SBUS_SIGNAL_OK if self.sbusFrame[self.SBUS_FRAME_LEN - 2] & (1 << 2): self.failSafeStatus = self.SBUS_SIGNAL_LOST if self.sbusFrame[self.SBUS_FRAME_LEN - 2] & (1 << 3): self.failSafeStatus = self.SBUS_SIGNAL_FAILSAFE def get_sync(self): if self.sbus.any() > 0: if self.startByteFound: if self.frameIndex == (self.SBUS_FRAME_LEN - 1): self.sbus.readinto(self.sbusBuff, 1) # end of frame byte if self.sbusBuff[0] == 0: # TODO: Change to use constant var value self.startByteFound = False self.isSync = True self.frameIndex = 0 else: self.sbus.readinto(self.sbusBuff, 1) # keep reading 1 byte until the end of frame self.frameIndex += 1 else: self.frameIndex = 0 self.sbus.readinto(self.sbusBuff, 1) # read 1 byte if self.sbusBuff[0] == 15: # TODO: Change to use constant var value self.startByteFound = True self.frameIndex += 1 def get_new_data(self): """ This function must be called periodically according to the specific SBUS implementation in order to update the channels values. For FrSky the period is 300us. """ if self.isSync: if self.sbus.any() >= self.SBUS_FRAME_LEN: self.sbus.readinto(self.sbusFrame, self.SBUS_FRAME_LEN) # read the whole frame if (self.sbusFrame[0] == 15 and self.sbusFrame[ self.SBUS_FRAME_LEN - 1] == 0): # TODO: Change to use constant var value self.validSbusFrame += 1 self.outOfSyncCounter = 0 self.decode_frame() else: self.lostSbusFrame += 1 self.outOfSyncCounter += 1 if self.outOfSyncCounter > self.OUT_OF_SYNC_THD: self.isSync = False self.resyncEvent += 1 else: self.get_sync()
'dd_rtc':'0','wkd_rtc':'0','hr_rtc':'0','min_rtc':'0','footer':'###'} z = pickle.dumps(reset_dict).encode('utf8') bkram[0] = len(z) ba[4: 4+len(z)] = z restore_data() return pkl def gestione_power_on(): print("Power On") uart.write("Power On.") #imposto setting seriale - set MCU serial port1 uart = UART(1, 9600) uart.init(9600, bits=8, parity=None, stop=1) test=0 reason=upower.why() # motivo dell'uscita da low power mode. # see upower.py module documentation. uart.write(str(reason) +'\n') #reason='ALARM_B' # solo per debug try: if reason=='X1': verde.on() pyb.delay(3) verde.off()
course_error -= 360 elif course_error < -180: course_error += 360 # record the turn direction - mainly for debugging if course_error > 0: turn_direction = 1 # Turn right elif course_error < 0: turn_direction = -1 # Turn left else: turn_direction = 0 # Stay straight return course_error, turn_direction, current_heading, desired_heading my_gps = MicropyGPS() gps_uart = UART(6, 9600) xbee_uart = UART(2, 9600) # Parachute # utime.sleep(2) # parachute = Pin('X6', Pin.OUT_PP) # parachute.high() # utime.sleep(2) # parachute.low() # Buzzer # buzzer = Pin('Y12') # tim = Timer(8, freq=1000) # ch = tim.channel(3, Timer.PWM, pin=buzzer) # utime.sleep(2) # ch.pulse_width_percent(50) # utime.sleep(2)
class SmartOpen_LCD(): def __init__(self): self.serial = UART(3, 115200, timeout=0) # open serial port self.color_table = { "black": "0000", "blue": "001F", "red": "F800", "green": "07E0", "cyan": "07FF", "magenta": "F81F", "yellow": "FFE0", "white": "FFFF", } self.wait(1.5) self.set_baud() def wait(self, time=1): utime.sleep_ms(int(time * 1000)) def reset(self): self.write_command("7E0205EF") self.wait(6) def set_baud(self): baud_index = int_to_hex(4) self.write_command("7E0340{baud_index}EF".format(baud_index=baud_index)) def read_feedback_signal(self): bytes_string = "" start = 0 attempts = 6 while attempts: attempts -= 1 #print(attempts) if self.serial.any(): a_byte = self.serial.read(1) byte_string = bytes_to_hex(a_byte) #print(f"read: {byte_string}") if byte_string == "7E": start = 1 if start == 1: bytes_string += byte_string if byte_string == "EF": return bytes_to_hex else: self.wait(0.1) def wait_for_command_to_be_executed(self): if self.read_feedback_signal() == "7E036F6BEF": return True else: return False def write_command(self, hex_string): self.serial.write(hex_to_bytes(hex_string)) self.wait_for_command_to_be_executed() def set_blacklight(self, brightness): brightness_hex = int_to_hex(brightness) self.write_command("7E0306{brightness_hex}EF".format(brightness_hex=brightness_hex)) def fill_screen(self, color="white"): if color in self.color_table.keys(): color = self.color_table[color] self.write_command("7E0420{color}EF".format(color=color)) def draw_pixel(self, x, y, color="black"): if color in self.color_table.keys(): color = self.color_table[color] x = int_to_hex(x, 4) y = int_to_hex(y, 4) self.write_command("7E0821{x}{y}{color}EF".format(x=x, y=y, color=color)) def draw_line(self, x0, y0, x1, y1, color="black"): if color in self.color_table.keys(): color = self.color_table[color] x0 = int_to_hex(x0, 4) y0 = int_to_hex(y0, 4) x1 = int_to_hex(x1, 4) y1 = int_to_hex(y1, 4) self.write_command("7E0C24{x0}{y0}{x1}{y1}{color}EF".format(x0=x0, y0=y0, x1=x1, y1=y1, color=color)) def draw_rectangle(self, x, y, width, height, color="black"): if color in self.color_table.keys(): color = self.color_table[color] x = int_to_hex(x, 4) y = int_to_hex(y, 4) width = int_to_hex(width, 4) height = int_to_hex(height, 4) self.write_command("7E0C26{x}{y}{width}{height}{color}EF".format(x=x, y=y, width=width, height=height, color=color)) def write_string(self, x, y, text): # set cursor self.write_command("7E060100000000EF") # set Text color self.write_command("7E0402f800EF") # set text size self.write_command("7E030302EF") def chunkstring(string, length): return [string[0+i:length+i] for i in range(0, len(string), length)] for i in range(y*2): # new line self.write_command("7E0210EF") self.write_command("7E0210EF") text_list = chunkstring(text, 5) for _, text in enumerate(text_list): text = text_to_hex(text.ljust(5)) self.write_command("7E0711{text}EF".format(text=text))
def __init__(self): self.uart = UART(6, 115200)
import sensor, image, time from pyb import UART from pyb import USB_VCP def timeprint(num): if (0): print(str(num) + ":" + str(clock.avg())) clock.reset() clock.tick() usb = USB_VCP() uart = UART(3, 9600) uart.init(9600, bits=8, parity=None, stop=1) sensor.reset() sensor.set_pixformat(sensor.GRAYSCALE) sensor.set_framesize(sensor.QQVGA) sensor.set_auto_exposure(0, value=1) sensor.skip_frames(time=2000) bg = sensor.snapshot() bg = bg.copy() sensor.set_auto_exposure(0, value=100) clock = time.clock() x = 0 y = 0 xbottom = 0 ybottom = 13 xtop = 0 ytop = 13 scalex = 127 / (sensor.height() - xbottom - xtop)
sensor.set_contrast(1) sensor.set_gainceiling(16) # HQVGA and GRAYSCALE are the best for face tracking. sensor.set_framesize(sensor.HQVGA) sensor.set_pixformat(sensor.GRAYSCALE) # 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() # uart interface uart = UART(3, 9600) led = LED(1) img = sensor.snapshot() frame_width = img.width() frame_height = img.height() print(frame_width) print(frame_height) while (True): #clock.tick() # Capture snapshot img = sensor.snapshot()
sensor.set_pixformat(sensor.RGB565) sensor.set_framesize(sensor.QVGA) sensor.set_auto_whitebal(False) clock = time.clock() # 追踪帧率 blob_thresholds = ((85, 100, -12, 12, -12, 12)) #白色 thresholds = [(160, 255)] # grayscale thresholds设置阈值 find_once = 0 s_rect = [10, 10, 300, 220] buf_x = [0, 0, 0] buf_y = [0, 0, 0] frame_time = 0.01 uart = UART(3, 115200) while (True): clock.tick() #buf_x[0] = int((b[5] - 160) * 600 / 230) #[0] = int((b[6] - 120) * 600 /230) buf_x[0] = -150 buf_y[0] = -560 speed_now_x = (buf_x[0] - buf_x[1]) / frame_time speed_now_y = (buf_y[0] - buf_y[1]) / frame_time speed_last_x = (buf_x[1] - buf_x[2]) / frame_time speed_last_y = (buf_y[1] - buf_y[2]) / frame_time a_speed_x = (speed_now_x - speed_last_x) / frame_time a_speed_y = (speed_now_y - speed_last_y) / frame_time
# Color Line Following Example with PID Steering # # For this script to work properly you should point the camera at a line at a # 45 or so degree angle. Please make sure that only the line is within the # camera's field of view. import sensor, image, pyb, math, time from pyb import Servo from pyb import LED from pyb import UART uart = UART(3, 9600) # no need to go faster than this. Slower = solid comms # Color Tracking Thresholds (L Min, L Max, A Min, A Max, B Min, B Max) # The below thresholds track in general red/green things. You may wish to tune them... # old thresholds = [(30, 100, 15, 127, 15, 127), # generic_red_thresholds # (30, 100, -64, -8, -32, 32), # generic_green_thresholds # (0, 15, 0, 40, -80, -20)] # generic_blue_thresholds threshold_index = 3 # 0 for red, 1 for green, 2 for blue 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 (0, 100, -47, 127, 14, 127)] # generic yellow threshold # 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
# * Content: * # *---------------------------------------------------------------------------* # * Language: Python * # * Compiler: * # * Target: STM32F411 micropython 1.9.3 * # *===========================================================================* import pyb import sensorcore import filterToolkit import time import math from pyb import Pin, Timer, ExtInt, Switch, UART import threading uart = UART(2, 9600, timeout=1000) switch = Switch() lastPressTime = time.time() l3gd20 = sensorcore.L3GD20() l3gd20.initGyro() lsm303dlhc = sensorcore.LSM303DLHC() lsm303dlhc.initAcc() lsm303dlhc.initAccInt() # enable click interrupt lsm303dlhc.initMag() roll, pitch, heading = 0, 0, 0 rawXGyro, rawYGyro, rawZGyro = 0, 0, 0
from pyb import UART, LED, Pin, Switch 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 # #########################
if uart.any() > 0: time.sleep(500) inByte = uart.readline().decode('gbk') print(inByte) print('okay')''' value = './dfg.txt' high_z = 50 bx = 160 by = 120 cy = 0 cx = 0 # Set up the serial port uart = UART(3, 115200) #Set color threshold w_threshold = (63, 100, -128, 127, -128, 127) thresholds = [ (0, 100, 25, 127, -128, 127), #red (0, 100, -128, -18, 11, 127), #green (1, 100, -128, 127, -128, -20) ] #blue #(42, 67, -9, 15, 19, 127) # Set the pwm output of led tim = Timer(4, freq=1000) #Hertz frequency Led = tim.channel(3, Timer.PWM, pin=Pin("P9"), pulse_width_percent=10) lcd.init()
course_error -= 360 elif course_error < -180: course_error += 360 # record the turn direction - mainly for debugging if course_error > 0: turn_direction = 1 # Turn right elif course_error < 0: turn_direction = -1 # Turn left else: turn_direction = 0 # Stay straight return course_error, turn_direction, current_heading, desired_heading my_gps = MicropyGPS() gps_uart = UART(6, 9600, read_buf_len=1000) xbee_uart = UART(2, 9600) Razor_IMU = IMU.Razor(3, 57600) # Razor_IMU.set_angle_output() Razor_IMU.set_all_calibrated_output() # while True: # a,b,c = Razor_IMU.get_one_frame() # print(a,b,c) # Countdown Timer start = pyb.millis() backup_timer = 5400000 # Don't do anything until GPS is found while gps_uart.any() >= 0:
def B_forward(value): B1.high() B2.low() motorB.pulse_width_percent(value) def B_stop(): B1.low() B2.low() # use keypad U and D keys to control speed uart = UART(6) # Adafruit Bluefruit LE 3EDC uart.init(9600, bits=8, parity=None, stop=2) DEADZONE = 5 speed = 0 while True: while uart.any() != 10: pass command = uart.read(10) if command[2] == ord('5'): if speed < 96: speed += 5 print(speed)
gps = GPS(3) # orientation = Orientation(4, 1) servo1 = Servo(0, 1) motor_a = Motor(1, 'X2', 'X3') gps_indicator = pyb.LED(3) new_data = False def pps_callback(line): global new_data, gps_indicator new_data = True gps_indicator.toggle() uart = UART(6, 9600, read_buf_len=1000) pps_pin = pyb.Pin.board.X8 extint = pyb.ExtInt(pps_pin, pyb.ExtInt.IRQ_FALLING, pyb.Pin.PULL_UP, pps_callback) indicator = pyb.LED(4) increase = True sensor_queue = SensorQueue(tmp36, mcp9808, accel, gps ) command_pool = CommandPool(servo1, motor_a) communicator = Communicator(sensor_queue, command_pool)
import sensor, image, time, math, pyb, json from pyb import Servo from pyb import UART # 作者:谢焕杰 # 获取黑球坐标,输出串口(baudRate:115200) # 黑球色域 Block_threshold = (5, 45, -20, 35, -20, 20) sensor.reset() sensor.set_pixformat(sensor.RGB565) sensor.set_framesize(sensor.QQVGA) sensor.skip_frames(10) sensor.set_auto_whitebal(False) uart = UART(3, 115200) uart.init(115200, bits=8, parity=None, stop=1) while (True): img = sensor.snapshot().lens_corr(1.0, 1.0) blobs = img.find_blobs([Block_threshold]) if blobs: for b in blobs: if (b[5] > 5) and (b[5] < 125) and (b[6] > 3) and (b[6] < 115): if (b[2] < 15) and (b[3] < 15): img.draw_rectangle(b[0:4]) uart_buf = bytearray([ 0xef, 0x0d, int(b[5]) >> 8, int(b[5]), int(b[6]) >> 8, int(b[6]), 0xfe ])
def __init__(self, uart, baudrate = 115200): """ uart = uart #1-6, baudrate must match what is set on the ESP8266. """ self._uart = UART(uart, baudrate)
######################### #create BMP180 object bmp180 = BMP180('X') bmp180.oversample_sett = 3 #0=low accuracy, 3=high accuracy bmp180.baseline = 101325 #pressure at main sea level #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()
class BLE: BLE_NONE=0 BLE_SHIELD=1 def command(self, cmd): if self.type==self.BLE_SHIELD: self.uart.write(cmd) self.uart.write("\r\n") r=self.uart.read(9) if r[0]!=82: raise OSError("Response corrupted!") if r[1]==49: raise OSError("Command failed!") if r[1]==50: raise OSError("Parse error!") if r[1]==51: raise OSError("Unknown command!") if r[1]==52: raise OSError("Too few args!") if r[1]==53: raise OSError("Too many args!") if r[1]==54: raise OSError("Unknown variable or option!") if r[1]==55: raise OSError("Invalid argument!") if r[1]==56: raise OSError("Timeout!") if r[1]==57: raise OSError("Security mismatch!") if r[1]!=48: raise OSError("Response corrupted!") for i in range(2,6): if r[i]<48 or 57<r[i]: raise OSError("Response corrupted!") if r[7]!=13 or r[8]!=10: raise OSError("Response corrupted!") l=((r[2]-48)*10000)+\ ((r[3]-48)*1000)+\ ((r[4]-48)*100)+\ ((r[5]-48)*10)+\ ((r[6]-48)*1) if not l: return None if l==1 or l==2: raise OSError("Response corrupted!") response=self.uart.read(l-2) if self.uart.readchar()!=13: raise OSError("Response corrupted!") if self.uart.readchar()!=10: raise OSError("Response corrupted!") return response def deinit(self): if self.type==self.BLE_SHIELD: self.uart.deinit() self.rst=None self.uart=None self.type=self.BLE_NONE def init(self, type=BLE_SHIELD): self.deinit() if type==self.BLE_SHIELD: self.rst=Pin("P7",Pin.OUT_OD,Pin.PULL_NONE) self.uart=UART(3,115200,timeout_char=1000) self.type=self.BLE_SHIELD self.rst.low() sleep(100) self.rst.high() sleep(100) self.uart.write("set sy c m machine\r\nsave\r\nreboot\r\n") sleep(1000) self.uart.readall() # clear def uart(self): if self.type==self.BLE_SHIELD: return self.uart def type(self): if self.type==self.BLE_SHIELD: return self.BLE_SHIELD def __init__(self): self.rst=None self.uart=None self.type=self.BLE_NONE
str += "312\n" # 321 if bux < gux and gux < rux and bux < rux: str += "321" if bdx < gdx and gdx < rdx and bdx < rdx: str += "321\n" return str else: i += 1 time.sleep_ms(1000) if i > 5: print("*********") return "213+213" uart = UART(3, 19200) while (True): if uart.any(): a = uart.read().decode() if a == "start!": led1.on() time.sleep_ms(250) led2.on() time.sleep_ms(250) led2.off() led1.off() led1.on() time.sleep_ms(250) led2.on() time.sleep_ms(250) led2.off()
from pyb import UART uart = UART(6, 115200) # init with given baudrate cmdStr = "" for i in range(1000): uart.write("hello ") pyb.delay(100) if uart.any() > 0: for i in range(uart.any()): ch = uart.readchar() if ch == 0x0d: print("Command is:", cmdStr) cmdStr = "" continue if ch == 0x0a: continue cmdStr += chr(ch) print (chr(ch))
def sekuai(): rl = [] gl = [] bl = [] while (True): number = 0 rl.clear() gl.clear() bl.clear() img = sensor.snapshot() # 拍摄一张照片,img为一个image对象 for blob in img.find_blobs([red, green, blue], merge=False, pixels_threshold=130, area_threshold=265): img.draw_rectangle(blob.rect()) img.draw_cross(blob.cx(), blob.cy()) if blob.code() == 1: # 红 rl.append(blob.cy()) rl.append(blob.cx()) if blob.code() == 2: # 绿 gl.append(blob.cy()) gl.append(blob.cx()) if blob.code() == 4: # 蓝 bl.append(blob.cy()) bl.append(blob.cx()) if len(rl) == 4 and len(gl) == 4 and len(bl) == 4: if rl[0] < rl[2]: rux = rl[1] rdx = rl[3] else: rux = rl[3] rdx = rl[1] if gl[0] < gl[2]: gux = gl[1] gdx = gl[3] else: gux = rl[3] gdx = rl[1] if bl[0] < bl[2]: bux = bl[1] bdx = bl[3] else: bux = rl[3] bdx = rl[1] uart1 = UART(3, 19200) str = "" # 123 if rux < gux and gux < bux and rux < bux: str += "123" if rdx < gdx and gdx < bdx and rdx < bdx: str += "123\n" # 132 if rux < bux and bux < gux and rux < gux: str += "132" if rdx < bdx and bdx < gdx and rdx < gdx: str += "132\n" # 213 if gux < rux and rux < bux and gux < bux: str += "213" if gdx < rdx and rdx < bdx and gdx < bdx: str += "213\n" # 231 if gux < bux and bux < rux and gux < rux: str += "231" if gdx < bdx and bdx < rdx and gdx < rdx: str += "231\n" # 312 if bux < rux and rux < gux and bux < gux: str += "312" if bdx < rdx and rdx < gdx and bdx < gdx: str += "312\n" # 321 if bux < gux and gux < rux and bux < rux: str += "321" if bdx < gdx and gdx < rdx and bdx < rdx: str += "321\n" return str else: i += 1 time.sleep_ms(1000) if i > 5: print("*********") return "213+213"