I'm trying to read the status of a PushButton with python via pyserial.
In the loop function of Arduino Uno I have this:
void loop() {
if(digitalRead(BUTTON) == HIGH){
Serial.print("E\n");
while(1){}
}
So, if my pushbutton is pressed, it will send this message "E" via serial and then it will enter in an infinite loop so that nothing else happens.
But I want to detect this message in the python code. So this is my python code:
import serial
import time
try:
arduino = serial.Serial('/dev/ttyACM0', 9600)
except:
print "Failed to connect on /dev/ttyACM0"
try:
print arduino.readline()
while True:
if arduino.readline() == 'E':
print("Detected!\n")
except:
print ("Failed to read!")
The first print before the infinite While is working: it is printing in the ubuntu terminal "Program Initiated", which is a message that I'm sending in the void Setup function of Arduino.
Then, it gets stucked in the line:
if arduino.readline() == 'E':
I mean, I press several times my pushbutton, and nothing is happening.
Any help? Thanks!
-
Use arduino.read instead of arduino.readlineGerben– Gerben2017年02月12日 21:23:31 +00:00Commented Feb 12, 2017 at 21:23
-
Isn't more secure to use readline() once I will end up my message with \n?ajcoelho– ajcoelho2017年02月12日 23:37:06 +00:00Commented Feb 12, 2017 at 23:37
1 Answer 1
The string you are sending ("E\n"
) is not the same one you are checking for: 'E'
.
You could, for example, strip newlines from the string:
if arduino.readline().strip() == 'E':
-
You're right! I thought that as I was using .readline (which stops reading with \n) it wouldn't be necessary to put it on. Thanks, now it's working - without using that strip thing. What does it do exactly?ajcoelho– ajcoelho2017年02月12日 21:32:40 +00:00Commented Feb 12, 2017 at 21:32
-
strip()
removes newlines and whitespace from the start and end of strings. I'm slightly surprised thatreadline()
works at all if you're not sending newlines but OK if it does. Please feel free to accept the answer if it was helpful.Mark Smith– Mark Smith2017年02月12日 21:39:18 +00:00Commented Feb 12, 2017 at 21:39