Python Serial Readline Example
Hi there I'm a OpenSesame and Python newbie who's running into timing problems. The goal is, to continuously read from a serial device and present a different stimulus every 5 seconds. After 5 stimuli or so, all the collected data is written to file. This doesn't seem to be very complicated, however I get some odd delays which I can't really explain. Here's my code: --- Prepare-Tab: (Imports and variable declaring is not interesting) Serial Port and IO-Wrapper ser = serial.Serial(1) sio = io.TextIOWrapper(io.BufferedRWPair(ser,ser,1), encoding='ascii') data = ([]) numOfPictures = 5 # define the number of pictures.
Hi, Interesting problem, and thanks a lot for the thorough explanation and investigation! I haven't actually used the io library much (only for buffering image streams), so I'm not quite familiar with it. I've tried looking your specific function up, but the aren't clear on whether there is a timeout in reading from a source like the Serial object. It seems like your code is simply waiting for something to become available to read, judging by the fact PRINT 5 never occurs. Could that be it?
Also, what is the Serial actually reading? Are they massive strings? Would it be an idea to specify a maximal line size, to prevent reading all of the built-up input at once? (Or, alternatively, to flush the input at the response window onset). Am I making any sense to you at all, or am I misunderstanding your setup completely?
Mar 12, 2004. When you create a file object in Python you can read from it in several different ways. Thanks commentors for pointing out that I and the Charmed Python book got it completely wrong. Readline() reads one line at a time. Xreadlines() also reads one line at a time. I've changed the example code above.
Thanks Edwin for your thoughts on this. Your understanding of the setup is quite correct. We have a plate which measures the balance of a person standing on it (similar to a Wii-board). It sends the coordinates every 100ms through a COM port in a string of 10 characters or so.
So there's 10 times per second a very short string, what leads to the assumption that the data itself shouldn't be a problem. I also watched the ressources of the system while running an experiment and the RAM usage is only rising some few megabytes, the CPU isn't fully loaded either. It just came to my mind that the line-variable should be deleted after each readline, that's probably why the PRINT 5 is never executed. What do you think about the design of the code? I first considered usage of multi-threading, with one thread reading the io-stream. But then I read a reply of yours on a similar question in the forum, suggesting this linear approach using an infinte while-loop. Can this approach even be accurate enought?
By accurate I mean a standard error of maybe 5ms. Ok here's a little update. Indeed, the problem is that io.readline() seems to take a timeout until a EOF is read. This means that the if not line.
In my while-loop is useless, since the loop 'sleeps' until a complete line is found. I would highly appreciate some good practices using pyserial. I'm just not sure if the current design is reliable enough. However, I also have a problem using the list containing self.offline_canvas() - objects. The following code only presents a black screen.
What's wrong in preparePics()? The path should be ok, the previous version where canvas(exp).show() was used ran flawlessly. NumOfPictures = 5 # define the number of pictures. (15 available atm) picsArr = [self.offline_canvas() for _ in range(numOfPictures)] def preparePics(): for i in range(numOfPictures): # i runs from 0 to 4 picsArr[i] = self.offline_canvas() # should be of no effect picture = 'bild ' + str(i)+ '.png' if not exp.file_in_pool(picture): print('image '%s' not found', picture) else: path = exp.get_file(picture) print(path) picsArr[i].image(path) def showPic(index): picsArr[index].show(). I would highly appreciate some good practices using pyserial. I'm just not sure if the current design is reliable enough.
My tip would be to avoid the io module (I don't know it, but it doesn't seem necessary here) and just use the pyserial API directly: • I don't think there are any 'magic tricks', everything is pretty much documented on the pyserial site. In general terms, you will need to read data from the serial port and make sure that it's segmented in the right way.
How you do this depends on the specifics of the device that you're communicating with. Maybe the vendor has some examples? If not, I would start by creating a short standalone Python script that does this. Once you have that, you can easily integrate it into your experiment.
However, I also have a problem using the list containing self.offline_canvas() - objects. The following code only presents a black screen. What's wrong in preparePics()? The path should be ok, the previous version where canvas(exp).show() was used ran flawlessly.
In this code snippet, there is no call to showPic(). In other words, if this is the entire script (?), nothing is shown.
If that's not it, you could try to do some more debugging, for example by printing out path (is it correct?) and drawing other things to the canvas objects so that you know for sure when it is presented.
Would be interested in how to clear the input serial buffer (and output?) as the following program example starts. When (re)starting the program the Pi seems to have happily accumulated everything and anything seen on the UART Rx line. This can be time consuming / messy esp if processing and forwarding data off the UART as we are doing to a web server etc. Import serial, time #this imports the libraries needed port = serial.Serial('/dev/ttyAMA0', baudrate=2400) #This sets up the serial port ttyAMA0 GPIO #baudrate is the bits per second. While True: rcv = port.readline() #read buffer until cr/lf #if not null then.
If(rcv): print ('Serial # = ' + repr(rcv)) #Echo the buffer bytes back to screen #&c. Can someone indicate where and how such a clear buffer command would go in the above example so it runs once on startup. I imagine it would be somewhere between the port command and the port.readline() command I imagine. For anyone interested the above port.readline() example works FAB with serial data arriving at the GPIO ad hoc / variable length and responds to the 13/10 LF/CR very nicely. Highly recommended when conversing and talking to picaxe etc. The read byte, read bytes and timeout functions have been 'discovered' already.
Superior Drummer Keygen Osx Snow. Can You Download Spotify Songs To An Ipod more. These took weeks to pull out of the www all over the place and usual fault finding and time consuming trial and error. Is there a code refference for this pyserial that is easy to find and use with syntax and examples some place. I imagine there will be an 'open' and 'close' command as well that would pretty much do the same thing and keep things tidy and under control. Thanks ~ Andrew. Hi Still trying to crack this one. It is most likely the mode or class (whatever that means) or environment I am running things in? This is just to set up simple classroom demo scripts running IDLE and minimal hardware and basic concepts.
+++++++++++++++++++ import serial, time #this imports the libraries needed port = serial.Serial('/dev/ttyAMA0', baudrate=2400) while True: flushinput() #clear serial buffer to remove junk and noise rcv = port.readline() #read buffer until cr/lf #if not null then. If(rcv): print ('Serial # = ' + repr(rcv)) #Echo the serial buffer bytes up to the CRLF back to screen Gives Python 2.7.3 (default, Mar 18 2014, 05:13:23) [GCC 4.6.3] on linux2 Type 'copyright', 'credits' or 'license()' for more information.
>>>================================ RESTART ================================ >>>Traceback (most recent call last): File '/home/pi/Documents/Python Pit/Serial/Read Cicadacom.py', line 14, in flushinput() NameError: name 'flushinput' is not defined >>>Ideas or another work-around?