Simple button is not working #9328
-
Hello! I am fairly new to microcontrollers, but have successfully programed a short script (CircuitPython) in the past, and I have absolutely no clue what is going on here (With MicroPython). The board is a Raspberry Pi Pico W running version My code is: from machine import Pin
btn = Pin(0, Pin.IN)
while True:
if btn() == 1:
print("pushed")
else:
print("Not pushed") Looking at this image, I am using 1 ( Since the button does not seem to work right at all, I just removed it and tried the below to see how the output changes when I changed the input. So here are the four things I have done, and what happens when I do them:
So for some reason it always just prints whatever it's initial state was, why is this? Apologies if the answer is really really simple, but nothing I find on the internet seems to work at all. Thanks in advance! |
Beta Was this translation helpful? Give feedback.
Replies: 7 comments 4 replies
-
Try changing: if btn() == 1: to if btn.value() == 1: |
Beta Was this translation helpful? Give feedback.
-
OK, I am working through a similar issue where GPIO state is unchanged on doing a CTRL-C in rshell. Something else to try before your while loop: btn.off() then at least you know what state you are starting off in. |
Beta Was this translation helpful? Give feedback.
-
After btn.off() put print (' btn state = ', btn.value()) Sorry, I don't use Thonny so maybe I am missing something there. |
Beta Was this translation helpful? Give feedback.
-
Do you have an external pull resistor to define the button open state? You do not use the |
Beta Was this translation helpful? Give feedback.
-
I can confirm Roberts code works as expected or almost, there are a couple of obvious and minor typos in Roberts code. |
Beta Was this translation helpful? Give feedback.
-
I figured it out. For future reference, this worked for me: from machine import Pin
btn = machine.Pin(0, machine.Pin.IN, machine.Pin.PULL_DOWN)
last_state = False
current_state = False
while True:
current_state = btn.value()
if last_state == False and current_state == True:
print ('pushed')
last_state = current_state Thanks to everyone that replied! |
Beta Was this translation helpful? Give feedback.
-
Just FYI @davefes @greenreader9 -- |
Beta Was this translation helpful? Give feedback.
I figured it out.
For future reference, this worked for me:
Thanks to everyone that replied!