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 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(): """Connect to Notcard and run a transaction test.""" print("Opening port...") try: if sys.platform == "linux" or sys.platform == "linux2": if use_periphery: port = Serial("/dev/serial0", 9600) else: port = serial.Serial(port="/dev/serial0", baudrate=9600) elif sys.platform == "darwin": port = serial.Serial(port="/dev/tty.usbmodemNOTE1", baudrate=9600) elif sys.platform == "win32": port = serial.Serial(port="COM21", baudrate=9600) except Exception as exception: raise Exception("error opening port: " + NotecardExceptionInfo(exception)) print("Opening Notecard...") try: card = notecard.OpenSerial(port) except Exception as exception: raise Exception("error opening notecard: " + NotecardExceptionInfo(exception)) # If success, do a transaction loop print("Performing Transactions...") while True: time.sleep(2) transactionTest(card)
def init(interfaceType='UART', number=0, baud=115200): global serial if (interfaceDict.get(interfaceType) != None): serial = Serial(interfaceDict[interfaceType] + str(number), baud) else: print('Interface type not exist, please concat us.')
def main(): # Initialize print("opening port") try: if sys.implementation.name == 'circuitpython': if use_uart: # https://circuitpython.readthedocs.io/en/2.x/shared-bindings/busio/UART.html port = busio.UART(board.TX, board.RX, baudrate=9600) else: # https://circuitpython.readthedocs.io/en/2.x/shared-bindings/busio/I2C.html port = busio.I2C(board.SCL, board.SDA) elif sys.implementation.name == 'micropython': if use_uart: # https://docs.micropython.org/en/latest/library/machine.UART.html # ESP32 IO2 RX:16 TX:17 port = UART(2, 9600) port.init(9600, bits=8, parity=None, stop=1) else: # https://docs.micropython.org/en/latest/library/machine.I2C.html port = I2C() elif sys.implementation.name == 'cpython': if use_uart: # https://github.com/vsergeev/python-periphery#serial if sys.platform == "linux" or sys.platform == "linux2": if use_periphery: port = Serial("/dev/serial0", 9600) else: port = serial.Serial(port="/dev/serial0", baudrate=9600) elif sys.platform == "darwin": port = serial.Serial(port="/dev/tty.usbmodemNOTE1", baudrate=9600) elif sys.platform == "win32": port = serial.Serial(port="COM21", baudrate=9600) else: # https://github.com/vsergeev/python-periphery#i2c if use_periphery: port = I2C("/dev/i2c-1") else: raise Exception("I2C not supported on platform: " + sys.platform) except Exception as exception: raise Exception("error opening port: " + ExceptionInfo(exception)) print("opening notecard") try: if use_uart: card = notecard.OpenSerial(port) else: card = notecard.OpenI2C(port, 0, 0) except Exception as exception: raise Exception("error opening notecard: " + ExceptionInfo(exception)) # If success, do a transaction loop print("transaction loop") while True: time.sleep(2) transactionTest(card)
def init(interfaceType='UART'): global serial if (interfaceDict.get(interfaceType) != None): serial = Serial(interfaceDict[interfaceType], 115200) else: print('Interface type not exist, please concat us.')
def post_to_notehub(): """Post all sensor data to Notehub.io""" while True: time.sleep(NOTECARD_TIME_BETWEEN_POSTS) notecard_port = Serial("/dev/ttyACM0", 9600) try: card = notecard.OpenSerial(notecard_port) except Exception as exception: raise Exception("Error opening notecard: {}".format(exception)) # Setup data sensor_data = collect_all_data() for sensor_data_key in sensor_data: data_unit = None if 'temperature' in sensor_data_key: data_unit = '°C' elif 'humidity' in sensor_data_key: data_unit = '%RH' elif 'pressure' in sensor_data_key: data_unit = 'hPa' elif 'oxidising' in sensor_data_key or 'reducing' in sensor_data_key or 'nh3' in sensor_data_key: data_unit = 'kOhms' elif 'proximity' in sensor_data_key: pass elif 'lux' in sensor_data_key: data_unit = 'Lux' elif 'pm' in sensor_data_key: data_unit = 'ug/m3' elif 'battery_voltage' in sensor_data_key: data_unit = 'V' elif 'battery_percentage' in sensor_data_key: data_unit = '%' request = { 'req': 'note.add', 'body': { sensor_data_key: sensor_data[sensor_data_key], 'units': data_unit } } try: response = card.Transaction(request) if DEBUG: logging.info('Notecard response: {}'.format(response)) except Exception as exception: logging.warning( 'Notecard data setup error: {}'.format(exception)) # Sync data with Notehub request = {'req': 'service.sync'} try: response = card.Transaction(request) if DEBUG: logging.info('Notecard response: {}'.format(response)) except Exception as exception: logging.warning('Notecard sync error: {}'.format(exception))
def __init__(self, path): self.device = None self.__t_read = None self.__t_deal = None self.data = [] self.acc_x = 0.0 self.acc_y = 0.0 self.acc_z = 0.0 self.gyr_x = 0.0 self.gyr_y = 0.0 self.gyr_z = 0.0 self.angle_x = 0.0 self.angle_y = 0.0 self.angle_z = 0.0 sequence = base_serial.get_usb_serial_sequence_by_path(path) if sequence != None: tty_name = "/dev/ttyUSB" + str(sequence) self.device = Serial(tty_name, BAUD_RATE) self.start() else: self.device = None
send_expect(sio, f'ROLE MASTER {config.mesh_send_ttl};', f'ACK {config.mesh_send_ttl};') send_rtc() send_expect(sio, 'INIT;', 'ACKINIT;') # m/dimmer/led1/value -> nodename/dimmer/led1/value def translate_topic(src_node, from_mesh_topic): _, raw_topic = from_mesh_topic.split("/", 1) mqtt_topic = src_node + '/' + raw_topic return mqtt_topic mesh_initialized = False with Serial(config.serial_port, config.serial_speed) as sio: #sio = io.TextIOWrapper(io.BufferedRWPair(ser, ser), errors='replace', encoding='ascii') rebooted = False while rebooted == False: rebooted = send_expect(sio, "REBOOT;", "READY;") init_mesh() mesh_initialized = True ts_ms = int(time.time() * 1000) # connect to mqtt broker client = mqtt.Client() client.on_connect = on_connect client.on_message = on_message client.connect(config.mqtt_host, config.mqtt_port, 60) # start mqtt async loop client.loop_start() # async loop
def init(): global serial serial = Serial('/dev/ttyTHS1', 115200)
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))
import board import busio import time import adafruit_bme680 import json 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)
#!/home/mendel/.virtualenvs/cv/bin/python from periphery import Serial import time uart3 = Serial("/dev/ttymxc2", 9600) def output_uart(): uart3.write(b'popo'); time.sleep(5) uart3.write(b'popo');
import board import busio import time import adafruit_bme680 import json import notecard from periphery import Serial productUID = "com.[your-company].[your-product]" serial = Serial('/dev/ttyS0', 9600) serial.write(b'\n') card = notecard.OpenSerial(serial) req = {"req": "hub.set"} req["product"] = productUID req["mode"] = "continuous" print(json.dumps(req)) rsp = card.Transaction(req) print(rsp) 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))
#!/home/mendel/.virtualenvs/cv/bin/python import cv2 as cv import time from periphery import Serial serial = Serial("/dev/ttymxc2", 9600) #i2c2 = I2C("/dev/i2c-1") #pwm = PWM(0, 0) while(1): time.sleep(5) serial.write(b"2!") print ("2")
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
import sys import argparse import time from periphery import Serial import notecard port = Serial("/dev/serial0", 9600) card = notecard.OpenSerial(port) if card.uart is not None: print("Notecard connected...") def send_request(req): try: rsp = card.Transaction(req) return rsp except Exception as exception: print("transaction error: " + ExceptionInfo(exception)) def ExceptionInfo(exception): s1 = '{}'.format(sys.exc_info()[-1].tb_lineno) s2 = exception.__class__.__name__ return "line " + s1 + ": " + s2 + ": " + ' '.join(map(str, exception.args)) def main(): print("Configuring card...")
SUCH DAMAGES. 3. NXP reserves the right to make changes to the NXP Software/Sourcecode any time, also without informing customer. 4. Licensee agrees to indemnify and hold harmless NXP and its affiliated companies from and against any claims, suits, losses, damages, liabilities, costs and expenses (including reasonable attorney's fees) resulting from Licensee's and/or Licensee customer's/licensee's use of the NXP Software/Source Code. ''' from periphery import Serial from periphery import time #connect to serial port ttyUSB1 of Sigfox module connected to coral micro usb port with baudrate 115200 sigfox_serial_port = Serial("/dev/ttyACM0", 115200) #send wakeup sigfox_serial_port.write(b"1\n\r") time.sleep(0.2) #switch to RCZ1 for Europe sigfox_serial_port.write(b"15\n\r") time.sleep(0.2) #transmit payload sigfox_serial_port.write(b"4\n\r") time.sleep(0.2) #transmit payload sigfox_serial_port.write(b"h3p1t182803\n\r")
#!/home/mendel/.virtualenvs/cv/bin/python import time import math import cv2 as cv from periphery import Serial #from matplotlib import pyplot as plt import numpy as np uart3 = Serial("/dev/ttymxc2", 9600) start = time.time() raw_image = cv.imread('data/road2_240x320.png') hsv_image = cv.cvtColor(raw_image, cv.COLOR_BGR2HSV) #plt.imshow(hsv_image) lower_blue = np.array([60, 40, 40]) upper_blue = np.array([150, 255, 255]) mask = cv.inRange(hsv_image, lower_blue, upper_blue) #plt.imshow(mask) edges = cv.Canny(mask, 200, 400) #plt.imshow(edges) def region_of_interest(edges): height, width = edges.shape mask = np.zeros_like(edges) # only focus bottom half of the screen polygon = np.array([[ (0, height * 1 / 2), (width, height * 1 / 2),
""" 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()
threshold1 = 80 threshold2 = 80 threshold3 = 70 # default ROI defaultRoiPoints = np.array( [[maxWidth / 2 - maxWidth * 3 / 8, maxHeight], [maxWidth / 2 + maxWidth * 3 / 8, maxHeight], [maxWidth / 2 + maxWidth / 8, maxHeight / 2 - maxHeight / 7], [maxWidth / 2 - maxWidth / 8, maxHeight / 2 - maxHeight / 7]], np.int32) # In[ ]: # Serial currentTime = time.time() serial = Serial('/dev/ttyTHS1', 115200) commandJson = {'o': 1, 'v': 0, 'c': 0, 'd': 0, 'r': 0, 'a': 0} # In[ ]: cap = cv.VideoCapture(0) cap.set(3, maxWidth) cap.set(4, maxHeight) # In[ ]: def controlTricar(command): global currentTime global commandJson
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
def buildSerial(self): pinVCC = GPIO(self.vccPin, "high") pinMOD_EN = GPIO(self.modPin, "high") pinA_MODE = GPIO(self.aModePin, "low") serial = Serial(self.ttyPort, baudrate=115200) return serial
# Set-up a Serial Connection between the Argon and Coral Dev Board from periphery import Serial from time import sleep import signal import sys import websocket import socket, threading # UART 1 on the Coral serial = Serial("/dev/ttymxc2", 115200) sock_ip = "192.168.1.235:4665" # Update with IP # import protobuf sys.path.insert(0, '/home/mendel/emotion-mesh/local-detector/streaming') import proto.messages_pb2 as messages_pb2 def start_serial(ws): print('Waiting for a message from the Argon...') # wait for something from the Argon to trigger the demo while True: if (serial.poll(timeout=1)): buf = serial.read(128, 0.5) serial_message = str(buf, 'utf-8').strip() print("read %d bytes: %s" % (len(buf), serial_message)) if (serial_message == 'capture'): capture_image(serial, ws) elif (serial_message == 'reset'): send_reset(ws)