node.jswebsocketraspberry-pidistancearduino-ultra-sonic

callback error, when trying to call a function in NodeJs


I am trying to control a raspberry pi through web socket. I found a similar project and have been building my project around it. I have managed to get everything except a distance sensor working.

tank.getDistance = function () {
   async.parallel([
    gpio.write(trig,0),
    gpio.write(trig,1),
    gpio.write(trig,0),
  ]);
  var start,stop;
  while(gpio.read(echo) == 0){start = Date.now();}
  while(gpio.read(echo) == 1){stop = Date.now();}
  var distance = ((stop-start)/1000.0)*17000
  console.log("distance: "+ distance);
};

this is how i am trying to read from the ultrasonic sensor. I have tested this logic in python and it was working there.

socket.on('keydown', function (dir) {
    switch (dir) {
      case 'up':
        tank.moveForward();
        console.log("forward");
        tank.getDistance();
        break;
...

this is where i call the function. But every time I call this function, I get a

/home/pi/marinaBot/marinaBot/node_modules/rpi-gpio/rpi-gpio.js:286
            throw new Error('A callback must be provided')
            ^
Error: A callback must be provided
    at Gpio.read.input (/home/pi/marinaBot/marinaBot/node_modules/rpi-gpio/rpi-gpio.js:286:19)
    at Object.tank.getDistance (/home/pi/marinaBot/marinaBot/app.js:78:14)

not sure why this is occurring as I am not returning anything. I have tried using other ultrasonic libraries like "r-pi-usonic" but I dont understand the setup of it. Any Ideas? Just starting to learn NodeJS. this may be something realluy simple.


Solution

  • gpio.read(echo, callbackfunction(error, data){})
    

    Please check this document

    https://github.com/JamesBarwell/rpi-gpio.js#readchannel-callback


    You need async/await function for while

    var gpio = require('rpi-gpio')
    
    var gpio_read = function (channel) {
        return new Promise(resolve => {
            gpio.read(channel, function (error, result) {
                console.log('gpio.read', error, result);
                resolve(result);
            });
        });
    }
    
    var echo = 16;
    
    var calculateDistance = async function () {
        var start, stop;
    
        while (await gpio_read(echo) == false) { start = Date.now(); }
        while (await gpio_read(echo) == true) { stop = Date.now(); }
        var distance = ((stop - start) / 1000.0) * 17000
        console.log("distance: " + distance);
    }
    
    gpiop.setup(echo, gpio.DIR_IN)
        .then(function () {
            calculateDistance();
        })
        .catch((err) => {
            console.log('Error: ', err.toString())
        })
    

    Updated content:
    1. Created calculateDistance function with async as

      var calculateDistance = async function () { ... }
    
    1. return new Promise