python串口接收數據
Ⅰ 如何用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;
Ⅱ 串口發送16進制1234,用python接收的是'\x01\x01\x03\x04'但用python再怎麼轉換成原來的數據1234呢
1、首先要引用Python的第三方庫:serial,打開pycharm。

Ⅲ Python語言中uart.any()是什麼意思
應該是any(uart)吧?如果是的話,那麼uart應該是列表、元組、集合、字典中的一個,如果列表、元組、集合裡面有一個值不為0、空字元串、False,就返回True,比如說any([0, 0, False, ''])就會返回False,因為全部都是假;如果是any([1, 0, 0])就會返回True,因為有一個是真。字典的話就相當於把裡面的鍵提取出來,再來像上面一樣進行判斷。

Ⅳ python 和 PLC通訊走TCP通訊,接收數據問題
這種問題快捷的可能是直接傳輸位元組序列(查ascii碼表),
確定接收端正確後,再看python這邊如何編碼
Ⅳ 大佬們,python怎麼接收通過感測器傳出的電機電流、電壓、轉速等數據
讀串口數據就行了,用pyserial模塊
Ⅵ python串口讀取數據 讀不完就列印了
python串口讀取數據 讀不完就列印了
Ⅶ 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 串口傳輸問題
首先用USB線連上串口設備,然後確認是哪個COM口,下面用COM3為例。
import serial
t=serial.Serial('COM3',115200)
command = "aabbccddee"   //十六進制字元串
t.write(command.decode("hex"))  //轉換成十六進制發送,否則設備不認識
print t.read(16)
Ⅸ 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()裡面的埠號。
Ⅹ python如何獲取感測器數據
python需要運行在windows、mac、linux這樣的系統環境里,而這樣的環境要拿到感測器的數據有幾種方法。
可以通過zigbee轉發數據,python第三方庫中有pyserial這樣的庫通過配置串口數據、波特率等參數,能夠接收到感測器數據,對數據進行處理後,再進行分析。
