0

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.readline – Gerben Feb 12 '17 at 21:23
  • Isn't more secure to use readline() once I will end up my message with \n? – ajcoelho Feb 12 '17 at 23:37
0

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 Feb 12 '17 at 21:32
  • strip() removes newlines and whitespace from the start and end of strings. I'm slightly surprised that readline() 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 Feb 12 '17 at 21:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.