Page 1 of 1

Connecting external grove button to Microbit

Posted: Thu Nov 19, 2020 2:40 am
by amberxoxo
Hi! Can someone please help me - I'm trying to connect an external grove button to the microbit. How can I code it in python to get it to work so that when you press it once, the neopixels glow a white light and then if you press it again it turns off? Thanks

Re: Connecting external grove button to Microbit

Posted: Thu Nov 19, 2020 10:45 pm
by jimmo
amberxoxo wrote:
Thu Nov 19, 2020 2:40 am
I'm trying to connect an external grove button to the microbit. How can I code it in python to get it to work so that when you press it once, the neopixels glow a white light and then if you press it again it turns off?
The simplest way to do this is if you're not also using the onboard "A" and "B" buttons, then if you connect it to pins 5 or 11, then you can make the external button behave as A or B. See the pinout here:
https://os.mbed.com/platforms/Microbit/

Then in Python you can use button_a.was_pressed() etc.

Otherwise, you can use any pin and access it as a digital pin. pinN.read_digital() to read the current state of the pin. Ideally what you do is in a loop you record the current value of the pin and detect a change from 0 to 1.

Code: Select all

neopixels_on = False
last_state = 0
while True:
  new_state = pinN.read_digital()
  if new_state == 1 and last_state == 0:
    if neopixels_on:
      # Turn them off
      neopixels_on = False
    else:
      # Turn them on
      neopixels_on = True
  last_state = new_state
This will use an internal pull-down resistor, but you might need to change it to pull-up depending on the way the grove module works. https://microbit-micropython.readthedoc ... 1/pin.html