I wired the sensor to my Raspberry Pi. My aim is to use JavaScript to get a live reading in the console of the distance, but the module I found has been archived by the author.

Code that I found on GitHub like this repo and this repo, all depend on that module, so they don't work as well.

However! I found Pigpio so on the console I ran:

npm install pigpio

Then I created a new file, inserted the following code:

const Gpio = require('pigpio').Gpio;

// The number of microseconds it takes sound to travel 1cm at 20 degrees celcius
const MICROSECDONDS_PER_CM = 1e6/34321;

const trigger = new Gpio(23, {mode: Gpio.OUTPUT});
const echo = new Gpio(24, {mode: Gpio.INPUT, alert: true});

trigger.digitalWrite(0); // Make sure trigger is low

const watchHCSR04 = () => {
  let startTick;

  echo.on('alert', (level, tick) => {
    if (level == 1) {
      startTick = tick;
    } else {
      const endTick = tick;
      const diff = (endTick >> 0) - (startTick >> 0); // Unsigned 32 bit arithmetic
      console.log(diff / 2 / MICROSECDONDS_PER_CM);


// Trigger a distance measurement once per second
setInterval(() => {
  trigger.trigger(10, 1); // Set trigger high for 10 microseconds
}, 1000);

and I ran:

sudo node distance-sensor.js

Which prompted me with an error:

2020-02-10 11:30:23 initInitialise: Can't lock /var/run/pigpio.pid

Error: pigpio error -1 in gpioInitialise
    at initializePigpio (/home/pi/node_modules/pigpio/pigpio.js:17:12)
    at new Gpio (/home/pi/node_modules/pigpio/pigpio.js:121:5)
    at Object.<anonymous> (/home/pi/distance-sensor.js:6:17)
    at Module._compile (module.js:653:30)
    at Object.Module._extensions..js (module.js:664:10)
    at Module.load (module.js:566:32)
    at tryModuleLoad (module.js:506:12)
    at Function.Module._load (module.js:498:3)
    at Function.Module.runMain (module.js:694:10)
    at startup (bootstrap_node.js:204:16)

and I have absolutely no idea what that means and how to fix it.

I have tried running:

sudo killall pigpiod

and then again:

sudo node distance-sensor.js

but that didn't solve the problem.

What can I do from here?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.