JamesBarwell / rpi-gpio.js

Control Raspberry Pi GPIO pins with node.js
MIT License
658 stars 115 forks source link

read pins value not right #42

Closed mxyue closed 8 years ago

mxyue commented 8 years ago
var lPins = [31,33,35,37]

lPins.forEach(function(channel){
        gpio.setup(channel, gpio.DIR_IN, gpio.EDGE_NONE );
})

lPins.forEach(function(channel){
            gpio.read(channel, function(err, value) {
                    console.log(channel + 'The value is ' + value);
            });
})

I didn't do anything but the value changed

31The value is true 33The value is true 35The value is true 37The value is true

31The value is false 33The value is false 35The value is false 37The value is false

31The value is true 33The value is true 35The value is true 37The value is true

31The value is false 33The value is false 35The value is false 37The value is false

31The value is true 33The value is true 35The value is true 37The value is true

JamesBarwell commented 8 years ago

There is a problem with your code. setup is an asynchronous method, and you need to wait for it to complete before attempting to read. At the moment your code is setting up four pins, then immediately trying to read all four. There's no defined behaviour for this scenario.

I'd suggest having a look at the async node module to help with the control flow you're trying to achieve.

mxyue commented 8 years ago

@JamesBarwell thanks for your help