找回密码
 立即注册

扫一扫,访问微社区

QQ登录

只需一步,快速开始

查看: 5279|回复: 3

[代码与实例] pyqt写的串口调试2.7

1

主题

3

帖子

3

积分

贫民

积分
3
yangzi8000 发表于 2016-10-21 15:45:01 | 显示全部楼层 |阅读模式
  1. # coding=utf-8
  2. import sys
  3. from PyQt4 import QtCore, QtGui, uic
  4. import serial
  5. import serial.tools.list_ports

  6. from thread_1 import Threadq
  7. import threading
  8. qtCreatorFile = "serial.ui" # Enter file
  9. Ui_MainWindow, QtBaseClass = uic.loadUiType(qtCreatorFile)

  10. class MyApp(QtGui.QMainWindow, Ui_MainWindow):
  11.         def __init__(self):
  12.                 QtGui.QMainWindow.__init__(self)
  13.                 Ui_MainWindow.__init__(self)
  14.                 self.setupUi(self)
  15.                 self.setWindowTitle(u'终端配置软件') #修改窗口名字
  16.                
  17.                 self.comboBox1.addItems(self.port_list())
  18.                 self.comboBox2.addItems(['1200','2400','4800','9600','14400','19200','38400','56000','57600','115200'])
  19.                 self.comboBox2.setCurrentIndex(3)
  20.                 self.comboBox3.addItems(['5','6','7','8'])
  21.                 self.comboBox3.setCurrentIndex(3)
  22.                 self.comboBox4.addItems(['1','1.5','2'])
  23.                 self.comboBox4.setCurrentIndex(0)
  24.                 self.comboBox5.addItems(['NONE','EVEN','ODD','MARK','SPACE'])
  25.                 self.comboBox5.setCurrentIndex(0)
  26.                 self.pushButton1.clicked.connect(self.open_serial)
  27.                 self.pushButton2.clicked.connect(self.close_serial)
  28.                 self.pushButton1.setDisabled(False)
  29.                 self.pushButton2.setDisabled(True)
  30.                 self.ser=serial.Serial()
  31.                 self.thread=None
  32.                 self.alive=threading.Event()
  33.         def port_list(self):
  34.                 com_list=[]
  35.                 port_list=list(serial.tools.list_ports.comports())
  36.                 for port in port_list:
  37.                     com_list.append(port[0])
  38.                 return com_list
  39.         def open_serial(self):
  40.                 self.ser.port=str(self.comboBox1.currentText())#端口
  41.                 self.ser.baudrate = self.comboBox2.currentText()#波特率
  42.                 self.ser.bytesize=int(self.comboBox3.currentText())#数据位
  43.                 self.ser.stopbits  = int(self.comboBox4.currentText())                     
  44.                 self.ser.parity=str(self.comboBox5.currentText())[0]#字符串的第一个字母
  45.                 self.ser.timeout=None
  46.                 self.ser.open()
  47.                 self.pushButton1.setDisabled(True)
  48.                 self.pushButton2.setDisabled(False)
  49.                 print(self.ser.isOpen())
  50.                 self.thread=Threadq(target=self.read_serial,name='read_serial')
  51.                 self.thread.setDaemon(1)
  52.                 self.alive.set()
  53.                 self.thread.start()
  54.         def close_serial(self):
  55.                 self.ser.close()
  56.                 self.pushButton1.setDisabled(False)
  57.                 self.pushButton2.setDisabled(True)
  58.                 print(self.ser.isOpen())
  59.                 if self.thread is not None:
  60.                         self.alive.clear()
  61.                         self.thread.terminate()
  62.                         self.thread.join()
  63.         def send_serial(self,text):
  64.                 if self.alive.isSet():
  65.                         self.ser.write(text)
  66.                      
  67.                         
  68.         def read_serial(self):
  69.            
  70.                
  71.                 while self.alive.isSet():
  72.                         
  73.                         
  74.                         text=self.ser.read(30)#读取一个字符
  75.                         if text:
  76.                                 print(text)
  77.                                 self.send_serial(text)
  78.             
  79.                                  
  80. if __name__=='__main__':
  81.     app = QtGui.QApplication(sys.argv)
  82.     window = MyApp()
  83.     window.show()
  84.     sys.exit(app.exec_())
复制代码
回复

使用道具 举报

1

主题

3

帖子

3

积分

贫民

积分
3
yangzi8000  楼主| 发表于 2016-10-21 15:47:08 | 显示全部楼层
  1. import threading
  2. import inspect
  3. import ctypes


  4. def _async_raise(tid, exctype):
  5.   #  """raises the exception, performs cleanup if needed"""
  6.     if not inspect.isclass(exctype):
  7.             raise TypeError("Only types can be raised (not instances)")
  8.     res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(exctype))
  9.     if res == 0:
  10.         raise ValueError("invalid thread id")
  11.     elif res != 1:
  12.         # """if it returns a number greater than one, you're in trouble,
  13.         # and you should call it again with exc=NULL to revert the effect"""
  14.         ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, 0)
  15.         raise SystemError("PyThreadState_SetAsyncExc failed")
  16. class Threadq(threading.Thread):
  17.     def _get_my_tid(self):
  18.         #"""determines this (self's) thread id"""
  19.         if not self.isAlive():
  20.             raise threading.ThreadError("the thread is not active")     # do we have it cached?
  21.         if hasattr(self, "_thread_id"):
  22.             return self._thread_id     # no, look for it in the _active dict
  23.         for tid, tobj in threading._active.items():
  24.             if tobj is self:
  25.                 self._thread_id = tid
  26.                 return tid
  27.         raise AssertionError("could not determine the thread's id")
  28.     def raise_exc(self, exctype):
  29.         _async_raise(self._get_my_tid(), exctype)
  30.     def terminate(self):
  31.         self.raise_exc(SystemExit)
复制代码
回复 支持 反对

使用道具 举报

1

主题

3

帖子

3

积分

贫民

积分
3
yangzi8000  楼主| 发表于 2016-10-21 15:48:24 | 显示全部楼层
下面是Threadq的内容,放一个文件中也可以
回复 支持 反对

使用道具 举报

1419

主题

1891

帖子

291

积分

侠客

积分
291

最佳新人热心会员默默耕耘

whydo1 发表于 2016-10-22 20:38:25 | 显示全部楼层
支持!
python3.4.4, win10
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

快速回复 返回顶部 返回列表