PYTHON SERIAL COMMUNICATION

List available serial port

import serial #导入模块

port_list = list(serial.tools.list_ports.comports())
print(port_list)
if len(port_list) == 0:
    print('无可用串口')
else:
    for i in range(0,len(port_list)):
        #help(port_list[i])
        #print(port_list[i].__dict__)
        print(port_list[i])

[<serial.tools.list_ports_linux.SysFS object at 0x72a67b30>]
/dev/ttyAMA0 - ttyAMA0

LIST ports and read encoder through readline()

import serial #导入模块
import threading
import time  
import serial.tools.list_ports

def get_time_stamp():
    ct = time.time()
    local_time = time.localtime(ct)
    data_head = time.strftime("%Y-%m-%d %H:%M:%S", local_time)
    data_secs = (ct - int(ct)) * 1000
    time_stamp = "%s.%03d" % (data_head, data_secs)
    return time_stamp

def doRead(ser,term):
    matcher = re.compile(term)    #gives you the ability to search for anything
    tic     = time.time()
    buff    = ser.read(128)
    tout    = 0.1
    # you can use if not ('\n' in buff) too if you don't like re
    while ((time.time() - tic) < tout) and (not matcher.search(buff)):
       buff += ser.read(128)

    return buff

port_list = list(serial.tools.list_ports.comports())
print(port_list)
if len(port_list) == 0:
    print('无可用串口')
else:
    for i in range(0,len(port_list)):
        #help(port_list[i])
        #print(port_list[i].__dict__)
        print(port_list[i])
        
            
for i in port_list:
    print('START TO TEST ',i.device)
    #set buad ==115200, timeout = 0.1
    encoder_serial = serial.Serial(i.device,115200, timeout=0.1)
    if encoder_serial.isOpen():
        print(i.device,' is open')
    else:
        encoder_serial.open()
    
    encoder_serial.write(b'II\n')
    try:
        #result = encoder_serial.readline(timeout = 0.1)
        result = doRead(encoder_serial,'\n')
        
    except:
        print(i.device,' has no response!')
        encoder_serial.close()
    
    if result == b'ENCODER\n':
        print(i.name, ' is connected to ENCODER!')
        
        while True:
            encoder_serial.write(b'RD\n')
            number_bytes = encoder_serial.readline()
            number = int(number_bytes)
            print(get_time_stamp(),number)
            #print()
        encoder_serial.close()
        #return i.name
    else:
        print(i.name, ' is not connected to ENCODER!')
        encoder_serial.close()
        #return None
    

[<serial.tools.list_ports_linux.SysFS object at 0x72a6a070>]
/dev/ttyAMA0 - ttyAMA0
START TO TEST /dev/ttyAMA0
/dev/ttyAMA0 is open

KeyboardInterrupt Traceback (most recent call last)
in ()
43 encoder_serial.open()
44
—> 45 encoder_serial.write(b’II\n’)
46 try:
47 #result = encoder_serial.readline(timeout = 0.1)

~/berryconda3/lib/python3.6/site-packages/serial/serialposix.py in write(self, data)
554 assert timeout.time_left() is None
555 # wait for write operation
–> 556 abort, ready, _ = select.select([self.pipe_abort_write_r], [self.fd], [], None)
557 if abort:
558 os.read(self.pipe_abort_write_r, 1)

KeyboardInterrupt:

get time_stamp() with milisecond

import time
print(dir(time))
print(time.asctime())
print(time.time())
print(time.gmtime())

 
 
def get_time_stamp():
    ct = time.time()
    local_time = time.localtime(ct)
    data_head = time.strftime("%Y-%m-%d %H:%M:%S", local_time)
    data_secs = (ct - int(ct)) * 1000
    time_stamp = "%s.%03d" % (data_head, data_secs)
    print(time_stamp)
    #stamp = ("".join(time_stamp.split()[0].split("-"))+"".join(time_stamp.split()[1].split(":"))).replace('.', '')
    #print(stamp)
 
 
if __name__ == '__main__':
    get_time_stamp()

[‘CLOCK_MONOTONIC’, ‘CLOCK_MONOTONIC_RAW’, ‘CLOCK_PROCESS_CPUTIME_ID’, ‘CLOCK_REALTIME’, ‘CLOCK_THREAD_CPUTIME_ID’, ‘_STRUCT_TM_ITEMS’, ‘doc’, ‘loader’, ‘name’, ‘package’, ‘spec’, ‘altzone’, ‘asctime’, ‘clock’, ‘clock_getres’, ‘clock_gettime’, ‘clock_settime’, ‘ctime’, ‘daylight’, ‘get_clock_info’, ‘gmtime’, ‘localtime’, ‘mktime’, ‘monotonic’, ‘perf_counter’, ‘process_time’, ‘sleep’, ‘strftime’, ‘strptime’, ‘struct_time’, ‘time’, ‘timezone’, ‘tzname’, ‘tzset’]
Thu Aug 8 02:58:35 2019
1565229515.915138
time.struct_time(tm_year=2019, tm_mon=8, tm_mday=8, tm_hour=1, tm_min=58, tm_sec=35, tm_wday=3, tm_yday=220, tm_isdst=0)
2019-08-08 02:58:35.917

Is there a nice way to check if readline() has timed-out other than checking the state of z

I’m using pyserial to communicate with a embedded devise.
ser = serial.Serial(PORT, BAUD, timeout = TOUT)
ser.write(CMD)
z = ser.readline(eol=’\n’)
So we send CMD to the device and it replies with an string of varing length ending in a ‘\n’

(1) if the devise cant replay then readline() times-out and z=’’

(2) if the devise is interrupted or crashes will it’s sending the data then readline() times-out and z will be a string without a ‘\n’ at the end.

Is there a nice way to check if readline() has timed-out other than checking the state of z.
answer1:

# Python PySerial read-line timeout method

import re
import time
import serial

def doRead(ser,term):
    matcher = re.compile(term)    #gives you the ability to search for anything
    tic     = time.time()
    buff    = ser.read(128)
    # you can use if not ('\n' in buff) too if you don't like re
    while ((time.time() - tic) < tout) and (not matcher.search(buff)):
       buff += ser.read(128)

    return buff

if __name__ == "__main__":
    ser = serial.Serial(PORT, BAUD, timeout = TOUT)
    ser.write(CMD)
    print doRead(ser,term='\n')

ETC…

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值