Skip to content

Instantly share code, notes, and snippets.

@IowaDave
Created June 21, 2018 19:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save IowaDave/989dc84b480b6efb266688828d51e47e to your computer and use it in GitHub Desktop.
Save IowaDave/989dc84b480b6efb266688828d51e47e to your computer and use it in GitHub Desktop.
Toggle Button for MakerBit and MakeCode
// **********************************************************
// Push Button Toggle Switch | MakerBit Example Code
//
// To demonstrate using code to make a simply push button
// function as a toggle switch.
//
// Target: MakeCode Javascript editor for micro:bit
//
// David Sparks June 21, 2018
// **********************************************************
//
// Declare variables
let LEDstate = 0
let ButtonState = 0
//
// Setup
pins.digitalWritePin(DigitalPin.P16, 0)
ButtonState = pins.digitalReadPin(DigitalPin.P8)
LEDstate = 0
//
// Loop
basic.forever(() => {
ButtonState = pins.digitalReadPin(DigitalPin.P8)
// Check the button state. Act only if it is LOW,
// indicating button is being pushed down.
if (ButtonState <= 0) {
// The button has been pushed down. Reverse the state
// of the LED and save the state in a variable.
if (LEDstate == 0) {
LEDstate = 1
pins.digitalWritePin(DigitalPin.P16, 1)
} else {
LEDstate = 0
pins.digitalWritePin(DigitalPin.P16, 0)
}
// Wait for button to be released.
while (ButtonState <= 0) {
ButtonState = pins.digitalReadPin(DigitalPin.P8)
}
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment