def main(): print("uart connection test") # Open /dev/ttyAMA1 with baudrate 115200 ser = Serial("/dev/ttyAMA1", 115200) print("Write to UART") ser.write(b"Hello from Atlas 200 DK\n") # Read up to 32 bytes, with timeout of 2 seconds readdata = ser.read(32, 2).decode('utf-8') print(f'Received reply: {readdata}')
def main(): parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('-m', '--model', required=True, help='File path of .tflite file.') parser.add_argument('-i', '--input', help='Image to be classified.') parser.add_argument('-l', '--labels', help='File path of labels file.') parser.add_argument('-k', '--top_k', type=int, default=1, help='Max number of classification results') parser.add_argument('-t', '--threshold', type=float, default=0.0, help='Classification score threshold') parser.add_argument('-c', '--count', type=int, default=5, help='Number of times to run inference') args = parser.parse_args() labels = read_label_file(args.labels) if args.labels else {} interpreter = make_interpreter(*args.model.split('@')) interpreter.allocate_tensors() _, height, width = interpreter.get_input_details()[0]['shape'] size = [height, width] trigger = GPIO("/dev/gpiochip2", 13, "out") # pin 37 # UART3, 9600 baud uart3 = Serial("/dev/ttymxc2", 115200) print('----INFERENCE TIME----') print('Note: The first inference on Edge TPU is slow because it includes', 'loading the model into Edge TPU memory.') #for i in range(1,351): while 1: #input_image_name = "./testSample/img_"+ str(i) + ".jpg" #input_image_name = "./testSample/img_1.jpg" #image = Image.open(input_image_name).resize(size, Image.ANTIALIAS) #arr = numpy.random.randint(0,255,(28,28), dtype='uint8') arr = uart3.read(784) #print(list(arr)) arr = numpy.array(list(arr), dtype='uint8') arr = numpy.reshape(arr, (28, 28)) image = Image.fromarray(arr, 'L').resize(size, Image.ANTIALIAS) common.set_input(interpreter, image) #inspector_start = int.from_bytes(uart3.read(1, 1), 'big') #print("read {:d} bytes: _{:s}_".format(len(inspector_start), inspector_start)) #print("Start Signal:", inspector_start) start = time.perf_counter() trigger.write(True) interpreter.invoke() trigger.write(False) inference_time = time.perf_counter() - start output_tensor = interpreter.get_tensor(1)[0] uart3.write(output_tensor.tobytes()) print('%.6fms' % (inference_time * 1000)) classes = classify.get_classes(interpreter, args.top_k, args.threshold) #print('RESULTS for image ', 1) for c in classes: print('%s: %.6f' % (labels.get(c.id, c.id), c.score))
from periphery import Serial productUID = "com.[your-company].[your-product]" serial = Serial('/dev/ttyS0', 9600) serial.write(b'\n') req = {"req": "hub.set"} req["product"] = productUID req["mode"] = "continuous" serial.write(bytearray(json.dumps(req), 'utf8')) serial.write(b'\n') print(json.dumps(req)) data = serial.read(32, 0.5) if data is not None: data_string = ''.join([chr(b) for b in data]) print(data_string, end="") print("Notecard configured...") else: print('Notecard not connected...') i2c = busio.I2C(board.SCL, board.SDA) sensor = adafruit_bme680.Adafruit_BME680_I2C(i2c) while True: temp = sensor.temperature humidity = sensor.humidity print('Temperature: {} degrees C'.format(temp)) print('Humidity: {}%'.format(humidity))
class PMS5003(object): def __init__(self, port, enable_pin=None, reset_pin=None): self.port = Serial(port, 9600) self.gpio_enable = None self.gpio_reset = None self.stop = Event() # suspend sensor by default if enable_pin: self.gpio_enable = GPIO(enable_pin, "low") if reset_pin: self.gpio_reset = GPIO(reset_pin, "high") def reset(self): if self.gpio_reset is None: return self.gpio_reset.write(False) self.enable() time.sleep(.1) self.gpio_reset.write(True) def enable(self): if not self.gpio_enable: return log.info("Enable sensor (via gpio %s)", self.gpio_enable.line) self.gpio_enable.write(True) def disable(self): if not self.gpio_enable: return log.info("Disable sensor (via gpio %s)", self.gpio_enable.line) self.gpio_enable.write(False) def discard_input(self): while self.port.input_waiting(): self.port.read(4096, 0) def warmup(self, seconds): log.info("Warming up for %s seconds", seconds) self.stop.wait(seconds) self.discard_input() @staticmethod def packet_from_data(data): numbers = struct.unpack('>16H', data) csum = sum(data[:-2]) if csum != numbers[-1]: log.warn("Bad packet data: %s / %s", data, csum) return return Packet(*numbers[2:-2]) def receive_one(self): while not self.stop.is_set(): c = self.port.read(1) if not c or c != '\x42': continue c = self.port.read(1, .1) if not c or c != '\x4d': continue data = bytearray(( 0x42, 0x4d, )) data += self.port.read(30, .1) if len(data) != 32: continue p = self.packet_from_data(data) if p: return p
""" periphery uart 测试 """ from periphery import Serial try: # 申请串口资源/dev/ttymxc2,设置串口波特率为115200,数据位为8,无校验位,停止位为1,不使用流控制 serial = Serial( "/dev/ttymxc2", baudrate=115200, databits=8, parity="none", stopbits=1, xonxoff=False, rtscts=False, ) # 使用申请的串口发送字节流数据 "Hello World!\n" serial.write(b"Hello World!\n") # 读取串口接收的数据,该函数返回条件二者满足其一,一、读取到128个字节,二、读取时间超过1秒 buf = serial.read(128, 1) # 注:Python读取出来的数据类型为:bytes # 打印原始数据 print("原始数据:\n", buf) # 转码为gbk字符串,可以显示中文 data_strings = buf.decode("gbk") # 打印读取的数据量及数据内容 print("读取到 {:d} 个字节 , 以字符串形式打印:\n {:s}".format(len(buf), data_strings)) finally: # 释放申请的串口资源 serial.close()
from periphery import Serial # Open /dev/ttyACM0 with baudrate 9600, and defaults of 8N1, no flow control serial = Serial("/dev/ttyACM0", 9600) # Read up to 128 bytes with 500ms timeout while (true): try: buf = serial.read(128, 0.5) ary = buf.decode().split(',') # status, hum, temp print("status: {d[0]}, humidity: {d[1]}, temperature: {d[2]}".format( d=ary)) except KeyboardInterrupt: serial.close() break