当前位置:编程学习 > 网站相关 >>

串口模块

该模块为线程对象,具体看代码。使用serial模块,数据接收为超时接收。适当的修改timeout可以变得更加合适于工作上的需要。调用serial的方法,可以在线程运行时修改串口的参数,自行修改这个模块。要很好的使用该模块,自己再了解下import 进来的几个模块。serial模块是需要自己进行安装的。python不自带。其他模块python2.5以上都是自带的。

 
01
#!/usr/bin/env python
02
#-*- encoding: gb18030 -*-
03
import threading
04
import Queue
05
import serial
06
import time
07
 
08
class ComOpen(threading.Thread):
09
    def __init__(self,port=None,baudrate=None,parity=None,bytesize=None,stopbits=None,queue=None):
10
        self.comm= serial.Serial()
11
        self.queue= queue
12
        self.comm.port = port
13
        self.comm.baudrate = baudrate
14
        self.comm.parity = parity
15
        self.comm.bytesize = bytesize
16
        self.comm.stopbits = stopbits
17
        self.comm.setTimeout(0.5)
18
        self.comm.open()
19
        self.thread_stop=False
20
        self.string=''
21
        threading.Thread.__init__(self)
22
 
23
    def run(self):
24
        while not self.thread_stop:
25
            try:
26
                s=self.comm.read()
27
                if len(s)>0:
28
                    self.string +=s
29
                elif len(self.string)>0:
30
                    self.queue.put(self.string)
31
##                    print self.string
32
                    self.string=''
33
                else:
34
                    pass
35
            except Exception,data:
36
                if data.message=="timed out" and len(self.string)>0:
37
                    print data
38
                    self.queue.put(self.string)
39
                    self.string=''
40
                    continue
41
                elif data.message=="timed out":
42
                    print data
43
                    continue
44
                else:
45
                    print data
46
                    self.stop()
47
 
48
    def senddate(self,data):
49
        if not self.thread_stop:
50
            self.comm.write(data)
51
 
52
    def stop(self):
53
        self.thread_stop=True
54
        try:
55
            self.comm.flush()
56
            self.comm.close()
57
        except Exception,data:
58
            print data

补充:综合编程 , 其他综合 ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,