Issue
I have posted some complex question earlier similar to this but in much simpler way. The major issue is whenever I am selecting the port from the drop-down menu and trying to open it to read the data from Arduino or wireless modem.
Every time I have to face the error of serial port not open.
The hard-code in which I am fixing the COM port is working perfectly fine
Mentioned below is the code I have simplified and trying to work with
import serial
import serial.tools.list_ports
from tkinter import *
ard = serial.Serial();
ard.baudrate = 9600
master = Tk()
variable = StringVar(master)
a=serial.tools.list_ports.comports()
for w in a:
print(w.device)
dev = [w.device]
print(dev)
variable.set(dev[0]) # default value
w = OptionMenu(master, variable, *dev)
w.pack()
ard.port = str(w)
ard.open
ard.is_open
#print(k)
def ok():
print (variable.get())
k = ard.readline()
button = Button(master, text="OK", command=ok)
button.pack()
mainloop()
but every time I am facing the error
COM4
['COM4']
COM4
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Misha\AppData\Local\Programs\Python\Python36\lib\tkinter\__init__.py", line 1702, in __call__
return self.func(*args)
File "C:\Users\Misha\Desktop\test\autoserial.py", line 27, in ok
k = ard.readline()
File "C:\Users\Misha\AppData\Local\Programs\Python\Python36\lib\site-packages\serial\serialwin32.py", line 267, in read
raise portNotOpenError
serial.serialutil.SerialException: Attempting to use a port that is not open
Please suggest which help me to make this work, Your leads will be a great help for me.
Solution
You have ard.open
in your code, but you aren't actually calling the method to open your serial connection. This is why you are getting an error saying Attempting to use a port that is not open
. Try ard.open()
to see if this works. This should open your port and make it usable.
However, given your setup, you probably want to wrap this around a callback that you can tie to another button or the OptionMenu
. It seems you'll want to the flexibility to choose ports and only open the port after choosing one.
Here's a small example of what it might look like:
import tkinter as tk
import serial
import serial.tools.list_ports
ard = serial.Serial();
ard.baudrate = 9600
a = serial.tools.list_ports.comports()
ports = [port.device for port in a]
def open_serial():
ard.port = variable.get()
ard.open()
print(f'Port {variable.get()} opened')
def close_serial():
p = ard.port
ard.close()
print(f'Port {p} closed')
master = tk.Tk()
variable = tk.StringVar()
variable.set(ports[0])
options = tk.OptionMenu(master, variable, *ports)
options.pack()
button_open = tk.Button(master, text='Open', command=open_serial)
button_open.pack()
button_close = tk.Button(master, text='Close', command=close_serial)
button_close.pack()
tk.mainloop()
Answered By - busybear
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.