Search code examples
cfile-ioembedded-linuxfile-descriptor

Weird thing in file-descrpiter I/O for gpio port


I'm coding in Linux to control the gpio port on my board, using the following codes. However,the result from read() is always a 0x10, which is a hex for LF line feed. Voltage is an enum variable having int value of 0 and 1 standing for low and high. fd is the file descripter for the gpio port. 0x30 is hex code for char '0'. There is no error in write().

int set_gpio( int fd,enum voltage_e voltage)
{
    const unsigned char w_buff =0x30+voltage;
    unsigned char r_buff='2';

    if (0 >= write(fd, &w_buff, 1))
    {
        LOGD(" Error1 in setting gpio to  %d", voltage);
        return -1;
    }
    __usr_sleep(0, 10000000);

    if (read(fd, &r_buff, 1))
    {
        if (r_buff != 0x30+voltage)
        {
            LOGD(" r_buff is %d", r_buff);
            return -1;
        }
    }
    else
    {
        LOGD(" Error3 in setting gpio to %d", voltage);
        return -1;
    }
    return 0;
}

Solution

  • For compatibility with shell utilities, the content of a GPIO port is typically a single character followed by a newline -- for instance:

    % xxd /sys/class/gpio/gpio89/value
    0000000: 310a                                     1.
    

    Writing a single character to the GPIO device is advancing the file pointer to the second character, which is always the newline which you're seeing.

    You will need to reset the file pointer to the beginning before doing a read/write operation:

    lseek(fd, 0, SEEK_SET);