A. 如何調用python設計語言中有關串口模塊serial
一、概述 pyserial模塊封裝了對串口的訪問。 二、特性 在支持的平台上有統一的介面。 通過python屬性訪問串口設置。 支持不同的位元組大孝停止位、校驗位和流控設置。 可以有或者沒有接收超時。 類似文件的API,例如read和write,也支持readline等
B. python3.5 讀取串口中的數據怎麼解碼
1、安裝串口庫
2、採用默認通信參數
import serial
t = serial.Serial('com1',9600)
n = t.write('you are my world')print t.portstrprint n
str = t.read(n)print str
3、可以自己設置參數
import timeimport serialser = serial.Serial( #下面這些參數根據情況修改 port='COM1', baudrate=9600, parity=serial.PARITY_ODD, stopbits=serial.STOPBITS_TWO, bytesize=serial.SEVENBITS)data = ''while ser.inWaiting() > 0: data += ser.read(1)if data != '': print data
注意:Python與多個串口通信的時候,要確定埠號。如果有時間的話,可以自己寫一個查詢所有埠的信息,不想這么麻煩的話,下載個串口助手,自己看埠信息,在py文件中修改serial.Serial()裡面的埠號。
C. python如何判斷串口是否有數據
通常在安裝目錄下的lib或其子目錄,以windows的python2.7.x為例,一般是在python安裝目錄下的lib或者Lib\site-packages目錄下
D. python中Pyserial如何實現RS485串口通訊
RS485 的數據線要交叉才能通訊,如果你是兩台電腦通訊測試,另外一台要有返回才行。就好像你給人家說話,人家聽到了重復一遍你才能聽到。不然就是單向傳輸,收不到任何回應。
E. 怎麼編寫一個上位機讀取串口數據 python3
運行速度還算可以,就是界面編輯比較復雜。我也用wxpython做了一套上位機程序,每秒和下位機交換3個數據。
F. Python如何進行多串口通信一個串口控制電機 一個串口採集數據
下載 pyserial包
def OpenCom(self,*args): #設置埠和波特率 selComPort =『com2』 #波特率 selBaudRate =9600 #奇偶校驗 selParity = 'N' try: if(not self.mySerial): self.mySerial = serial.Serial(port=selComPort, baudrate=selBaudRate,bytesize=8,parity=selParity,stopbits=1,timeout=5) else: if(self.mySerial.isOpen()): self.mySerial.close() self.mySerial = serial.Serial(port=selComPort, baudrate=selBaudRate, bytesize=8, parity=selParity, stopbits=1, timeout=5) self.lblInfo['text'] = '打開成功!' except Exception as ex: self.lblInfo['text'] = '打開失敗!'
#使用com口發送modbus協議給終端設備。
def btnEmId_Click(self):
barray = bytearray([0x05, 0x03, 0xA#, 0x54, 0x00, 0x08])
vOldEmId = self.txbOldEmId.get()
vNewEmId = self.txbNewEmId.get()
barray[0] = int(vOldEmId)
barray[5] = int(vNewEmId)
#crc校驗
strInput = utils.crc16_append(barray)
print(barray)
n = self.mySerial.write(barray)
if(n > 0):
str = self.mySerial.readall()
self.lblInfo['text'] = 'success!'
# for s in str:
# print (hex(s))
else:
self.lblInfo['text'] = 'error!'
G. 如何用python寫個串口通信的程序
打開串口後啟動一個線程來監聽串口數據的進入,有數據時,就做數據的處理。
H. python串口讀取數據 讀不完就列印了
python串口讀取數據 讀不完就列印了
I. 如何用串口工具模擬器向python發送數據
串口模塊的波特率比較特別,找了幾個串口工具都不支持。。。所以,乾脆用python自己來寫了,其實已經好奇好久了,別人的工具各種不順手。
需要pyserial的支持,兼容各種平台,不需要新編譯二進制文件。
先貼一個定時發送的代碼:
import serial
import time
ser = serial.Serial('/dev/ttyUSB0', 250000, timeout=1)
print ser.isOpen()
words="gggggggggggggggg"
while (1):
print "send 256x\""+words+"\" to remotes"
startTime = time.time()
times = 256
while (times):
times -= 1
s = ser.write(words)
endTime = time.time()
print "use time: "+str(endTime-startTime)
print ""
time.sleep(5)
ser.close()
J. 如何用python寫個串口通信的程序
就是打開串口後,啟動一個線程來監聽串口數據的進入,有數據時,就做數據的處理(也可以發送一個事件,並攜帶接收到的數據)。
我沒有用到串口處理太深的東西。
客戶的原程序不能給你,不過我給你改一下吧。
裡面的一些東西,已經經過了處理,要運行,可能你要自己改一下,把沒有用的東西去掉。
我這里已經沒有串口設備了,不能調了,你自己處理一下吧,不過基本的東西已經有了。
=================================================================
#coding=gb18030
import sys,threading,time;
import serial;
import binascii,encodings;
import re;
import socket;
class ReadThread:
def __init__(self, Output=None, Port=0, Log=None, i_FirstMethod=True):
self.l_serial = None;
self.alive = False;
self.waitEnd = None;
self.bFirstMethod = i_FirstMethod;
self.sendport = '';
self.log = Log;
self.output = Output;
self.port = Port;
self.re_num = None;
def waiting(self):
if not self.waitEnd is None:
self.waitEnd.wait();
def SetStopEvent(self):
if not self.waitEnd is None:
self.waitEnd.set();
self.alive = False;
self.stop();
def start(self):
self.l_serial = serial.Serial();
self.l_serial.port = self.port;
self.l_serial.baudrate = 9600;
self.l_serial.timeout = 2;
self.re_num = re.compile('\d');
try:
if not self.output is None:
self.output.WriteText(u'打開通訊埠\r\n');
if not self.log is None:
self.log.info(u'打開通訊埠');
self.l_serial.open();
except Exception, ex:
if self.l_serial.isOpen():
self.l_serial.close();
self.l_serial = None;
if not self.output is None:
self.output.WriteText(u'出錯:\r\n %s\r\n' % ex);
if not self.log is None:
self.log.error(u'%s' % ex);
return False;
if self.l_serial.isOpen():
if not self.output is None:
self.output.WriteText(u'創建接收任務\r\n');
if not self.log is None:
self.log.info(u'創建接收任務');
self.waitEnd = threading.Event();
self.alive = True;
self.thread_read = None;
self.thread_read = threading.Thread(target=self.FirstReader);
self.thread_read.setDaemon(1);
self.thread_read.start();
return True;
else:
if not self.output is None:
self.output.WriteText(u'通訊埠未打開\r\n');
if not self.log is None:
self.log.info(u'通訊埠未打開');
return False;
def InitHead(self):
#串口的其它的一些處理
try:
time.sleep(3);
if not self.output is None:
self.output.WriteText(u'數據接收任務開始連接網路\r\n');
if not self.log is None:
self.log.info(u'數據接收任務開始連接網路');
self.l_serial.flushInput();
self.l_serial.write('\x11');
data1 = self.l_serial.read(1024);
except ValueError,ex:
if not self.output is None:
self.output.WriteText(u'出錯:\r\n %s\r\n' % ex);
if not self.log is None:
self.log.error(u'%s' % ex);
self.SetStopEvent();
return;
if not self.output is None:
self.output.WriteText(u'開始接收數據\r\n');
if not self.log is None:
self.log.info(u'開始接收數據');
self.output.WriteText(u'===================================\r\n');
def SendData(self, i_msg):
lmsg = '';
isOK = False;
if isinstance(i_msg, unicode):
lmsg = i_msg.encode('gb18030');
else:
lmsg = i_msg;
try:
#發送數據到相應的處理組件
pass
except Exception, ex:
pass;
return isOK;
def FirstReader(self):
data1 = '';
isQuanJiao = True;
isFirstMethod = True;
isEnd = True;
readCount = 0;
saveCount = 0;
RepPos = 0;
#read Head Infor content
self.InitHead();
while self.alive:
try:
data = '';
n = self.l_serial.inWaiting();
if n:
data = data + self.l_serial.read(n);
#print binascii.b2a_hex(data),
for l in xrange(len(data)):
if ord(data[l])==0x8E:
isQuanJiao = True;
continue;
if ord(data[l])==0x8F:
isQuanJiao = False;
continue;
if ord(data[l]) == 0x80 or ord(data[l]) == 0x00:
if len(data1)>10:
if not self.re_num.search(data1,1) is None:
saveCount = saveCount + 1;
if RepPos==0:
RepPos = self.output.GetInsertionPoint();
self.output.Remove(RepPos,self.output.GetLastPosition());
self.SendData(data1);
data1 = '';
continue;
except Exception, ex:
if not self.log is None:
self.log.error(u'%s' % ex);
self.waitEnd.set();
self.alive = False;
def stop(self):
self.alive = False;
self.thread_read.join();
if self.l_serial.isOpen():
self.l_serial.close();
if not self.output is None:
self.output.WriteText(u'關閉通迅埠:[%d] \r\n' % self.port);
if not self.log is None:
self.log.info(u'關閉通迅埠:[%d]' % self.port);
def printHex(self, s):
s1 = binascii.b2a_hex(s);
print s1;
#測試用部分
if __name__ == '__main__':
rt = ReadThread();
f = open("sendport.cfg", "r")
rt.sendport = f.read()
f.close()
try:
if rt.start():
rt.waiting();
rt.stop();
else:
pass;
except Exception,se:
print str(se);
if rt.alive:
rt.stop();
print 'End OK .';
del rt;