Skip to content

Instantly share code, notes, and snippets.

@poulou0
Last active September 23, 2022 07:35
Show Gist options
  • Save poulou0/a20c61d41f6f5b787caab4bd10cdf13b to your computer and use it in GitHub Desktop.
Save poulou0/a20c61d41f6f5b787caab4bd10cdf13b to your computer and use it in GitHub Desktop.
Node.js `pigpio` + two servos

Node.js (pigpio) + two servos

Requirements

  • sudo npm install -g pigpio

Use

cd ~ && \
git clone https://gist.github.com/poulou0/a20c61d41f6f5b787caab4bd10cdf13b pigpio-servos && \
cd pigpio-servos && \
sudo node servos.js
#!/usr/bin/env node
process.env.NODE_PATH = "/usr/lib/node_modules";
require("module").Module._initPaths();
const Gpio = require('pigpio').Gpio;
const stdin = process.stdin;
stdin.setRawMode( true );
stdin.resume();
stdin.setEncoding( 'utf8' );
const motorX = new Gpio(14, {mode: Gpio.OUTPUT});
const motorY = new Gpio(15, {mode: Gpio.OUTPUT});
let motorXpulseMax = 1750,
motorYpulseMax = 2500,
motorXpulseMin = 500,
motorYpulseMin = 500,
motorXpulseCurrent = 1125,
motorYpulseCurrent = 1500,
motorXpulseTarget = 1125,
motorYpulseTarget = 1500,
step = 150
smoothMovement = true;
setInterval(() => {
if (!smoothMovement) motorXpulseCurrent = motorXpulseTarget
else if (motorXpulseCurrent < motorXpulseTarget) motorXpulseCurrent += 1;
else if (motorXpulseCurrent > motorXpulseTarget) motorXpulseCurrent -= 1;
if (motorXpulseCurrent > motorXpulseMax) motorXpulseCurrent = motorXpulseMax;
else if (motorXpulseCurrent < motorXpulseMin) motorXpulseCurrent = motorXpulseMin;
motorX.servoWrite(motorXpulseCurrent);
if (!smoothMovement) motorYpulseCurrent = motorYpulseTarget;
else if(motorYpulseCurrent < motorYpulseTarget) motorYpulseCurrent += 1;
else if (motorYpulseCurrent > motorYpulseTarget) motorYpulseCurrent -= 1;
if (motorYpulseCurrent > motorYpulseMax) motorYpulseCurrent = motorYpulseMax;
else if (motorYpulseCurrent < motorYpulseMin) motorYpulseCurrent = motorYpulseMin;
motorY.servoWrite(motorYpulseCurrent);
}, 4);
(async () => {
motorX.servoWrite(motorXpulseCurrent);
motorY.servoWrite(motorYpulseCurrent);
stdin.on( 'data', function( key ) {
if ( key === '\u0003' ) { // ctrl-c ( end of text )
process.exit();
} else if ( key === '\033[D' ) { //left, Y+
motorYpulseTarget = motorYpulseCurrent + step;
} else if ( key === '\033[C' ) { //right, Y-
motorYpulseTarget = motorYpulseCurrent - step;
} else if ( key === '\033[A' ) { //up, X+
motorXpulseTarget = motorXpulseCurrent + step;
} else if ( key === '\033[B' ) { //down, X-
motorXpulseTarget = motorXpulseCurrent - step;
} else if ( key === '\u0020' ) { //space
smoothMovement = !smoothMovement;
}
// write the key to stdout all normal like
// process.stdout.write( key );
});
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment