I am struggling to read back the value of a pin that I set before.
Is this even possible? (It is using sysfs!)
I have this code:
#include <gpiod.h> // gpiod_line_set_value, gpiod_line_get_value
#include <stdio.h>
// Open gpio device and read/write gpio pin
const char CHIP[] = "/dev/gpiochip1";
const int LINE = 3; // EN_FAN
// if arg 1 is 0/1, write to gpio pin else read from gpio pin
int main(int argc, char* argv[])
{
struct gpiod_chip* chip;
struct gpiod_line* line;
int val;
chip = gpiod_chip_open(CHIP);
if (!chip)
{
perror("Open chip failed");
return 1;
}
line = gpiod_chip_get_line(chip, LINE);
if (!line)
{
perror("Get line failed");
gpiod_chip_close(chip);
return 1;
}
if (argc == 2) // write
{
val = atoi(argv[1]);
if (gpiod_line_request_output(line, "gpiot", val))
{
perror("Request line as output failed");
gpiod_line_release(line);
gpiod_chip_close(chip);
return 1;
}
// No need to set. Default value in request_output is applied.
val = gpiod_line_get_value(line);
if (val == 0 || val == 1)
{
printf("Line value: %dn", val);
}
else
{
perror("Get line value failed");
gpiod_line_release(line);
gpiod_chip_close(chip);
return 1;
}
}
else // read
{
if (gpiod_line_request_input(line, "gpiot"))
{
perror("Request line as input failed");
gpiod_line_release(line);
gpiod_chip_close(chip);
return 1;
}
val = gpiod_line_get_value(line);
if (val < 0)
{
perror("Get line value failed");
gpiod_line_release(line);
gpiod_chip_close(chip);
return 1;
}
printf("Line value: %dn", val);
}
gpiod_line_release(line);
gpiod_chip_close(chip);
return 0;
}
I have a gpiod_line_get_value() right after gpiod_line_request_output(). It always reads 0 regardless of what the pin is set to. (Setting the pin works, I can see the fan running).
Opening the pin in input mode (no argument to executable, gpiod_line_request_input) resets the pin. The fan no longer runs.
Additional question: Using gpiod_line_request_output
instead of gpiod_line_request_output_flags
used default flags (no bit set). This means it keeps the flags from before, right? The settings that were set from the kernel/device tree.
1