Monday, November 2, 2009

PySerial DTR and RTS Manipulation

Another application using (Python) PyQt and PySerial: a simple serial port LED blinker program.

two LEDs connected to DTR and RTS of a COM port (pins 4 and 7 of DB9):

simple python py script:
 import sys, serial  
from PyQt4.QtGui import *
from PyQt4.QtCore import *

class MyForm(QDialog):
def __init__(self, parent = None):
super(MyForm, self).__init__(parent)
self.setWindowTitle('PySerial DTR and RTS Manipulation')
self.setMinimumSize(300, 100)
# widgets
DTRlabel, RTSlabel = QLabel(), QLabel()
self.DTRbutton = QPushButton('set to Logic "True"')
self.RTSbutton = QPushButton('set to Logic "True"')
self.DTRcheckbox = QCheckBox('continuous toggle')
self.RTScheckbox = QCheckBox('continuous toggle')
# layout
layout = QGridLayout()
layout.addWidget(DTRlabel, 0, 0)
layout.addWidget(RTSlabel, 0, 1)
layout.addWidget(self.DTRbutton, 1, 0)
layout.addWidget(self.RTSbutton, 1, 1)
layout.addWidget(self.DTRcheckbox, 2, 0)
layout.addWidget(self.RTScheckbox, 2, 1)
self.setLayout(layout)
# serial port
self.port = serial.Serial('COM1')
DTRlabel.setText("<font size = 5 color = darkred><b> " +self.port.name + " DTR pin:</b></font>")
RTSlabel.setText("<font size = 5 color = darkred><b> " +self.port.name + " RTS pin:</b></font>")
self.DTRlogic, self.RTSlogic = False, False
self.port.setDTR(self.DTRlogic)
self.port.setRTS(self.RTSlogic)
# events
self.connect(self.DTRbutton, SIGNAL('clicked()'), self.toggleDTR)
self.connect(self.RTSbutton, SIGNAL('clicked()'), self.toggleRTS)
self.DTRtimer , self.RTStimer = QTimer(), QTimer()
self.connect(self.DTRtimer, SIGNAL('timeout()'), self.eventDTRtimer)
self.DTRtimer.start(250) # in milliseconds
self.connect(self.RTStimer, SIGNAL('timeout()'), self.eventRTStimer)
self.RTStimer.start(100) # in milliseconds

def toggleDTR(self):
self.DTRbutton.setText('set to Logic "' + str(self.DTRlogic) + '"')
self.DTRlogic = not self.DTRlogic # invert logic
self.port.setDTR(self.DTRlogic)
def toggleRTS(self):
self.RTSbutton.setText('set to Logic "' + str(self.RTSlogic) + '"')
self.RTSlogic = not self.RTSlogic # invert logic
self.port.setRTS(self.RTSlogic)
def eventDTRtimer(self):
if self.DTRcheckbox.isChecked():
self.toggleDTR()
def eventRTStimer(self):
if self.RTScheckbox.isChecked():
self.toggleRTS()

if __name__ == '__main__':
app = QApplication(sys.argv)
form = MyForm()
form.show()
sys.exit(app.exec_())


demo:

*the 'blink' rate depends on QTimer timeout period

forum link: serial port LED blinker

2 comments:

  1. Very nice, what resistors did you use?

    ReplyDelete
  2. Hi everyone. I have a question towards to the programmer, The following error pops up on the console:

    orlin@orlin-HP-Compaq-6715s-GR822ES-ABB:~/Desktop$ ./rs.py
    File "./rs.py", line 7
    class MyForm(QDialog):
    ^
    IndentationError: unexpected indent

    How can i handle this problem ?? Thank you in advance! Regards ! :)

    e-mail: orlin369@abv.bg

    ReplyDelete