How does PySerial work?
Question: Say I have the following python script to read in serial data from my Arduino:

    
    
    import serial
    
    ser = serial.Serial("dev/ttyACM1", 9600)
    ser.timeout = 2
    ser.readlines()
    

On the other end I've flashed my Arduino with a program that sends 20 voltage
readings every 0.5 seconds. The Arduino starts sending those readings from the
moment it's hooked up, then after 20 seconds it stops and sends nothing.

Now what I've noticed is that I can read those 20 voltage values using the
first script whenever I want. That is, I can hook up the Arduino, wait a
couple of minutes then read in the values. This makes me think that the data
is getting stored somewhere. I'm inclined to think that it's not being stored
on the Arduino but on my laptop somewhere.

I've come up with a few questions that I hope the community could help me
with:

  1. Where is PySerial getting the data from (the Arduino or some buffer on my laptop)?
  2. For how long is the data stored in this place? 
  3. Is there a way to clear this space before reading in values?
  4. How much storage space is there?
  5. When you set the baud rate in PySerial (second line in script), is this the rate that PySerial reads data from the storage area (not the Arduino)?
  6. I've noticed that if I set the baud rate in PySerial too high the first few lines of data are fragmented and sometimes completely wrong, why?
  7. Not exactly related but when you set serial.Serial.timeout are the units in seconds?

I appreciate your time.


Answer: Have you tried using a terminal program like TerraTerm (windows) or GTKTerm
(linux) to open the same port to the arduino? I think this would be helpful to
answer some of your questions.

Some quick answers to your questions that I can dump off the top of my head.

  1. From the port specified, I'm guessing you are asking something deeper than this?
  2. If you do a 

x = ser.readlines()

then the data will be in x as long as you'd like.

  3. There is a flush function defined in PySerial
  4. Not sure. You can specify how many characters you would like to read though example:

x = ser.read(number) The pyserial documentation states the following Read size
bytes from the serial port. If a timeout is set it may return less characters
as requested. With no timeout it will block until the requested number of
bytes is read. <http://pyserial.sourceforge.net/pyserial_api.html>

  5. This is the clock rate of the port you are opening, ie /dev/ttyACM1, most serial comms are at 9600, if you happen to be using a USB to serial you'll need 115200

  6. Clock rate mismatch. You're computer is sampling data at a rate higher than the arduino is providing it, causing it to be incorrectly displayed.
  7. Seconds, quote from Pyserial documentation : "timeout = x: set timeout to x seconds (float allowed)" Same link as number 4

Hope that helps some!

