Reputation: 31
I'm using an arduino uno with the basic "DigitalReadSerial" setup as outlined here: http://arduino.cc/en/Tutorial/DigitalReadSerial
If i use the serial monitor included with the arduino IDE, it immediately displays any changes from pressing the button.
This is what i want in pyserial, either a 0 or a 1 depending on whether the button is pressed. (to eventually trigger a timer)
just to test it, i threw this together, not the prettiest, but it seems to read out the pushbutton state, but there is a 20second delay.
import serial
ser = serial.Serial()
ser.setPort("COM2")
ser.baudrate = 9600
ser.open()
while 1==1:
ser.readline()
Does anyone have any ideas?
Upvotes: 3
Views: 9633
Reputation: 699
Only commence a readline if there is something to read otherwise it will either block while waiting for eol, or it may time out half way through reading the serial buffer, truncating your string. This speeds up the loop, and allows you to use a short timeout, great for cycling through multiple ports. Using pyserial3.0...
while 1:
if ser.in_waiting > 0:
data = ser.readline()
print(data)
Also try something like
while 1:
if ser.in_waiting > 0:
data = ser.read(32)
print(data)
Which will not care if the buffer contains less than the specified bytes, I sometimes do as it will read/flush out extra data that has builds up in the buffer.
Upvotes: 1
Reputation:
I just met the same problem and I'm sure there is no delay in PySerial.
The delay was caused by the delay in my PyQT Thread .I print through serial port in arduino with one line/0.1sec but I read the serial output in QThread with a 0.5sec delay,that's the problem.As time goes by,the delay will increase.
I verified that by extracting pyserial reading code from my project.Just remember,the read frequency should not be less than the write frequency.
From your code,I assume that your python enviroment if not fast enough to receive the data from arduino in time.
Try to slow down the serial print speed by insert a small delay between two print.
Upvotes: 1
Reputation: 31
It seems to be a caching/sync problem, similar to those that affects the file sync in common filesystems. I have suffered that problem with my arduino/pyserial... until now?
From http://pyserial.sourceforge.net/pyserial_api.html, if I put the 3 flush commands: ser.flush(), ser.flushInput() and ser.flushOutput() in my program, it seems to work as expected.
Upvotes: 3
Reputation: 23166
Are you using Serial.print
or Serial.println
in your Arduino code? If the former, its not going to issue a carriage return and the ser.readline()
in your code will be waiting for one.
Upvotes: 1