2

I am writing an application that will allow me to connect to my device through selected serial port (using RS485). And everything works fine except one thing. When a pushbutton is clicked my app calls the funnction and opens the connection but then as soon as this function do everything it is supposed to the port connection imidiatlely closes. So when I want to use this connection later I receive an error that "serial is not defined".

def open_connection(self):
    cur_item = self.comboBox.currentText()
    if (cur_item) is not None:
        fullname = self.full_port_name(str(cur_item))
        try:                                                                     
            ser = serial.Serial(
            port=fullname, 
            baudrate=115200, 
            parity=serial.PARITY_NONE,
            stopbits=serial.STOPBITS_ONE,
            bytesize=serial.EIGHTBITS,
            timeout=None)                                                

        except SerialException, e:
            QMessageBox.critical(self, 'Failure',
                'Failed to open %s:\n%s' % (cur_item, e))

I want my connection to be open since the button is clicked to when I close the program so that i can use lineEdit (triggers other function after pressing enter) in the meantime to send some commands to device. Can you guys help me?

EDIT: Ok I solved this using QThreads. But still I don't know why if a certain part of my program is using serial port the other one can not do it w/o opening the port for itself (which is impossible since only one 'thing' may connect to a serial port at one time).

Devligue
  • 413
  • 5
  • 16
  • Do you correctly close your serial port using ser.close()? EDIT: Since you are using PyQt anyway, you should consider using the serial device classes it provides. PySerial is not under active development afaik. – sonovice Aug 31 '15 at 13:00
  • 2
    If you don't keep a reference to the `Serial` object, it will just be garbage-collected when the function returns. So you need to do something like `self.ser = serial.Serial(...)`. (PS: `currentText()` will never return `None`, so your if statement is currently redundant. Test for an empty string instead). – ekhumoro Aug 31 '15 at 16:22

0 Answers0