python实现串口通信 要导入serial的包 而且刚开始在等待接受收到0x45退出
2014-11-23 10:27
519 查看
import sys,threading,time; import serial; import binascii,encodings; import re; import socket; from struct import *; class ComThread: def __init__(self, Port=1): self.l_serial = None; self.alive = False; self.waitEnd = None; self.port = Port; 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.l_serial.open(); if self.l_serial.isOpen(): 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: return False; def FirstReader(self): print "waiting data" while self.alive: time.sleep(0.01); try: data = ''; n = self.l_serial.inWaiting(); if n: data = data + self.l_serial.read(n); #for l in xrange(len(data)): # print '%02X' % ord(data[l]), #snddata = ''; #snddata += chr(97) #tt = 0x12345678; #snddata += pack('i', tt) #snddata += chr(0x64) #print snddata; #self.l_serial.write(snddata); snddata= pack('i', 0x12345600) snddata+= pack('B', 0x11) self.l_serial.write(snddata); if len(data) > 0 and ord(data[len(data)-1])==0x0a: #pass; break; except Exception, ex: print str(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 __name__ == '__main__': rt = ComThread(); try: if rt.start(): rt.waiting(); rt.stop(); else: pass; except Exception,se: print str(se); if rt.alive: rt.stop(); print ''; print 'End OK .'; del rt;
相关文章推荐
- python 实现:题目:有n个人围成一圈,顺序排号。从第一个人开始报数(从1到3报数),凡报到3的人退出圈子,问最后留下的是原来第几号的那位。
- 做机械臂导航时遇到的问题5:如何使用ROS内嵌serial功能包实现串口通信
- matlab 实现串口通信 SERIAL
- 串口数据通信程序实现(SerialPort类方法)
- python3中利用serial模块实现单片机与python上位机的通信(串口调试助手)
- 单片机C51串口中断接收和发送测试例程(含通信协议的实现)
- 串行通信的基本原理及用MFC实现串口通信编程
- VC++实现串口通信下GP接收机定位数据的提取
- VC实现串口通信例程 作者:阮帮秋
- Microsoft Visual C++ 6.0实现串口的通信
- 单片机C51串口中断接收和发送测试例程(含通信协议的实现)
- VC中用API实现串口通信
- 基于Vxworks实时操作系统的串口通信程序设计与实现
- VC实现串口通信例程
- 单片机C51串口中断接收和发送测试例程(含通信协议的实现)——龚建伟
- 在C#中实现串口通信
- 串行通信的基本原理及用MFC实现串口通信编程
- VC实现串口通信例程(http://www.zahui.com/html/1/563.htm)
- 在C#中实现串口通信的方法
- 串口通信,C#,C++,短信发送模块实现