Reconnecting to device with pySerial

2024/11/6 9:40:44

I am currently having a problem with the pySerial module in Python. My problem relates to connecting and disconnecting to a device. I can successfully connect to my device and communicate with it for as long as I want to, and disconnect from it whenever I desire. However, I am unable to reconnect to the device once the connection has been severed.

Here is the wrapper class that my program uses to interface with the serial port:

import serial, tkMessageBoxclass Controller:
""" Wrapper class for managing the serial connection with the MS-2000. """def __init__(self, settings):self.ser = Noneself.settings = settingsdef connect(self):""" Connect or disconnect to MS-2000. Return connection status."""try:if self.ser == None:self.ser = serial.Serial(self.settings['PORT'],self.settings['BAUDRATE'])print "Successfully connected to port %r." % self.ser.portreturn Trueelse:if self.ser.isOpen():self.ser.close()print "Disconnected."return Falseelse:self.ser.open()print "Connected."return Trueexcept serial.SerialException, e:return Falsedef isConnected(self):'''Is the computer connected with the MS-2000?'''try:return self.ser.isOpen()except:return Falsedef write(self, command):""" Sends command to MS-2000, appending a carraige return. """try:self.ser.write(command + '\r')except Exception, e:tkMessageBox.showerror('Serial connection error','Error sending message "%s" to MS-2000:\n%s' %(command, e))def read(self, chars):""" Reads specified number of characters from the serial port. """return self.ser.read(chars)

Does anybody know the reason why this problem exists and what I could try to do to fix it?

Answer

You aren't releasing the serial port when you are finished. Use ser.close() to close the port before exiting your program, otherwise the port will stay locked indefinitely. I would suggest adding a method called disconnect() in your class for this.

If you are on Windows, to remedy the situation during testing, start Task Manager and kill any python.exe or pythonw.exe processes that may be locking the serial port.

https://en.xdnf.cn/q/70955.html

Related Q&A

How to check if a sentence is a question with spacy?

I am using spacy library to build a chat bot. How do I check if a document is a question with a certain confidence? I know how to do relevance, but not sure how to filter statements from questions.I a…

Python: Lifetime of module-global variables

I have a shared resource with high initialisation cost and thus I want to access it across the system (its used for some instrumentation basically, so has to be light weight). So I created a module man…

Power spectrum with Cython

I am trying to optimize my code with Cython. It is doing a a power spectrum, not using FFT, because this is what we were told to do in class. Ive tried to write to code in Cython, but do not see any di…

Detect abbreviations in the text in python

I want to find abbreviations in the text and remove it. What I am currently doing is identifying consecutive capital letters and remove them.But I see that it does not remove abbreviations such as MOOC…

filtering of tweets received from statuses/filter (streaming API)

I have N different keywords that i am tracking (for sake of simplicity, let N=3). So in GET statuses/filter, I will give 3 keywords in the "track" argument.Now the tweets that i will be recei…

UndefinedError: current_user is undefined

I have a app with flask which works before But Now I use Blueprint in it and try to run it but got the error so i wonder that is the problem Blueprint that g.user Not working? and how can I fix it Thn…

Scipy filter with multi-dimensional (or non-scalar) output

Is there a filter similar to ndimages generic_filter that supports vector output? I did not manage to make scipy.ndimage.filters.generic_filter return more than a scalar. Uncomment the line in the cod…

How do I stop execution inside exec command in Python 3?

I have a following code:code = """ print("foo")if True: returnprint("bar") """exec(code) print(This should still be executed)If I run it I get:Tracebac…

sqlalchemy concurrency update issue

I have a table, jobs, with fields id, rank, and datetime started in a MySQL InnoDB database. Each time a process gets a job, it "checks out" that job be marking it started, so that no other p…

Python matplotlib: Change axis labels/legend from bold to regular weight

Im trying to make some publication-quality plots, but I have encountered a small problem. It seems by default that matplotlib axis labels and legend entries are weighted heavier than the axis tick mark…