PYTHON SERIAL COMMUNICATION

发布时间:2025-01-27 01:03

学习Python基础语法:https://www.runoob.com/python/python-tutorial.html #生活技巧# #工作学习技巧# #编程学习资源#

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]) 1234567891011

[<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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869

[<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()

12345678910111213141516171819202122

[‘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')

1234567891011121314151617181920 ETC…

网址:PYTHON SERIAL COMMUNICATION https://www.yuejiaxmz.com/news/view/742045

相关内容

python serial模块的使用
Research and Prospects of Smart Home Communication Security
python
Python-Docx:Word与Python的完美结合
python panda
python中
python基础===Python 代码优化常见技巧
Python自动化任务
基于Python的个人健康管理系统的设计与实现
推荐项目:Python

随便看看