EMS/drv/drv_do.c

164 lines
3.4 KiB
C
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include "drv_do.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <errno.h>
// 设置GPIO引脚为输出模式
int gpio_export(int gpio_num) {
int fd;
char buf[64];
// 导出GPIO写入对应的GPIO编号
fd = open(GPIO_PATH "/export", O_WRONLY);
if (fd == -1) {
perror("Failed to open export file");
return -1;
}
snprintf(buf, sizeof(buf), "%d", gpio_num);
if (write(fd, buf, strlen(buf)) == -1) {
perror("Failed to export GPIO");
close(fd);
return -1;
}
close(fd);
return 0;
}
// 设置GPIO引脚方向
int gpio_set_direction(int gpio_num, const char *direction) {
int fd;
char buf[64];
// 设置GPIO方向
snprintf(buf, sizeof(buf), GPIO_PATH "/gpio%d/direction", gpio_num);
fd = open(buf, O_WRONLY);
if (fd == -1) {
perror("Failed to open GPIO direction file");
return -1;
}
if (write(fd, direction, strlen(direction)) == -1) {
perror("Failed to set GPIO direction");
close(fd);
return -1;
}
close(fd);
return 0;
}
// 读取GPIO引脚值
int gpio_read_value(int gpio_num) {
int fd;
char buf[64];
char value;
// 打开GPIO值文件
snprintf(buf, sizeof(buf), GPIO_PATH "/gpio%d/value", gpio_num);
fd = open(buf, O_RDONLY);
if (fd == -1) {
perror("Failed to open GPIO value file");
return -1;
}
// 读取GPIO值
if (read(fd, &value, 1) == -1) {
perror("Failed to read GPIO value");
close(fd);
return -1;
}
close(fd);
return (value == '1') ? 1 : 0;
}
// 设置GPIO引脚值
int gpio_write_value(int gpio_num, int value) {
int fd;
char buf[64];
// 打开GPIO值文件
snprintf(buf, sizeof(buf), GPIO_PATH "/gpio%d/value", gpio_num);
fd = open(buf, O_WRONLY);
if (fd == -1) {
perror("Failed to open GPIO value file");
return -1;
}
// 写入GPIO值
if (write(fd, (value ? "1" : "0"), 1) == -1) {
perror("Failed to write GPIO value");
close(fd);
return -1;
}
close(fd);
return 0;
}
// 取消导出GPIO
int gpio_unexport(int gpio_num) {
int fd;
char buf[64];
// 取消导出GPIO
fd = open(GPIO_PATH "/unexport", O_WRONLY);
if (fd == -1) {
perror("Failed to open unexport file");
return -1;
}
snprintf(buf, sizeof(buf), "%d", gpio_num);
if (write(fd, buf, strlen(buf)) == -1) {
perror("Failed to unexport GPIO");
close(fd);
return -1;
}
close(fd);
return 0;
}
void do_open()
{
int gpio_num = 24; // 需要操作的GPIO引脚编号
// 导出GPIO
if (gpio_export(gpio_num) == -1) {
return -1;
}
// 设置GPIO为输出模式
if (gpio_set_direction(gpio_num, "out") == -1) {
gpio_unexport(gpio_num);
return -1;
}
// 设置GPIO值为1 (高电平)
if (gpio_write_value(gpio_num, 1) == -1) {
gpio_unexport(gpio_num);
return -1;
}
// 读取GPIO值
int value = gpio_read_value(gpio_num);
if (value != -1) {
printf("GPIO %d value: %d\n", gpio_num, value);
}
// 设置GPIO值为0 (低电平)
if (gpio_write_value(gpio_num, 0) == -1) {
gpio_unexport(gpio_num);
return -1;
}
}