Connect to serial from a PyQt GUI Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 00:00UTC (8:00pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!PyQt5 - Main interface not showing while serial data receivingHow to randomly select an item from a list?How do I connect to a MySQL Database in Python?Why can't Python parse this JSON data?Why is reading lines from stdin much slower in C++ than Python?Python: AttributeError: type object 'Ui_Form' has no attribute 'comboBox'How can I save output tho the same file that I have got the data from, in Python 3PyQt5 button click not work in imported classHow to read all message from queue using stomp library in Python?multiple gui python qt and switch between themDynamically add rows and columns in QTable in pyQT5

Chinese Seal on silk painting - what does it mean?

Dating a Former Employee

Did Krishna say in Bhagavad Gita "I am in every living being"

Project Euler #1 in C++

Why does it sometimes sound good to play a grace note as a lead in to a note in a melody?

Do wooden building fires get hotter than 600°C?

Why is the AVR GCC compiler using a full `CALL` even though I have set the `-mshort-calls` flag?

Performance gap between vector<bool> and array

How would a mousetrap for use in space work?

How to write this math term? with cases it isn't working

Why wasn't DOSKEY integrated with COMMAND.COM?

Hangman Game with C++

Why do we bend a book to keep it straight?

When a candle burns, why does the top of wick glow if bottom of flame is hottest?

Why should I vote and accept answers?

AppleTVs create a chatty alternate WiFi network

Maximum summed subsequences with non-adjacent items

Why do we need to use the builder design pattern when we can do the same thing with setters?

Is it fair for a professor to grade us on the possession of past papers?

How to react to hostile behavior from a senior developer?

Did Deadpool rescue all of the X-Force?

Is a ledger board required if the side of my house is wood?

Should I use a zero-interest credit card for a large one-time purchase?

Take 2! Is this homebrew Lady of Pain warlock patron balanced?



Connect to serial from a PyQt GUI



Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 23, 2019 at 00:00UTC (8:00pm US/Eastern)
Data science time! April 2019 and salary with experience
The Ask Question Wizard is Live!PyQt5 - Main interface not showing while serial data receivingHow to randomly select an item from a list?How do I connect to a MySQL Database in Python?Why can't Python parse this JSON data?Why is reading lines from stdin much slower in C++ than Python?Python: AttributeError: type object 'Ui_Form' has no attribute 'comboBox'How can I save output tho the same file that I have got the data from, in Python 3PyQt5 button click not work in imported classHow to read all message from queue using stomp library in Python?multiple gui python qt and switch between themDynamically add rows and columns in QTable in pyQT5



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








2















I write a program to that send and recive data from serial, but I have a problem, I want to create a function "connect()" or a class, and when I press a button, the function is executed, but if I create this function in "MainWindow" class, variable "ser" from "TestThread" class become uninitialized, can you help me?



import sys
import serial


from PyQt5.QtWidgets import QMainWindow, QApplication
from PyQt5.QtCore import QThread, pyqtSignal
from PyQt5.uic import loadUi


ser = serial.Serial('/dev/tty.usbmodem14201', 9600, timeout=1)

class TestThread(QThread):
serialUpdate = pyqtSignal(str)
def run(self):
while ser.is_open:
QThread.sleep(1)
value = ser.readline().decode('ascii')
self.serialUpdate.emit(value)
ser.flush()

class MainWindow(QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
loadUi('/Users/bogdanvesa/P2A_GUI/mainwindow.ui', self)
self.thread = TestThread(self)
self.thread.serialUpdate.connect(self.handleSerialUpdate)

self.connect_btn.clicked.connect(self.connectSer)
self.lcd_EBtn.clicked.connect(self.startThread)

def startThread(self):
self.thread.start()

def handleSerialUpdate(self, value):
print(value)
self.lcd_lineEdit.setText(value)


def main():

app = QApplication(sys.argv)
form = MainWindow()
form.show()
sys.exit(app.exec_())

if __name__ == "__main__":
main()









share|improve this question






















  • Explain yourself better

    – eyllanesc
    Mar 8 at 20:31











  • @eyllanesc Ok, when I press a button, I want the connection to Arduino be made (open serial), when I press another button close connection (close serial) but I have no idea how to make this

    – Vesa95
    Mar 8 at 20:38


















2















I write a program to that send and recive data from serial, but I have a problem, I want to create a function "connect()" or a class, and when I press a button, the function is executed, but if I create this function in "MainWindow" class, variable "ser" from "TestThread" class become uninitialized, can you help me?



import sys
import serial


from PyQt5.QtWidgets import QMainWindow, QApplication
from PyQt5.QtCore import QThread, pyqtSignal
from PyQt5.uic import loadUi


ser = serial.Serial('/dev/tty.usbmodem14201', 9600, timeout=1)

class TestThread(QThread):
serialUpdate = pyqtSignal(str)
def run(self):
while ser.is_open:
QThread.sleep(1)
value = ser.readline().decode('ascii')
self.serialUpdate.emit(value)
ser.flush()

class MainWindow(QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
loadUi('/Users/bogdanvesa/P2A_GUI/mainwindow.ui', self)
self.thread = TestThread(self)
self.thread.serialUpdate.connect(self.handleSerialUpdate)

self.connect_btn.clicked.connect(self.connectSer)
self.lcd_EBtn.clicked.connect(self.startThread)

def startThread(self):
self.thread.start()

def handleSerialUpdate(self, value):
print(value)
self.lcd_lineEdit.setText(value)


def main():

app = QApplication(sys.argv)
form = MainWindow()
form.show()
sys.exit(app.exec_())

if __name__ == "__main__":
main()









share|improve this question






















  • Explain yourself better

    – eyllanesc
    Mar 8 at 20:31











  • @eyllanesc Ok, when I press a button, I want the connection to Arduino be made (open serial), when I press another button close connection (close serial) but I have no idea how to make this

    – Vesa95
    Mar 8 at 20:38














2












2








2








I write a program to that send and recive data from serial, but I have a problem, I want to create a function "connect()" or a class, and when I press a button, the function is executed, but if I create this function in "MainWindow" class, variable "ser" from "TestThread" class become uninitialized, can you help me?



import sys
import serial


from PyQt5.QtWidgets import QMainWindow, QApplication
from PyQt5.QtCore import QThread, pyqtSignal
from PyQt5.uic import loadUi


ser = serial.Serial('/dev/tty.usbmodem14201', 9600, timeout=1)

class TestThread(QThread):
serialUpdate = pyqtSignal(str)
def run(self):
while ser.is_open:
QThread.sleep(1)
value = ser.readline().decode('ascii')
self.serialUpdate.emit(value)
ser.flush()

class MainWindow(QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
loadUi('/Users/bogdanvesa/P2A_GUI/mainwindow.ui', self)
self.thread = TestThread(self)
self.thread.serialUpdate.connect(self.handleSerialUpdate)

self.connect_btn.clicked.connect(self.connectSer)
self.lcd_EBtn.clicked.connect(self.startThread)

def startThread(self):
self.thread.start()

def handleSerialUpdate(self, value):
print(value)
self.lcd_lineEdit.setText(value)


def main():

app = QApplication(sys.argv)
form = MainWindow()
form.show()
sys.exit(app.exec_())

if __name__ == "__main__":
main()









share|improve this question














I write a program to that send and recive data from serial, but I have a problem, I want to create a function "connect()" or a class, and when I press a button, the function is executed, but if I create this function in "MainWindow" class, variable "ser" from "TestThread" class become uninitialized, can you help me?



import sys
import serial


from PyQt5.QtWidgets import QMainWindow, QApplication
from PyQt5.QtCore import QThread, pyqtSignal
from PyQt5.uic import loadUi


ser = serial.Serial('/dev/tty.usbmodem14201', 9600, timeout=1)

class TestThread(QThread):
serialUpdate = pyqtSignal(str)
def run(self):
while ser.is_open:
QThread.sleep(1)
value = ser.readline().decode('ascii')
self.serialUpdate.emit(value)
ser.flush()

class MainWindow(QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
loadUi('/Users/bogdanvesa/P2A_GUI/mainwindow.ui', self)
self.thread = TestThread(self)
self.thread.serialUpdate.connect(self.handleSerialUpdate)

self.connect_btn.clicked.connect(self.connectSer)
self.lcd_EBtn.clicked.connect(self.startThread)

def startThread(self):
self.thread.start()

def handleSerialUpdate(self, value):
print(value)
self.lcd_lineEdit.setText(value)


def main():

app = QApplication(sys.argv)
form = MainWindow()
form.show()
sys.exit(app.exec_())

if __name__ == "__main__":
main()






python python-3.x pyqt5 pyserial






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 8 at 20:21









Vesa95Vesa95

287




287












  • Explain yourself better

    – eyllanesc
    Mar 8 at 20:31











  • @eyllanesc Ok, when I press a button, I want the connection to Arduino be made (open serial), when I press another button close connection (close serial) but I have no idea how to make this

    – Vesa95
    Mar 8 at 20:38


















  • Explain yourself better

    – eyllanesc
    Mar 8 at 20:31











  • @eyllanesc Ok, when I press a button, I want the connection to Arduino be made (open serial), when I press another button close connection (close serial) but I have no idea how to make this

    – Vesa95
    Mar 8 at 20:38

















Explain yourself better

– eyllanesc
Mar 8 at 20:31





Explain yourself better

– eyllanesc
Mar 8 at 20:31













@eyllanesc Ok, when I press a button, I want the connection to Arduino be made (open serial), when I press another button close connection (close serial) but I have no idea how to make this

– Vesa95
Mar 8 at 20:38






@eyllanesc Ok, when I press a button, I want the connection to Arduino be made (open serial), when I press another button close connection (close serial) but I have no idea how to make this

– Vesa95
Mar 8 at 20:38













1 Answer
1






active

oldest

votes


















0














Instead of using pySerial + thread it is better to use QSerialPort that is made to live with the Qt event-loop:



from PyQt5 import QtCore, QtWidgets, QtSerialPort

class Widget(QtWidgets.QWidget):
def __init__(self, parent=None):
super(Widget, self).__init__(parent)
self.message_le = QtWidgets.QLineEdit()
self.send_btn = QtWidgets.QPushButton(
text="Send",
clicked=self.send
)
self.output_te = QtWidgets.QTextEdit(readOnly=True)
self.button = QtWidgets.QPushButton(
text="Connect",
checkable=True,
toggled=self.on_toggled
)
lay = QtWidgets.QVBoxLayout(self)
hlay = QtWidgets.QHBoxLayout()
hlay.addWidget(self.message_le)
hlay.addWidget(self.send_btn)
lay.addLayout(hlay)
lay.addWidget(self.output_te)
lay.addWidget(self.button)

self.serial = QtSerialPort.QSerialPort(
'/dev/tty.usbmodem14201',
baudRate=QtSerialPort.QSerialPort.Baud9600,
readyRead=self.receive
)

@QtCore.pyqtSlot()
def receive(self):
while self.serial.canReadLine():
text = self.serial.readLine().data().decode()
text = text.rstrip('rn')
self.output_te.append(text)

@QtCore.pyqtSlot()
def send(self):
self.serial.write(self.message_le.text().encode())

@QtCore.pyqtSlot(bool)
def on_toggled(self, checked):
self.button.setText("Disconnect" if checked else "Connect")
if checked:
if not self.serial.isOpen():
if not self.serial.open(QtCore.QIODevice.ReadWrite):
self.button.setChecked(False)
else:
self.serial.close()

if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
w = Widget()
w.show()
sys.exit(app.exec_())





share|improve this answer























  • thank you a lot, I'll use your code, but for my peace, is possible to connect to serial from a button from my "main window" class? in the same time my "TestThread" class to run fine.. can you give me an example?

    – Vesa95
    Mar 8 at 22:19











Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55070483%2fconnect-to-serial-from-a-pyqt-gui%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









0














Instead of using pySerial + thread it is better to use QSerialPort that is made to live with the Qt event-loop:



from PyQt5 import QtCore, QtWidgets, QtSerialPort

class Widget(QtWidgets.QWidget):
def __init__(self, parent=None):
super(Widget, self).__init__(parent)
self.message_le = QtWidgets.QLineEdit()
self.send_btn = QtWidgets.QPushButton(
text="Send",
clicked=self.send
)
self.output_te = QtWidgets.QTextEdit(readOnly=True)
self.button = QtWidgets.QPushButton(
text="Connect",
checkable=True,
toggled=self.on_toggled
)
lay = QtWidgets.QVBoxLayout(self)
hlay = QtWidgets.QHBoxLayout()
hlay.addWidget(self.message_le)
hlay.addWidget(self.send_btn)
lay.addLayout(hlay)
lay.addWidget(self.output_te)
lay.addWidget(self.button)

self.serial = QtSerialPort.QSerialPort(
'/dev/tty.usbmodem14201',
baudRate=QtSerialPort.QSerialPort.Baud9600,
readyRead=self.receive
)

@QtCore.pyqtSlot()
def receive(self):
while self.serial.canReadLine():
text = self.serial.readLine().data().decode()
text = text.rstrip('rn')
self.output_te.append(text)

@QtCore.pyqtSlot()
def send(self):
self.serial.write(self.message_le.text().encode())

@QtCore.pyqtSlot(bool)
def on_toggled(self, checked):
self.button.setText("Disconnect" if checked else "Connect")
if checked:
if not self.serial.isOpen():
if not self.serial.open(QtCore.QIODevice.ReadWrite):
self.button.setChecked(False)
else:
self.serial.close()

if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
w = Widget()
w.show()
sys.exit(app.exec_())





share|improve this answer























  • thank you a lot, I'll use your code, but for my peace, is possible to connect to serial from a button from my "main window" class? in the same time my "TestThread" class to run fine.. can you give me an example?

    – Vesa95
    Mar 8 at 22:19















0














Instead of using pySerial + thread it is better to use QSerialPort that is made to live with the Qt event-loop:



from PyQt5 import QtCore, QtWidgets, QtSerialPort

class Widget(QtWidgets.QWidget):
def __init__(self, parent=None):
super(Widget, self).__init__(parent)
self.message_le = QtWidgets.QLineEdit()
self.send_btn = QtWidgets.QPushButton(
text="Send",
clicked=self.send
)
self.output_te = QtWidgets.QTextEdit(readOnly=True)
self.button = QtWidgets.QPushButton(
text="Connect",
checkable=True,
toggled=self.on_toggled
)
lay = QtWidgets.QVBoxLayout(self)
hlay = QtWidgets.QHBoxLayout()
hlay.addWidget(self.message_le)
hlay.addWidget(self.send_btn)
lay.addLayout(hlay)
lay.addWidget(self.output_te)
lay.addWidget(self.button)

self.serial = QtSerialPort.QSerialPort(
'/dev/tty.usbmodem14201',
baudRate=QtSerialPort.QSerialPort.Baud9600,
readyRead=self.receive
)

@QtCore.pyqtSlot()
def receive(self):
while self.serial.canReadLine():
text = self.serial.readLine().data().decode()
text = text.rstrip('rn')
self.output_te.append(text)

@QtCore.pyqtSlot()
def send(self):
self.serial.write(self.message_le.text().encode())

@QtCore.pyqtSlot(bool)
def on_toggled(self, checked):
self.button.setText("Disconnect" if checked else "Connect")
if checked:
if not self.serial.isOpen():
if not self.serial.open(QtCore.QIODevice.ReadWrite):
self.button.setChecked(False)
else:
self.serial.close()

if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
w = Widget()
w.show()
sys.exit(app.exec_())





share|improve this answer























  • thank you a lot, I'll use your code, but for my peace, is possible to connect to serial from a button from my "main window" class? in the same time my "TestThread" class to run fine.. can you give me an example?

    – Vesa95
    Mar 8 at 22:19













0












0








0







Instead of using pySerial + thread it is better to use QSerialPort that is made to live with the Qt event-loop:



from PyQt5 import QtCore, QtWidgets, QtSerialPort

class Widget(QtWidgets.QWidget):
def __init__(self, parent=None):
super(Widget, self).__init__(parent)
self.message_le = QtWidgets.QLineEdit()
self.send_btn = QtWidgets.QPushButton(
text="Send",
clicked=self.send
)
self.output_te = QtWidgets.QTextEdit(readOnly=True)
self.button = QtWidgets.QPushButton(
text="Connect",
checkable=True,
toggled=self.on_toggled
)
lay = QtWidgets.QVBoxLayout(self)
hlay = QtWidgets.QHBoxLayout()
hlay.addWidget(self.message_le)
hlay.addWidget(self.send_btn)
lay.addLayout(hlay)
lay.addWidget(self.output_te)
lay.addWidget(self.button)

self.serial = QtSerialPort.QSerialPort(
'/dev/tty.usbmodem14201',
baudRate=QtSerialPort.QSerialPort.Baud9600,
readyRead=self.receive
)

@QtCore.pyqtSlot()
def receive(self):
while self.serial.canReadLine():
text = self.serial.readLine().data().decode()
text = text.rstrip('rn')
self.output_te.append(text)

@QtCore.pyqtSlot()
def send(self):
self.serial.write(self.message_le.text().encode())

@QtCore.pyqtSlot(bool)
def on_toggled(self, checked):
self.button.setText("Disconnect" if checked else "Connect")
if checked:
if not self.serial.isOpen():
if not self.serial.open(QtCore.QIODevice.ReadWrite):
self.button.setChecked(False)
else:
self.serial.close()

if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
w = Widget()
w.show()
sys.exit(app.exec_())





share|improve this answer













Instead of using pySerial + thread it is better to use QSerialPort that is made to live with the Qt event-loop:



from PyQt5 import QtCore, QtWidgets, QtSerialPort

class Widget(QtWidgets.QWidget):
def __init__(self, parent=None):
super(Widget, self).__init__(parent)
self.message_le = QtWidgets.QLineEdit()
self.send_btn = QtWidgets.QPushButton(
text="Send",
clicked=self.send
)
self.output_te = QtWidgets.QTextEdit(readOnly=True)
self.button = QtWidgets.QPushButton(
text="Connect",
checkable=True,
toggled=self.on_toggled
)
lay = QtWidgets.QVBoxLayout(self)
hlay = QtWidgets.QHBoxLayout()
hlay.addWidget(self.message_le)
hlay.addWidget(self.send_btn)
lay.addLayout(hlay)
lay.addWidget(self.output_te)
lay.addWidget(self.button)

self.serial = QtSerialPort.QSerialPort(
'/dev/tty.usbmodem14201',
baudRate=QtSerialPort.QSerialPort.Baud9600,
readyRead=self.receive
)

@QtCore.pyqtSlot()
def receive(self):
while self.serial.canReadLine():
text = self.serial.readLine().data().decode()
text = text.rstrip('rn')
self.output_te.append(text)

@QtCore.pyqtSlot()
def send(self):
self.serial.write(self.message_le.text().encode())

@QtCore.pyqtSlot(bool)
def on_toggled(self, checked):
self.button.setText("Disconnect" if checked else "Connect")
if checked:
if not self.serial.isOpen():
if not self.serial.open(QtCore.QIODevice.ReadWrite):
self.button.setChecked(False)
else:
self.serial.close()

if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
w = Widget()
w.show()
sys.exit(app.exec_())






share|improve this answer












share|improve this answer



share|improve this answer










answered Mar 8 at 21:48









eyllanesceyllanesc

88.9k103565




88.9k103565












  • thank you a lot, I'll use your code, but for my peace, is possible to connect to serial from a button from my "main window" class? in the same time my "TestThread" class to run fine.. can you give me an example?

    – Vesa95
    Mar 8 at 22:19

















  • thank you a lot, I'll use your code, but for my peace, is possible to connect to serial from a button from my "main window" class? in the same time my "TestThread" class to run fine.. can you give me an example?

    – Vesa95
    Mar 8 at 22:19
















thank you a lot, I'll use your code, but for my peace, is possible to connect to serial from a button from my "main window" class? in the same time my "TestThread" class to run fine.. can you give me an example?

– Vesa95
Mar 8 at 22:19





thank you a lot, I'll use your code, but for my peace, is possible to connect to serial from a button from my "main window" class? in the same time my "TestThread" class to run fine.. can you give me an example?

– Vesa95
Mar 8 at 22:19



















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55070483%2fconnect-to-serial-from-a-pyqt-gui%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

1928 у кіно

Захаров Федір Захарович

Ель Греко