Question

I've been looking at some node.js gpio libraries, and though I really like onoff, I don't want to be reliant on an installed python version (and it fails on my laptop because I've got python 3.3.2), so I'm looking at writing my own gpio library.

The basic idea of GPIO seems to simply be reading and writing to the specific GPIO file, and I'm guessing the operating system is looking for changes, or can make changes to that file.

All the libraries I see have a 'direction', but I'm thinking this seems a bit of overkill to me. If I am reading a value, my direction is 'out', if I'm writing to a file, my direction is 'in'. Is there some other reason that these are separated out in most of the libraries?

example from pi-gpio, which is a very simple library https://github.com/rakeshpai/pi-gpio/blob/master/pi-gpio.js

gpio.open(16, "output", function(err) {     // Open pin 16 for output
    gpio.write(16, 1, function() {          // Set pin 16 high (1)
        gpio.close(16);                     // Close pin 16
    });
});

and the open method in the library is

open: function(pinNumber, direction, callback) {
        pinNumber = sanitizePinNumber(pinNumber);

        if(!callback && typeof direction === "function") {
            callback = direction;
            direction = "out";
        }

        direction = sanitizeDirection(direction);

        exec(gpioAdmin + " export " + pinMapping[pinNumber], handleExecResponse("open", pinNumber, function(err) {
            if(err) return (callback || noop)(err);

            gpio.setDirection(pinNumber, direction, callback);
        }));
    },
Was it helpful?

Solution

If you dig down through all the layers of abstraction, you'll see that many microprocessor / SoC devices expose GPIO through (at least) two hardware registers:

  • Data register
  • Direction register

The data register is of course what you read/write to get a value from an input pin, or change the value of an output pin.

The direction register controls whether a pin is an input or an output (or both). This affects the internal buffering / output driver circuitry associated with that pin.

For example, a GPIO pin configured for "input" (or reading) will be in a high-impedance (high-Z) state, so it presents little to no load to the connected circuitry. On the other hand, an output pin will usually be pulled to either Vcc or GND.

What you're seeing is this necessary direction register being abstracted all the way up to the Javascript level, where it seemingly makes no sense. As the electrical engineers, however. It is necessary.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top