Created
September 6, 2017 00:59
-
-
Save bcr/8f24cee4cfc33fe0aa12e56529c7fa6b to your computer and use it in GitHub Desktop.
Circuit Playground MakeCode turning test
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let current_x = 0 | |
let turning_right = 0 | |
let turning_left = 0 | |
let threshold_changed = 0 | |
let threshold_increment = 0 | |
let turning_threshold = 0 | |
input.buttonA.onEvent(ButtonEvent.Click, function () { | |
turning_threshold += threshold_increment | |
turning_threshold = Math.constrain(turning_threshold, 0, 1023) | |
threshold_changed = 1 | |
}) | |
input.buttonB.onEvent(ButtonEvent.Click, function () { | |
turning_threshold += -1 * threshold_increment | |
turning_threshold = Math.constrain(turning_threshold, 0, 1023) | |
threshold_changed = 1 | |
}) | |
loops.forever(function () { | |
if (threshold_changed) { | |
show_current_threshold() | |
loops.pause(500) | |
threshold_changed = 0 | |
serial.writeValue("turning_threshold", turning_threshold) | |
} | |
turning_left = 0 | |
turning_right = 0 | |
// Sample the current X axis accelerometer reading | |
// which will be from -1023 to 1023. | |
current_x = input.acceleration(Dimension.X) | |
serial.writeValue("current_x", current_x) | |
// Check the X accelerometer value and see if it | |
// exceeds the threshold indicating a turn, and set | |
// turning_left or turning_right as appropriate. | |
if (current_x >= turning_threshold) { | |
turning_left = 1 | |
} else { | |
if (current_x <= -1 * turning_threshold) { | |
turning_right = 1 | |
} | |
} | |
// Change LED color based on turning direction, green | |
// for left. | |
if (turning_left) { | |
light.showRing( | |
`red red red red red black black black black black` | |
) | |
} else { | |
// If turning right, make all the pixels red, if not, | |
// we must be going straight, so make all the pixels | |
// white | |
if (turning_right) { | |
light.showRing( | |
`black black black black black red red red red red` | |
) | |
} else { | |
light.pixels.setAll(Colors.Black) | |
} | |
} | |
}) | |
function show_current_threshold() { | |
light.pixels.clear() | |
// The turning threshold will now be clamped to | |
// 0-1023. Map this to one of the ten Neopixels and | |
// light it up to show the current threshold as user | |
// feedback. | |
light.pixels.setPixelColor(Math.map( | |
turning_threshold, | |
0, | |
1023, | |
0, | |
9 | |
), Colors.Yellow) | |
light.pixels.show() | |
} | |
turning_threshold = 512 | |
threshold_increment = 128 | |
threshold_changed = 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment