㈠ 濡备綍鐢╬ython鍐欎釜涓插彛阃氢俊镄勭▼搴
鎴戠敤镄勬槸钬灭嚎绋嬭疆瀵烩濇柟寮忋
灏辨槸镓揿紑涓插彛钖庯纴钖锷ㄤ竴涓绾跨▼𨱒ョ洃钖涓插彛鏁版嵁镄勮繘鍏ワ纴链夋暟鎹镞讹纴灏卞仛鏁版嵁镄勫勭悊锛堜篃鍙浠ュ彂阃佷竴涓浜嬩欢锛屽苟鎼哄甫鎺ユ敹鍒扮殑鏁版嵁锛夈
鎴戞病链夌敤鍒颁覆鍙e勭悊澶娣辩殑涓滆タ銆
瀹㈡埛镄勫师绋嫔簭涓嶈兘缁欎綘锛屼笉杩囨垜缁欎綘鏀逛竴涓嫔惂銆
閲岄溃镄勪竴浜涗笢瑗匡纴宸茬粡缁忚繃浜嗗勭悊锛岃佽繍琛岋纴鍙鑳戒綘瑕佽嚜宸辨敼涓涓嬶纴鎶婃病链夌敤镄勪笢瑗垮幓鎺夈
鎴戣繖閲屽凡缁忔病链変覆鍙h惧囦简锛屼笉鑳借皟浜嗭纴浣犺嚜宸卞勭悊涓涓嫔惂锛屼笉杩囧熀链镄勪笢瑗垮凡缁忔湁浜嗐
=================================================================
#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'阃氲绔鍙f湭镓揿紑\r\n');
if not self.log is None:
self.log.info(u'阃氲绔鍙f湭镓揿紑');
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'鍏抽棴阃氲繀绔鍙o细[%d] \r\n' % self.port);
if not self.log is None:
self.log.info(u'鍏抽棴阃氲繀绔鍙o细[%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;
㈡ python Serial 串口能不能发送16进制的数字
pyserial默认的写入格式是字符串,并不是16进制的。接收到的也是字符串,除非你在接收端设置了默认接受hex格式,就会显示hex。我用过蓝牙串口和Arino开发板的串口,收到的都是字符串。
㈢ python 如何防止串口通信失败
Python中串口出现异常通常有:1.打开串口时,串口不存在,2.写串口时,3.读串口时。这几个异常是经常会碰到的(有经验的人就深有体会),一旦异常出现了,整个程序很可能会因此就运行不下去了。避免因为这些异常的出现而导致程序死机的方法是对这些可能存在的异常进行捕捉。举一个例子:
try:
ComDev.read(1)
print "read Com ok!"
except:
print "read Com error!"
上面的代码意思是:对ComDev这个串口对象读取一个字节,如果读成功,就接着执行print "read Com ok!"而不执行except以下的语句,如果读出现异常,就执行print "read Com error"而不执行
print "read Com ok!"
当然系统还会抛出异常信息,只是我这里没有进行接收,个人觉得很多异常不必接收其信息。
㈣ 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!'
㈤ python获取串口设备的描述
importwinreg
key=winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,r"{36FC9E60-C465-11CF-8056-444553540000}")
foriinrange(winreg.QueryInfoKey(key)[0]):
subkey=winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,"SYSTEM\ControlSet001\Control\Class\{36FC9E60-C465-11CF-8056-444553540000}\"+winreg.EnumKey(key,i))
print(winreg.QueryValueEx(subkey,'DriverDesc'))
winreg.CloseKey(subkey)
winreg.CloseKey(key)
importwinreg
key=winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,r"")
try:
i=0
while1:
name,value,type=winreg.EnumValue(key,i)
print(repr(name),value)
i+=1
value,type=winreg.QueryValueEx(key,"EnableAutoTray")
exceptFileNotFoundError:
exceptOSError:
以前回答过一个,好像跟你说的意思差不多,都是读取注册表,一个读USB,一个是串口
㈥ 如何用python写个串口通信的程序
打开串口后启动一个线程来监听串口数据的进入,有数据时,就做数据的处理。
㈦ 调用python模块串口的write写的数据与串口实际写的数
1、写入的数据长度不一致。在使用Python的`serial`模块进行串口通信时,使用`write`函数写入数据时需要指定写入数据的长度,如果指定的长度与实际写入的数据长度不一致,就会导致写入的数据与实际写入的数据不同。
2、串口参数设置不正确。在使用Python的`serial`模块进行串口通信时,需要设置串口的通信参数,如波特率、数据位、校验位、停止位等。如果设置不正确,就会导致写入的数据与实际写入的数据不同。
3、串口通信过程中出现错误。在串口通信过程中,可能会出现一些错误,如数据丢失、数据重复等问题,这也会导致写入的数据与实际写入的数据不同。