使用python操作串口
一、
为了使用python操作串口,首先需要下载相关模块:
1. pyserial ()
2. pywin32 ()
二、
google “python 串口 操作”关键字,找到相关python代码,
我是从
http://currentlife.blog.sohu.com/53741351.html页面上拷贝
的代码。
咱得参考人家的代码修改。
三、
发送数据可用chr和pack组装处理,如:
snd = ''
snd += chr(97)
data = 0x12345678
snd += pack.('i', data)
snd += chr(0x64)
self.l_serial.write(snd);
#发送的数据是(16进制):61 78 56 34 12 64
接收的数据用ord
函数,将字节内容变为整数,进行判断处理。
如:if ord(recv[2])== 0x01:
判断recv[2]是否是0x01.
注意:不能这样比较
if recv[2] == 'a':
pass
也不能这样比较
if recv[2] == 0x97:
pass
因为python的字符串存储机制我不清楚,所以不知道为什么这样比较不可以。
帖点代码,依据前面的参考代码修改的:
#coding=gb18030
import sys,threading,time;
import serial;
import binascii,encodings;
import re;
import socket;
from struct import *;
class ComThread:
def __init__(self, Port=0):
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):
while self.alive:
# 接收间隔
time.sleep(0.1);
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)
self.l_serial.write(snddata);
# 判断结束
if len(data) > 0
and ord(data[len(data)-1])==0x45:
#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;