Created
April 1, 2023 23:11
-
-
Save yvele/4f25abd2c3eaa7cdf60573a1b1129b5e to your computer and use it in GitHub Desktop.
Stepper Motor and ULN2003 Driver Board on Raspberry Pi with Node.js
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
// Inspired from: | |
// https://ben.akrin.com/driving-a-28byj-48-stepper-motor-uln2003-driver-with-a-raspberry-pi/ | |
// https://gist.github.com/wolli2710/9ae48c9f39737896c1f6 | |
const { Gpio } = require("onoff"); | |
const in1ToGpio = 17; // IN1 | |
const in2ToGpio = 18; // IN2 | |
const in3ToGpio = 27; // IN3 | |
const in4ToGpio = 22; // IN4 | |
const timeout = 1; // milliseconds | |
const antiClockWise = false; | |
const gpios = [ | |
new Gpio(in1ToGpio, "out"), | |
new Gpio(in2ToGpio, "out"), | |
new Gpio(in3ToGpio, "out"), | |
new Gpio(in4ToGpio, "out") | |
]; | |
// Make sure to clean up GPIO on exit | |
let processStepTimeoutID; | |
function exit() { | |
clearTimeout(processStepTimeoutID); | |
gpios.forEach(gpio => gpio.writeSync(0)); | |
process.exit(0); | |
} | |
process.on("SIGINT", exit); // CTRL+C | |
process.on("SIGQUIT", exit); // Keyboard quit | |
process.on("SIGTERM", exit); // `kill` command | |
// http://www.4tronix.co.uk/arduino/Stepper-Motors.php | |
// From the specification: | |
// - Reduction ratio: 1/64 | |
// - Step angle: 5.625 x 1/64 | |
// This gives 4096 steps to get a full 360° (5.625 x 1/64 per step) | |
const sequenceSteps = [ | |
[1, 0, 0, 0], | |
[1, 1, 0, 0], | |
[0, 1, 0, 0], | |
[0, 1, 1, 0], | |
[0, 0, 1, 0], | |
[0, 0, 1, 1], | |
[0, 0, 0, 1], | |
[1, 0, 0, 1] | |
]; | |
// For anti-clockwise motion, simply follow the sequence in reverse | |
if (antiClockWise) { | |
sequenceSteps.reverse(); | |
} | |
const lastStepIndex = sequenceSteps.length - 1; | |
let currentStepIndex = 0; | |
function processStep () { | |
const step = sequenceSteps[currentStepIndex]; | |
Promise.resolve([ | |
gpios[0].write(step[0]), | |
gpios[1].write(step[1]), | |
gpios[2].write(step[2]), | |
gpios[3].write(step[3]) | |
]).then(() => { | |
currentStepIndex = currentStepIndex < lastStepIndex ? currentStepIndex + 1 : 0; | |
processStepTimeoutID = setTimeout(processStep, timeout); | |
}); | |
} | |
processStep(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment