While operating the miniature stepper motor 28BYJ-48 without a ULN2003—a dedicated motor driver chip that protects circuitry from high currents—risks damaging both the Microshield and the micro:bit, the immediate outcomes offer fascinating insights for electronics enthusiasts.
In this setup, the micro:bit logo serves as a capacitive touch button to manage the motor's state machine. An initial press triggers clockwise rotation, while a subsequent press reverses the direction to counter-clockwise following a precise 1200ms pause. Furthermore, registering a double-press in under one second acts as an immediate override to stop the motor completely.
Check out the video and accompanying code below.
let motorState = 0 // 0 = Stopped, 1 = CW, 2 = Transitioning/Pausing, 3 = CCW
let lastPressTime = 0
let currentPressTime = 0
input.onLogoEvent(TouchButtonEvent.Pressed, function () {
currentPressTime = input.runningTime()
// 1. Double-click detection (less than 1000ms apart) -> Always STOP
if (motorState != 0 && (currentPressTime - lastPressTime < 1000)) {
motorState = 0
} else {
// 2. Single-click state machine transitions
if (motorState == 0) {
motorState = 1 // From Stopped -> Go CW
} else if (motorState == 1) {
motorState = 2 // From CW -> Trigger Pause then CCW
} else if (motorState == 3) {
motorState = 1 // From CCW -> Instant reverse back to CW
}
}
lastPressTime = currentPressTime
})
basic.forever(function () {
if (motorState == 1) {
// Rotate Clockwise (CW)
microshield.Stepper(microshield.Steppers.STEP1, 30, microshield.stepUnit.Degrees)
basic.pause(10) // Small stability delay
} else if (motorState == 2) {
// The 1200ms pause sequence before CCW begins
basic.pause(1200)
// Safety check: If the user double-clicked to STOP during those 1.2 seconds,
// don't start the CCW motor. Otherwise, switch to CCW state.
if (motorState == 2) {
motorState = 3
}
} else if (motorState == 3) {
// Rotate Counter-Clockwise (CCW)
microshield.Stepper(microshield.Steppers.STEP1, -30, microshield.stepUnit.Degrees)
basic.pause(10) // Small stability delay
} else {
// motorState == 0 (Stopped)
basic.pause(100) // Idle low-power pause
}
})
Cap comentari:
Publica un comentari a l'entrada