導航:首頁 > 編程語言 > python串口發送負數

python串口發送負數

發布時間:2024-09-16 10:14:10

㈠ 濡備綍鐢╬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:
print
exceptOSError:
print

以前回答過一個,好像跟你說的意思差不多,都是讀取注冊表,一個讀USB,一個是串口

㈥ 如何用python寫個串口通信的程序

打開串口後啟動一個線程來監聽串口數據的進入,有數據時,就做數據的處理。

㈦ 調用python模塊串口的write寫的數據與串口實際寫的數

1、寫入的數據長度不一致。在使用Python的`serial`模塊進行串口通信時,使用`write`函數寫入數據時需要指定寫入數據的長度,如果指定的長度與實際寫入的數據長度不一致,就會導致寫入的數據與實際寫入的數據不同。
2、串口參數設置不正確。在使用Python的`serial`模塊進行串口通信時,需要設置串口的通信參數,如波特率、數據位、校驗位、停止位等。如果設置不正確,就會導致寫入的數據與實際寫入的數據不同。
3、串口通信過程中出現錯誤。在串口通信過程中,可能會出現一些錯誤,如數據丟失、數據重復等問題,這也會導致寫入的數據與實際寫入的數據不同。

閱讀全文

與python串口發送負數相關的資料

熱點內容
手機proxy伺服器地址 瀏覽:449
吉他清音壓縮 瀏覽:301
簡歷模板程序員 瀏覽:881
螺桿壓縮機虛標型號 瀏覽:953
idea開發項目伺服器ip地址 瀏覽:125
串口伺服器出現亂碼怎麼解決 瀏覽:950
命令按鈕的default 瀏覽:161
戰網如何登錄其他伺服器 瀏覽:990
中國銀行app如何關閉簡訊 瀏覽:493
nx120編程技巧 瀏覽:722
手機也能使用源碼公式 瀏覽:918
怎樣把壓縮的文件下載 瀏覽:334
pdf是哪的 瀏覽:27
群暉伺服器如何建立自己資料庫 瀏覽:868
win10怎麼查找伺服器地址 瀏覽:506
freepdfsplit 瀏覽:172
如何更改linux伺服器地址 瀏覽:221
編程求字元串abcdefh長度 瀏覽:312
座機時間伺服器地址 瀏覽:419
華康寶app是怎麼樣的 瀏覽:73