0

My partner and I were able to write a txt file that recorded when we were and were not pushing a button down. We now want to read this file and make an LED blink when the txt file is read for "Button is pressed" and we want to make the LED turn off when the txt file is read for "Button is not pressed". We can get the txt file to print with all the correct information in it, but we cannot get the LED to turn on after everything we have tried.

We have tried using all the suggestions on the Python for Beginners page (https://www.pythonforbeginners.com/files/reading-and-writing-files-in-python) and String Comparison (String comparison in Python: is vs. ==). We have also tried using a string but we don't know if we implemented it the correct way. We also tried using this problem for guidance (Python Read file to turn on LED: String comparison in Python: is vs. ==). This is the code we have mainly been coming back to:

from gpiozero import LED

from time import sleep

blue = LED(17)

file = open("/home/pi/Documents/buttonfile.txt","r")

while True:

    myfile = (file.readline())
    sleep(1)
    print (myfile)
    if myfile == ("Button is pressed"):
        print (myfile)
        blue.on()
        sleep (1)
    else:
        blue.off()

file.close()

From this, we are getting the Raspberry Pi to print the correct information that is in the .txt file, but the LED is doing nothing.

HelgeFox
  • 349
  • 2
  • 13
  • 1
    it might be a new line at the end try to change `myfile = (file.readline())` to `myfile = (file.readline()).strip()` – Mahmoud Elshahat Apr 24 '19 at 22:20
  • Have you gotten Python to turn on the lights at all? Do you know that part works? – MyNameIsCaleb Apr 24 '19 at 22:35
  • In a similar thought like @MahmoudElshahat (and proposing the question of GiraffeMan is answered yes) I would alternatively recommend the check `if "Button is pressed" in myfile:`. That said - why do you (and Mahmoud) use all those parantheses...? – SpghttCd Apr 24 '19 at 22:43
  • 1
    @SpghttCd i didn't want to confuse him, i just put extra .strip() so he can get the idea – Mahmoud Elshahat Apr 24 '19 at 22:51
  • So doesn't the .strip() just take the txt file and take out any spaces or line breaks? How would that help the information be read as individual statements that can turn on and off and LED if it is all put into one string?... Also, I am a woman, just so you know. – Buffalo B Apr 25 '19 at 15:40
  • No strip removes _leading and trailing white spaces_ - and in your case, not of the whole text file but of the current line, because you named each next read line `myfile`. Perhaps you should change this as well... – SpghttCd Apr 25 '19 at 20:30
  • Thank you @MahmoudElshahat. That .strip() did the trick! – Buffalo B Apr 25 '19 at 22:09
  • And thank you @SpghttCd for explaining that in more detail! – Buffalo B Apr 25 '19 at 22:09

0 Answers0