Search code examples
embedded-linuxvalagpio

How to control embedded-linux gpio?


The following shell commands toggle Leopardboard gpio 31 just fine:

echo 31 > /sys/class/gpio/export
echo out > /sys/class/gpio/gpio31/direction
echo 0 > /sys/class/gpio/gpio31/value
echo 1 > /sys/class/gpio/gpio31/value
echo 0 > /sys/class/gpio/gpio31/value

This is used as an example for the code below. Any idea why the following .vala code does not toggle gpio 31 out?

public void sync () {
    int fd = -1;
    fd = open("/sys/class/gpio/export", O_WRONLY);
    if (fd < 0) {
        GLib.stdout.printf("Error sync export\n");
        return;
    }
    write(fd, "31", 3);
    close(fd);
    fd = open("/sys/class/gpio/gpio31/direction", O_WRONLY);
    if (fd < 0) {
        GLib.stdout.printf("Error sync direction\n");
        return;
    }
    write(fd, "out", 4);
    close(fd);
    fd = open("/sys/class/gpio/gpio31/value", O_WRONLY);
    if (fd < 0) {
        GLib.stdout.printf("Error sync value\n");
        return;
    }
    write(fd, "0", 2);
    write(fd, "1", 2);
    Thread.usleep (1000); /* 1ms */
    write(fd, "0", 2);
    close(fd);
}

Solution

  • echo 31 will actually result in \x33\x31\x0a, but your write call will write \x33\x31\x00. Try something like this:

    write(fd, "31\n", 3);
    

    And you'll want to make similar adjustments to the other calls to write.