External button

Use an external push button

This time we’ll be blinking an LED, but only when the button is pressed.

If you try it out, you’ll see that the LED is initially off (or on), but when you press the button it’ll quickly blink. When you release the button, the blinking will stop and it will keep the last state (either on or off).

If you have one of these boards but do not have a pushbutton, you can also use a small wire to connect the given pin (D2/A2/GP2 depending on the board) and then touch a ground point, such as the outside of the USB connector.

	led := machine.LED
	led.Configure(machine.PinConfig{Mode: machine.PinOutput})

This configures the on-board LED, same as in the blink example.

	button := machine.D2 // Arduino Uno
	button.Configure(machine.PinConfig{Mode: machine.PinInputPullup})

This configures the button input. The button pin varies by board, but this time it’s always a pullup.

		// if the button is low (pressed)
		if !button.Get() {
			// ...
		}

Here we check whether the button input is low, in other words, whether it is pressed. This is a bit counter intuitive, but that’s how it is.

			// toggle the LED
			led.Set(!led.Get())

Here we use a trick to toggle the LED: we can actually read the current output value using led.Get() and then we can change the value to the opposite value using led.Set. This is equivalent to the following:

			if led.Get() {
				led.Low()
			} else {
				led.High()
			}
Loading...

Note: these numbers are estimates, based on datasheets and measurements. They don't include everything and may be wrong.

Loading...