How to use GPIO signals

本文详细介绍如何在 Linux 系统中配置和使用 GPIO 接口,包括内核配置、导出 GPIO 到用户空间、设置输入输出方向、配置中断源等步骤,并提供了 C 语言示例代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原文地址:http://blog.youkuaiyun.com/drivermonkey/article/details/20132241


References

http://www.avrfreaks.net/wiki/index.php/Documentation:Linux/GPIO

GPIO Usage from a Linux Application

Overview

The following table summarizes the steps to configuring and using GPIO signals from a Linux application.

Step NumberActionDescription
1Configure the kernel for GPIO support in sysfsAllow GPIO configuration and control from Linux applications (user space). The GPIO shoulw up in the system file system, sysfs, at /sys/class/gpio
2Export GPIO to user spaceEach GPIO is are not accessible from user space until the GPIO has been exported. You can only export a GPIO that isn’t owned by a Linux kernel driver
3Configure GPIO for input or outputTo avoid hardware issues where two devices are driving the same signal, GPIOs default to be configured as an input. If you want to use the GPIO as an output, you need to change the configuration
4Configure GPIO an an interrupt sourceIf you have a GPIO that is an input, and you have an application you want to block waiting for the GPIO to change level, you can configure the GPIO as an interrupt source. You also need to configure if the interrupt occurs when the GPIO signal has a rising edge, a falling edge, or interrupts on both rising and falling edges. Once configured as an interrupt, your application can read the value file and the read will block until the interrupt occurs, then your application will return from the read system call and continue running.

The sysfs directory /sys/class/gpio contains subdirectories and files that are used for configuring and using GPIO signals from a Linux application.

Configure the kernel for GPIO support in sysfs

Symbol: GPIO_SYSFS [=y]
  Prompt: /sys/class/gpio/... (sysfs interface)
    Defined at drivers/gpio/Kconfig:51
    Depends on: GPIOLIB && SYSFS && EXPERIMENTAL
     Location:
      -> Kernel configuration
        -> Device Drivers
         -> GPIO Support (GPIOLIB [=y])

Enable GPIO access from user space

GPIO=22

cd /sys/class/gpio
ls
echo $GPIO > export
ls

Notice on the first ls that gpio22 doesn’t exist, but does after you export GPIO 22 to user space.

cd /sys/class/gpio/gpio$GPIO
ls

There are files to set the direction and retrieve the current value.

echo "in" > direction
cat value

You can configure the GPIO for output and set the value as well.

echo "out" > direction
echo 1 > value

GPIO interrupts from user space

Reference

http://bec-systems.com/site/281/how-to-implement-an-interrupt-driven-gpio-input-in-linux
http://www.spinics.net/lists/linux-newbie/msg01028.html
elinux.org/images/d/d4/Celf-gpio.odp
http://docs.blackfin.uclinux.org/doku.php?id=linux-kernel:drivers:gpio-sysfs

LeopoardBoard 365 GPIO 0 connection

On the LeopardBoard 365, the only GPIO I could find that was usable for interrupt input is GPIO0, also called CMOS_TRIGGER in the schematics. In looking at the schematics resistor R12 is not loaded and one of the pads connects to CMOS_TRIGGER. This R12 pad is the one closest to R11. If you hold the leopardboard 365 with the SD card slot facing you and rotate the board until the SD card slot is on the bottom edge, the the R12 pads are to the right of J6 and to the left of the SD card slot upper left corner.
这里写图片描述

Using poll() to monitor for GPIO 0 change

The gpio-int-test.c program (or gpiopin.cpp for those who prefer C++) shows one way of using the sysfs file /sys/class/gpio/gpio0/value to block program execution using poll() until the input level on GPIO0 changes. The tricky part was figuring out to use POLLPRI instead of POLLIN as the event to monitor. You must have GPIO support in sysfs for this program to work (or you will not see the /sys/class/gpio directory).

The gpio-int-test.c program uses poll() to wake up every 3 seconds (using poll() timeout mechanism) at which time it prints a period. The poll() function is also watching for input from stdin and for an interrupt from GPIO 0.

Here is an example output. I started gpio-int to watch GPIO 0. I waited around 12 seconds (4 timeout periods), then pressed the letter ‘a’ twice followed by enter key. Then I shorted the haywire to 3.3V that is accessible on pin 5 on the JTAG connector. JTAG pin 5 is across from the JTAG missing pin). I exited the program using cntl-C.

/root # gpio-int 0 

....aa

poll() stdin read 0xA61

poll() stdin read 0xA61

poll() stdin read 0xA0A
..
poll() GPIO 0 interrupt occurred (len 0)

poll() GPIO 0 interrupt occurred (len 0)

poll() GPIO 0 interrupt occurred (len 0)

poll() GPIO 0 interrupt occurred (len 0)
..^C

Viewing GPIO Configuration

You can use debugfs to videw the current GPIO configuration. You may also be able to use debugfs to see if the GPIO pin is multiplex as a GPIO or is dedicated to some other function.

Configure the kernel to enable debugfs:

Symbol: DEBUG_FS [=y]
   Prompt: Debug Filesystem
     Defined at lib/Kconfig.debug:77
     Depends on: SYSFS     
     Location:
       -> Kernel configuration
         -> Kernel hacking         

Boot the target hardware and mount debugfs:

mount -t debugfs none /sys/kernel/debug

Dump the GPIO configuration.

cat /sys/kernel/debug/gpio

Dump the pin multiplexing configuration.

cat /sys/kernel/debug/omap_mux/board      # for OMAP
cat /sys/kernel/debug/dm365_mux           # for DM36x

Example shell script making it easy to set GPIOs from the command line

If you want to have a simple way to control a GPIO signal from the Linux command line, try the gpio.sh script below.

For examaple, if you want to read the value of GPIO 72 without setting its direction, try

gpio.sh 72

If you want to force GPIO 35 to be in input and read the current value, try

gpio.sh 35 in

If you want to configure GPIO 4 to be an output and set the value high, try

gpio.sh 4 out 1

For the script below to work, you need to first make sure you have build busybox with printf enabled.

#!bin/sh

show_usage()
{
    printf "\ngpio.sh <gpio pin number> [in|out [<value>]]\n"
}

if [ \( $# -eq 0 \) -o \( $# -gt 3 \) ] ; then
    show_usage
    printf "\n\nERROR: incorrect number of parameters\n"
    exit 255
fi

#doesn't hurt to export a gpio more than once
echo $1 > /sys/class/gpio/export

if [  $# -eq 1 ] ; then
   cat /sys/class/gpio/gpio$1/value
   exit 0
fi

if [ \( "$2" != "in" \) -a  \( "$2" != "out" \) ] ; then
    show_usage
    printf "\n\nERROR: second parameter must be 'in' or 'out'\n"
    exit 255
fi

echo $2 > /sys/class/gpio/gpio$1/direction

if [  $# -eq 2 ] ; then
   cat /sys/class/gpio/gpio$1/value
   exit 0
fi


VAL=$3

if [ $VAL -ne 0 ] ; then
    VAL=1
fi

echo $VAL > /sys/class/gpio/gpio$1/value

以下是C语言测试代码:

/* Copyright (c) 2011, RidgeRun 
 * All rights reserved. 
 *  
 * Redistribution and use in source and binary forms, with or without 
 * modification, are permitted provided that the following conditions are met: 
 * 1. Redistributions of source code must retain the above copyright 
 *    notice, this list of conditions and the following disclaimer. 
 * 2. Redistributions in binary form must reproduce the above copyright 
 *    notice, this list of conditions and the following disclaimer in the 
 *    documentation and/or other materials provided with the distribution. 
 * 3. All advertising materials mentioning features or use of this software 
 *    must display the following acknowledgement: 
 *    This product includes software developed by the RidgeRun. 
 * 4. Neither the name of the RidgeRun nor the 
 *    names of its contributors may be used to endorse or promote products 
 *    derived from this software without specific prior written permission. 
 *  
 * THIS SOFTWARE IS PROVIDED BY RIDGERUN ''AS IS'' AND ANY 
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 
 * DISCLAIMED. IN NO EVENT SHALL RIDGERUN BE LIABLE FOR ANY 
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
 */  

#include <stdio.h>  
#include <stdlib.h>  
#include <string.h>  
#include <errno.h>  
#include <unistd.h>  
#include <fcntl.h>  
#include <poll.h>  

 /**************************************************************** 
 * Constants 
 ****************************************************************/  

#define SYSFS_GPIO_DIR "/sys/class/gpio"  
#define POLL_TIMEOUT (3 * 1000) /* 3 seconds */  
#define MAX_BUF 64  

/**************************************************************** 
 * gpio_export 
 ****************************************************************/  
int gpio_export(unsigned int gpio)  
{  
    int fd, len;  
    char buf[MAX_BUF];  

    fd = open(SYSFS_GPIO_DIR "/export", O_WRONLY);  
    if (fd < 0) {  
        perror("gpio/export");  
        return fd;  
    }  

    len = snprintf(buf, sizeof(buf), "%d", gpio);  
    write(fd, buf, len);  
    close(fd);  

    return 0;  
}  

/**************************************************************** 
 * gpio_unexport 
 ****************************************************************/  
int gpio_unexport(unsigned int gpio)  
{  
    int fd, len;  
    char buf[MAX_BUF];  

    fd = open(SYSFS_GPIO_DIR "/unexport", O_WRONLY);  
    if (fd < 0) {  
        perror("gpio/export");  
        return fd;  
    }  

    len = snprintf(buf, sizeof(buf), "%d", gpio);  
    write(fd, buf, len);  
    close(fd);  
    return 0;  
}  

/**************************************************************** 
 * gpio_set_dir 
 ****************************************************************/  
int gpio_set_dir(unsigned int gpio, unsigned int out_flag)  
{  
    int fd, len;  
    char buf[MAX_BUF];  

    len = snprintf(buf, sizeof(buf), SYSFS_GPIO_DIR  "/gpio%d/direction", gpio);  

    fd = open(buf, O_WRONLY);  
    if (fd < 0) {  
        perror("gpio/direction");  
        return fd;  
    }  

    if (out_flag)  
        write(fd, "out", 4);  
    else  
        write(fd, "in", 3);  

    close(fd);  
    return 0;  
}  

/**************************************************************** 
 * gpio_set_value 
 ****************************************************************/  
int gpio_set_value(unsigned int gpio, unsigned int value)  
{  
    int fd, len;  
    char buf[MAX_BUF];  

    len = snprintf(buf, sizeof(buf), SYSFS_GPIO_DIR "/gpio%d/value", gpio);  

    fd = open(buf, O_WRONLY);  
    if (fd < 0) {  
        perror("gpio/set-value");  
        return fd;  
    }  

    if (value)  
        write(fd, "1", 2);  
    else  
        write(fd, "0", 2);  

    close(fd);  
    return 0;  
}  

/**************************************************************** 
 * gpio_get_value 
 ****************************************************************/  
int gpio_get_value(unsigned int gpio, unsigned int *value)  
{  
    int fd, len;  
    char buf[MAX_BUF];  
    char ch;  

    len = snprintf(buf, sizeof(buf), SYSFS_GPIO_DIR "/gpio%d/value", gpio);  

    fd = open(buf, O_RDONLY);  
    if (fd < 0) {  
        perror("gpio/get-value");  
        return fd;  
    }  

    read(fd, &ch, 1);  

    if (ch != '0') {  
        *value = 1;  
    } else {  
        *value = 0;  
    }  

    close(fd);  
    return 0;  
}  


/**************************************************************** 
 * gpio_set_edge 
 ****************************************************************/  

int gpio_set_edge(unsigned int gpio, char *edge)  
{  
    int fd, len;  
    char buf[MAX_BUF];  

    len = snprintf(buf, sizeof(buf), SYSFS_GPIO_DIR "/gpio%d/edge", gpio);  

    fd = open(buf, O_WRONLY);  
    if (fd < 0) {  
        perror("gpio/set-edge");  
        return fd;  
    }  

    write(fd, edge, strlen(edge) + 1);   
    close(fd);  
    return 0;  
}  

/**************************************************************** 
 * gpio_fd_open 
 ****************************************************************/  

int gpio_fd_open(unsigned int gpio)  
{  
    int fd, len;  
    char buf[MAX_BUF];  

    len = snprintf(buf, sizeof(buf), SYSFS_GPIO_DIR "/gpio%d/value", gpio);  

    fd = open(buf, O_RDONLY | O_NONBLOCK );  
    if (fd < 0) {  
        perror("gpio/fd_open");  
    }  
    return fd;  
}  

/**************************************************************** 
 * gpio_fd_close 
 ****************************************************************/  

int gpio_fd_close(int fd)  
{  
    return close(fd);  
}  

/**************************************************************** 
 * Main 
 ****************************************************************/  
int main(int argc, char **argv, char **envp)  
{  
    struct pollfd fdset[2];  
    int nfds = 2;  
    int gpio_fd, timeout, rc;  
    char *buf[MAX_BUF];  
    unsigned int gpio;  
    int len;  



    if (argc < 2) {  
        printf("Usage: gpio-int <gpio-pin>\n\n");  
        printf("Waits for a change in the GPIO pin voltage level or input on stdin\n");  
        exit(-1);  
    }  

    gpio = atoi(argv[1]);  

    gpio_export(gpio);  
    gpio_set_dir(gpio, 0);  
    gpio_set_edge(gpio, "rising");  
    gpio_fd = gpio_fd_open(gpio);  

    timeout = POLL_TIMEOUT;  

    while (1) {  
        memset((void*)fdset, 0, sizeof(fdset));  

        fdset[0].fd = STDIN_FILENO;  
        fdset[0].events = POLLIN;  

        fdset[1].fd = gpio_fd;  
        fdset[1].events = POLLPRI;  

        rc = poll(fdset, nfds, timeout);        

        if (rc < 0) {  
            printf("\npoll() failed!\n");  
            return -1;  
        }  

        if (rc == 0) {  
            printf(".");  
        }  

        if (fdset[1].revents & POLLPRI) {  
            len = read(fdset[1].fd, buf, MAX_BUF);  
            printf("\npoll() GPIO %d interrupt occurred\n", gpio);  
        }  

        if (fdset[0].revents & POLLIN) {  
            (void)read(fdset[0].fd, buf, 1);  
            printf("\npoll() stdin read 0x%2.2X\n", (unsigned int) buf[0]);  
        }  

        fflush(stdout);  
    }  

    gpio_fd_close(gpio_fd);  
    return 0;  
}  
# UART Echo Example (See the README.md file in the upper level 'examples' directory for more information about examples.) This example demonstrates how to utilize UART interfaces by echoing back to the sender any data received on configured UART. ## How to use example ### Hardware Required The example can be run on any development board, that is based on the Espressif SoC. The board shall be connected to a computer with a single USB cable for flashing and monitoring. The external interface should have 3.3V outputs. You may use e.g. 3.3V compatible USB-to-Serial dongle. ### Setup the Hardware Connect the external serial interface to the board as follows. ``` ----------------------------------------------------------------------------------------- | Target chip Interface | Kconfig Option | Default ESP Pin | External UART Pin | | ----------------------|--------------------|----------------------|-------------------- | Transmit Data (TxD) | EXAMPLE_UART_TXD | GPIO4 | RxD | | Receive Data (RxD) | EXAMPLE_UART_RXD | GPIO5 | TxD | | Ground | n/a | GND | GND | ----------------------------------------------------------------------------------------- ``` Note: Some GPIOs can not be used with certain chips because they are reserved for internal use. Please refer to UART documentation for selected target. Optionally, you can set-up and use a serial interface that has RTS and CTS signals in order to verify that the hardware control flow works. Connect the extra signals according to the following table, configure both extra pins in the example code `uart_echo_example_main.c` by replacing existing `UART_PIN_NO_CHANGE` macros with the appropriate pin numbers and configure UART1 driver to use the hardware flow control by setting `.flow_ctrl = UART_HW_FLOWCTRL_CTS_RTS` and adding `.rx_flow_ctrl_thresh = 122` to the `uart_config` structure. ``` --------------------------------------------------------------- | Target chip Interface | Macro | External UART Pin | | ----------------------|-----------------|-------------------- | Transmit Data (TxD) | ECHO_TEST_RTS | CTS | | Receive Data (RxD) | ECHO_TEST_CTS | RTS | | Ground | n/a | GND | --------------------------------------------------------------- ``` ### Configure the project Use the command below to configure project using Kconfig menu as showed in the table above. The default Kconfig values can be changed such as: EXAMPLE_TASK_STACK_SIZE, EXAMPLE_UART_BAUD_RATE, EXAMPLE_UART_PORT_NUM (Refer to Kconfig file). ``` idf.py menuconfig ``` ### Build and Flash Build the project and flash it to the board, then run monitor tool to view serial output: ``` idf.py -p PORT flash monitor ``` (To exit the serial monitor, type ``Ctrl-]``.) See the Getting Started Guide for full steps to configure and use ESP-IDF to build projects. ## Example Output Type some characters in the terminal connected to the external serial interface. As result you should see echo in the same terminal which you used for typing the characters. You can verify if the echo indeed comes from ESP board by disconnecting either `TxD` or `RxD` pin: no characters will appear when typing. ## Troubleshooting You are not supposed to see the echo in the terminal which is used for flashing and monitoring, but in the other UART configured through Kconfig can be used. 我怎么使用
最新发布
05-17
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值