Linux:设置和获取单片机gpio引脚和key值

目录

1、设置gpio引脚的值

2、获取gpio引脚的值

3、获取主控板上key的值


1、设置gpio引脚的值

/*

* 输出IO:

* echo 300 > /sys/class/gpio/export //将编号为 300 的 GPIO 引脚"导出"到用户空间

* echo out > /sys/class/gpio/gpio300/direction //将已导出的 GPIO 300 设置为"输出模式"

* echo in > /sys/class/gpio/gpio300/direction //将已导出的 GPIO 300 设置为"输入模式"

* echo 1 > /sys/class/gpio/gpio300/value (#设置gpio 300 为高)

* echo 0 > /sys/class/gpio/gpio300/value (#设置gpio 300 为低)

*/

以上的命令是通过 Linux 系统的 ​sysfs 接口​ 控制 GPIO(通用输入输出)引脚的操作,常见于嵌入式开发或树莓派等单板机。

标准的 GPIO 初始化流程:导出引脚 → 设置为输出/输入模式,再进行赋值。

cpp 复制代码
void fun()
{
    QString strEcho = QString("echo 1 > /sys/class/gpio/gpio300/value");
    
    int ret = system(strEcho.toLocal8Bit().data());
    
    if(0==ret)
        qDebug("成功");
}

2、获取gpio引脚的值

/*

* 读取IO:

* echo 400 > /sys/class/gpio/export

* echo in > /sys/class/gpio/gpio400/direction

* cat /sys/class/gpio/gpio400/value (#读取gpio 400)

*/

(1)第一种方式:FILE

cpp 复制代码
void fun1()
{
    QString strEcho = QString("cat /sys/class/gpio/gpio400/value");
    FILE* fp = nullptr;
    char result[512]={0};
    QString strRet = "";
    if ((fp = popen(strEcho.toLocal8Bit().data(), "r")) != nullptr)
    {
        fgets(result, sizeof(result), fp);
        pclose(fp);

        if(result[0]=='0') strRet = "1";
        else strRet = "0";
    }
}

(2)第二种方式:Qfile

cpp 复制代码
bool readGpioValue(QString gpioNumber, )
{
    QString value;

    // 构造GPIO值文件路径
    QString path = QString("/sys/class/gpio/gpio%1/value").arg(gpioNumber);

    QFile file(path);
    if (!file.open(QIODevice::ReadOnly)) {
        qDebug() << "Failed to open GPIO value file:" << path;
        return false;
    }

    QByteArray data = file.readAll();
    value = QString(data).trimmed();
    file.close();

    return true;
}

3、获取主控板上key的值

在 Linux 系统中通过 ​输入子系统(Input Subsystem)​​ 读取按键事件的典型操作。

(1)/dev/input/event1是什么?

  • ​Linux 输入子系统​:

    Linux 将所有输入设备(键盘、鼠标、触摸屏、GPIO 按键等)抽象为统一的输入事件接口,设备文件位于 /dev/input/目录下。

  • ​**eventX设备文件**​:

    event0, event1, event2... 代表不同的输入设备通道(按检测顺序编号)。

    • event1通常是系统中的第二个输入设备 ​(第一个是 event0)。

    • 具体对应哪个物理设备,可通过命令查看:

bash 复制代码
cat /proc/bus/input/devices  # 列出所有输入设备及对应的 event 节点

(2)Key 事件" 的具体含义

当成功打开 event1后,程序可以通过 read(keys_fd, ...)从该设备读取原始输入事件数据。这些事件遵循 Linux 的 ​**input_event结构体** ​(定义于 <linux/input.h>):

cpp 复制代码
struct input_event {
    struct timeval time;  // 事件触发的时间戳
    __u16 type;           // 事件类型(如 EV_KEY=按键, EV_SW=开关)
    __u16 code;           // 按键编码(如 KEY_A=按键A, KEY_POWER=电源键)
    __s32 value;          // 值(0=释放, 1=按下, 2=长按重复)
};

常见事件类型

类型宏 值 说明
EV_KEY 0x01 ​按键事件​(最常用)
EV_REL 0x02 相对位移(如鼠标移动)
EV_ABS 0x03 绝对坐标(如触摸屏点击)
EV_SYN 0x00 同步事件(数据包结束)

典型应用场景

  1. 嵌入式设备按键监听​

    例如:通过 GPIO 连接的物理按钮(如复位键、用户按键)。

  2. ​自定义键盘/遥控器​

    处理红外遥控、矩阵键盘等非标准输入设备。

  3. ​系统级按键捕获​

    拦截电源键、音量键等特殊功能键。

(3)代码演示

第一个例子

cpp 复制代码
#include <linux/input.h>
#include <fcntl.h>
#include <unistd.h>

int main() {
    int fd = open("/dev/input/event1", O_RDONLY);
    struct input_event ev;

    while (read(fd, &ev, sizeof(ev)) == sizeof(ev)) {
        if (ev.type == EV_KEY && ev.value == 1) {  // 按键按下事件
            printf("按键按下: code=%d\n", ev.code);
            // 根据 ev.code 执行对应操作(如 KEY_VOLUMEUP=115)
        }
    }
    close(fd);
    return 0;
}

这段代码的核心目的是打开一个输入设备(/dev/input/event1)以监听按键事件 。它是 Linux 下处理硬件按键的标准方法,常见于嵌入式开发、自定义外设交互等场景。后续需通过 read()读取 input_event结构体数据,并根据 code和 value解析具体按键动作。

第二个例子:

cpp 复制代码
#include <linux/input.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <cstring>

static void* createThread(void *arg);

void fun()
{
    pthread_t *tid1 = nullptr;
    if (tid1 == nullptr)
    {
        tid1 = new pthread_t;
        pthread_create(tid1, NULL, createThread, DevMananger::instance());
    }
}

void* DevMananger::createThread(void *arg)
{
    DevMananger *p = (DevMananger *)arg;
    qDebug("createThread sucess ");
	
	qint64 startpushtime, endpushtime, dotime;
    while(true)
    {
        struct input_event ev;
        keys_fd = open("/dev/input/event1", O_RDONLY);
        qDebug("open /dev/input/event1 device65 \n");

        if (keys_fd <= 0)
        {
            qDebug("open /dev/input/event device error!\n");
            continue;
        }

        if (read(keys_fd, &ev, sizeof(ev)) == sizeof(ev))
        {
            qDebug("key %d %s\n", ev.code, (ev.value) ? "Pressed" : "Released");
            switch (ev.code)
            {
            case 148:
                qDebug("上工位按下按键");
                startpushtime = getCurrentMsec();
                qDebug() << startpushtime - endpushtime;
                if((startpushtime - endpushtime) > (400 + dotime))
                {
                    p->sendPushMessage("1",1);
                    endpushtime = getCurrentMsec();
                    dotime = 0;
                }
                else
                {
                    dotime = dotime + 50;
                }
                break;
            case 202:
                qDebug("下工位按下按键");
                startpushtime = QDateTime::currentMSecsSinceEpoch();
                qDebug() << startpushtime - endpushtime;
                if((startpushtime - endpushtime)> 400 + dotime)
                {
                    p->sendPushMessage("2",1);
                    endpushtime = QDateTime::currentMSecsSinceEpoch();
                    dotime = 0;
                }
                else
                {    dotime = dotime + 50;
                }
                break;
            default:
                break;;
            }
        }
        close(keys_fd);
        usleep(10000);
    }
}

这段代码是在 Linux 系统中通过 ​输入子系统(Input Subsystem)​ ​ 读取按键事件的典型操作。具体来说,它打开了 /dev/input/event1设备文件,用于监听和处理硬件按键事件(如键盘、GPIO 按键等)

相关推荐
Ivanqhz17 小时前
激活函数在 Transformer 中的作用及各种变体简述
java·linux·数据库·人工智能·深度学习
殷色玫瑰19 小时前
C/C++ 内存管理详解:从内存分布到 new/delete 底层原理
java·linux·c语言·c++
C++ 老炮儿的技术栈20 小时前
main函数之后的调用
c语言·c++·人工智能·qt·mfc·c
꯭自꯭闭꯭20 小时前
DM7主备升级方案
linux·服务器·数据库
用户41071920132520 小时前
VMware 虚拟机Ubuntu 环境linux远程连接失败
linux
lisanmengmeng21 小时前
Nagios邮件报警的配置
linux·运维·服务器
Ruiery21 小时前
Linux 6.6内核 CPU 深度解析(六):cpufreq
linux·运维·服务器
倔强的石头10621 小时前
【Linux指南】动静态库系列(十一):PLT 与延迟绑定:第一次调用动态库函数时发生了什么
linux·人工智能·python
硅基手札1 天前
【linux内核专栏 08】时间与定时器
linux·运维·服务器
想做小南娘,发现自己是女生喵1 天前
Linux之Ubuntu入门篇知识总结
linux·运维·服务器