STM32MP157驱动开发——按键驱动(线程化处理)

文章目录

  • “线程化处理”机制:
  • 内核函数
  • 线程化处理方式的按键驱动程序(stm32mp157)
    • 编程思路
    • button_test.c
    • gpio_key_drv.c
    • Makefile
    • 修改设备树文件
    • 编译测试

“线程化处理”机制:

工作队列是在内核的线程的上下文中执行的

工作队列中有多个 work,前一个 work 没处理完会影响后面的 work。解决方法有如下2种:

  • 比如自己创建一个内核线程,不跟别的 work 在一块。例如存储设备比如 SD/TF采用的就是单独一个线程。

  • 使用线程化的中断处理。中断的处理仍然可以认为分为上半部、下半部。上半部用来处理紧急的事情,下半部用一个内核线程来处理,这个内核线程专用于这个中断。

内核函数

在这里插入图片描述
只需要提供 thread_fn,系统会为这个函数创建一个内核线程。发生中断时,系统会立刻调用 handler 函数,然后唤醒某个内核线程,内核线程再来执行 thread_fn 函数。

线程化处理方式的按键驱动程序(stm32mp157)

编程思路

调用 request_threaded_irq 函数注册中断,调用 free_irq 卸载中断。

request_threaded_irq可以提供上半部函数,也可以不提供

  • 如果不提供,内核会提供默认的上半部处理函数:irq_default_primary_handler,它是直接返回 IRQ_WAKE_THREAD
  • 如果提供的话,返回值必须是:IRQ_WAKE_THREAD。在 thread_fn 中,如果中断被正确处理了,应该返回 IRQ_HANDLED

button_test.c


#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <poll.h>
#include <signal.h>

static int fd;

/*
 * ./button_test /dev/my_button0 &
 *
 */
int main(int argc, char **argv)
{
	int val;
	struct pollfd fds[1];
	int timeout_ms = 5000;
	int ret;
	int	flags;

	int i;
	
	/* 1. 判断参数 */
	if (argc != 2) 
	{
		printf("Usage: %s <dev>\n", argv[0]);
		return -1;
	}


	/* 2. 打开文件 */
	fd = open(argv[1], O_RDWR | O_NONBLOCK);
	if (fd == -1)
	{
		printf("can not open file %s\n", argv[1]);
		return -1;
	}

	for (i = 0; i < 10; i++) 
	{
		if (read(fd, &val, 4) == 4)
			printf("get button: 0x%x\n", val);
		else
			printf("get button: -1\n");
	}

	flags = fcntl(fd, F_GETFL);
	fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);

	while (1)
	{
		if (read(fd, &val, 4) == 4)
			printf("get button: 0x%x\n", val);
		else
			printf("while get button: -1\n");
	}
	
	close(fd);
	
	return 0;
}



gpio_key_drv.c

#include <linux/module.h>
#include <linux/poll.h>

#include <linux/fs.h>
#include <linux/errno.h>
#include <linux/miscdevice.h>
#include <linux/kernel.h>
#include <linux/major.h>
#include <linux/mutex.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <linux/stat.h>
#include <linux/init.h>
#include <linux/device.h>
#include <linux/tty.h>
#include <linux/kmod.h>
#include <linux/gfp.h>
#include <linux/gpio/consumer.h>
#include <linux/platform_device.h>
#include <linux/of_gpio.h>
#include <linux/of_irq.h>
#include <linux/interrupt.h>
#include <linux/irq.h>
#include <linux/slab.h>
#include <linux/fcntl.h>
#include <linux/timer.h>
#include <linux/workqueue.h>
#include <asm/current.h>//打印内核线程的id需要的头文件


struct gpio_key{
	int gpio;
	struct gpio_desc *gpiod;
	int flag;
	int irq;
	struct timer_list key_timer;
	struct tasklet_struct tasklet;
	struct work_struct work;//每个按键都有工作队列
} ;

static struct gpio_key *gpio_keys_first;

/* 主设备号                                                                 */
static int major = 0;
static struct class *gpio_key_class;

/* 环形缓冲区 */
#define BUF_LEN 128
static int g_keys[BUF_LEN];
static int r, w;

struct fasync_struct *button_fasync;

#define NEXT_POS(x) ((x+1) % BUF_LEN)

static int is_key_buf_empty(void)
{
	return (r == w);
}

static int is_key_buf_full(void)
{
	return (r == NEXT_POS(w));
}

static void put_key(int key)
{
	if (!is_key_buf_full())
	{
		g_keys[w] = key;
		w = NEXT_POS(w);
	}
}

static int get_key(void)
{
	int key = 0;
	if (!is_key_buf_empty())
	{
		key = g_keys[r];
		r = NEXT_POS(r);
	}
	return key;
}


static DECLARE_WAIT_QUEUE_HEAD(gpio_key_wait);

static void key_timer_expire(struct timer_list *t)
{
	struct gpio_key *gpio_key = from_timer(gpio_key, t, key_timer);
	int val;
	int key;

	val = gpiod_get_value(gpio_key->gpiod);


	printk("key_timer_expire key %d %d\n", gpio_key->gpio, val);
	key = (gpio_key->gpio << 8) | val;
	put_key(key);
	wake_up_interruptible(&gpio_key_wait);
	kill_fasync(&button_fasync, SIGIO, POLL_IN);
}

static void key_tasklet_func(unsigned long data)
{
	/* data ==> gpio */
	struct gpio_key *gpio_key = data;
	int val;
	int key;

	val = gpiod_get_value(gpio_key->gpiod);


	printk("key_tasklet_func key %d %d\n", gpio_key->gpio, val);
}

static void key_work_func(struct work_struct *work)
{
	struct gpio_key *gpio_key = container_of(work, struct gpio_key, work);//根据work成员的地址反推结构体地址
	int val;

	val = gpiod_get_value(gpio_key->gpiod);

	printk("key_work_func: the process is %s pid %d\n",current->comm, current->pid);//打印内核线程的id	
	printk("key_work_func key %d %d\n", gpio_key->gpio, val);
}

/* 实现对应的open/read/write等函数,填入file_operations结构体                   */
static ssize_t gpio_key_drv_read (struct file *file, char __user *buf, size_t size, loff_t *offset)
{
	//printk("%s %s line %d\n", __FILE__, __FUNCTION__, __LINE__);
	int err;
	int key;

	if (is_key_buf_empty() && (file->f_flags & O_NONBLOCK))
		return -EAGAIN;
	
	wait_event_interruptible(gpio_key_wait, !is_key_buf_empty());
	key = get_key();
	err = copy_to_user(buf, &key, 4);
	
	return 4;
}

static unsigned int gpio_key_drv_poll(struct file *fp, poll_table * wait)
{
	printk("%s %s line %d\n", __FILE__, __FUNCTION__, __LINE__);
	poll_wait(fp, &gpio_key_wait, wait);
	return is_key_buf_empty() ? 0 : POLLIN | POLLRDNORM;
}

static int gpio_key_drv_fasync(int fd, struct file *file, int on)
{
	if (fasync_helper(fd, file, on, &button_fasync) >= 0)
		return 0;
	else
		return -EIO;
}


/* 定义自己的file_operations结构体                                              */
static struct file_operations gpio_key_drv = {
	.owner	 = THIS_MODULE,
	.read    = gpio_key_drv_read,
	.poll    = gpio_key_drv_poll,
	.fasync  = gpio_key_drv_fasync,
};


static irqreturn_t gpio_key_isr(int irq, void *dev_id)
{
	struct gpio_key *gpio_key = dev_id;
	//printk("gpio_key_isr key %d irq happened\n", gpio_key->gpio);
	tasklet_schedule(&gpio_key->tasklet);
	mod_timer(&gpio_key->key_timer, jiffies + HZ/50);
	schedule_work(&gpio_key->work);
	return IRQ_WAKE_THREAD;//指定上半部分函数返回值指定为:IRQ_WAKE_THREAD
}

static irqreturn_t gpio_key_thread_func(int irq, void *data)
{
	struct gpio_key *gpio_key = data;
	int val;

	val = gpiod_get_value(gpio_key->gpiod);

	printk("gpio_key_thread_func: the process is %s pid %d\n",current->comm, current->pid);	//打印线程id
	printk("gpio_key_thread_func key %d %d\n", gpio_key->gpio, val);
	
	return IRQ_HANDLED;//指定下半部分函数返回值指定为:IRQ_WAKE_THREAD
}

/* 1. 从platform_device获得GPIO
 * 2. gpio=>irq
 * 3. request_irq
 */
static int gpio_key_probe(struct platform_device *pdev)
{
	int err;
	struct device_node *node = pdev->dev.of_node;
	int count;
	int i;
	enum of_gpio_flags flag;
		
	printk("%s %s line %d\n", __FILE__, __FUNCTION__, __LINE__);

	count = of_gpio_count(node);
	if (!count)
	{
		printk("%s %s line %d, there isn't any gpio available\n", __FILE__, __FUNCTION__, __LINE__);
		return -1;
	}

	gpio_keys_first= kzalloc(sizeof(struct gpio_key) * count, GFP_KERNEL);
	for (i = 0; i < count; i++)
	{		
		gpio_keys_first[i].gpio = of_get_gpio_flags(node, i, &flag);
		if (gpio_keys_first[i].gpio < 0)
		{
			printk("%s %s line %d, of_get_gpio_flags fail\n", __FILE__, __FUNCTION__, __LINE__);
			return -1;
		}
		gpio_keys_first[i].gpiod = gpio_to_desc(gpio_keys_first[i].gpio);
		gpio_keys_first[i].flag = flag & OF_GPIO_ACTIVE_LOW;
		gpio_keys_first[i].irq  = gpio_to_irq(gpio_keys_first[i].gpio);

		//setup_timer(&gpio_keys_first[i].key_timer, key_timer_expire, &gpio_keys_first[i]);
		timer_setup(&gpio_keys_first[i].key_timer, key_timer_expire, 0);
		gpio_keys_first[i].key_timer.expires = ~0;
		add_timer(&gpio_keys_first[i].key_timer);

		tasklet_init(&gpio_keys_first[i].tasklet, key_tasklet_func, &gpio_keys_first[i]);

		INIT_WORK(&gpio_keys_first[i].work, key_work_func);//初始化工作队列
	}

	for (i = 0; i < count; i++)
	{
		//err = request_irq(gpio_keys_first[i].irq, gpio_key_isr, IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING, "my_gpio_key", &gpio_keys_first[i]);
		err = request_threaded_irq(gpio_keys_first[i].irq, gpio_key_isr, gpio_key_thread_func, IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING, "my_gpio_key", &gpio_keys_first[i]);
	}

	/* 注册file_operations 	*/
	major = register_chrdev(0, "my_gpio_key", &gpio_key_drv);  /* /dev/gpio_key */

	gpio_key_class = class_create(THIS_MODULE, "my_gpio_key_class");
	if (IS_ERR(gpio_key_class)) {
		printk("%s %s line %d\n", __FILE__, __FUNCTION__, __LINE__);
		unregister_chrdev(major, "my_gpio_key");
		return PTR_ERR(gpio_key_class);
	}

	device_create(gpio_key_class, NULL, MKDEV(major, 0), NULL, "my_gpio_key"); /* /dev/my_gpio_key */
        
    return 0;
    
}

static int gpio_key_remove(struct platform_device *pdev)
{
	//int err;
	struct device_node *node = pdev->dev.of_node;
	int count;
	int i;

	device_destroy(gpio_key_class, MKDEV(major, 0));
	class_destroy(gpio_key_class);
	unregister_chrdev(major, "my_gpio_key");

	count = of_gpio_count(node);
	for (i = 0; i < count; i++)
	{
		free_irq(gpio_keys_first[i].irq, &gpio_keys_first[i]);
		del_timer(&gpio_keys_first[i].key_timer);
		tasklet_kill(&gpio_keys_first[i].tasklet);
	}
	kfree(gpio_keys_first);
    return 0;
}



static const struct of_device_id my_keys[] = {
    { .compatible = "first_key,gpio_key" },
    { },
};

/* 1. 定义platform_driver */
static struct platform_driver gpio_keys_driver = {
    .probe      = gpio_key_probe,
    .remove     = gpio_key_remove,
    .driver     = {
        .name   = "my_gpio_key",
        .of_match_table = my_keys,
    },
};

/* 2. 在入口函数注册platform_driver */
static int __init gpio_key_init(void)
{
    int err;
    
	printk("%s %s line %d\n", __FILE__, __FUNCTION__, __LINE__);
	
    err = platform_driver_register(&gpio_keys_driver); 
	
	return err;
}

/* 3. 有入口函数就应该有出口函数:卸载驱动程序时,就会去调用这个出口函数
 *     卸载platform_driver
 */
static void __exit gpio_key_exit(void)
{
	printk("%s %s line %d\n", __FILE__, __FUNCTION__, __LINE__);

    platform_driver_unregister(&gpio_keys_driver);
}


/* 7. 其他完善:提供设备信息,自动创建设备节点                                     */

module_init(gpio_key_init);
module_exit(gpio_key_exit);

MODULE_LICENSE("GPL");



Makefile

# 1. 使用不同的开发板内核时, 一定要修改KERN_DIR
# 2. KERN_DIR中的内核要事先配置、编译, 为了能编译内核, 要先设置下列环境变量:
# 2.1 ARCH,          比如: export ARCH=arm64
# 2.2 CROSS_COMPILE, 比如: export CROSS_COMPILE=aarch64-linux-gnu-
# 2.3 PATH,          比如: export PATH=$PATH:/home/book/100ask_roc-rk3399-pc/ToolChain-6.3.1/gcc-linaro-6.3.1-2017.05-x86_64_aarch64-linux-gnu/bin 
# 注意: 不同的开发板不同的编译器上述3个环境变量不一定相同,
#       请参考各开发板的高级用户使用手册

KERN_DIR =   /home/book/100ask_stm32mp157_pro-sdk/Linux-5.4

all:
	make -C $(KERN_DIR) M=`pwd` modules 
	$(CROSS_COMPILE)gcc -o button_test button_test.c
clean:
	make -C $(KERN_DIR) M=`pwd` modules clean
	rm -rf modules.order  button_test

# 参考内核源码drivers/char/ipmi/Makefile
# 要想把a.c, b.c编译成ab.ko, 可以这样指定:
# ab-y := a.o b.o
# obj-m += ab.o



obj-m += gpio_key_drv.o

修改设备树文件

在这里插入图片描述
对于一个引脚要用作中断时,

  • a) 要通过 PinCtrl 把它设置为 GPIO 功能;【ST 公司对于 STM32MP157 系列芯片,GPIO 为默认模式 不需要再进行配置Pinctrl 信息】
  • b) 表明自身:是哪一个 GPIO 模块里的哪一个引脚【修改设备树】

打开内核的设备树文件:arch/arm/boot/dts/stm32mp157c-100ask-512d-lcd-v1.dts

gpio_keys_first {
	compatible = "first_key,gpio_key";
	gpios = <&gpiog 3 GPIO_ACTIVE_LOW
			&gpiog 2 GPIO_ACTIVE_LOW>;
};

与此同时,需要把用到引脚的节点禁用

注意,如果其他设备树文件也用到该节点,需要设置属性为disabled状态,在arch/arm/boot/dts目录下执行如下指令查找哪些设备树用到该节点

grep "&gpiog" * -nr

如果用到该节点,需要添加属性去屏蔽:

status = "disabled"; 

在这里插入图片描述

编译测试

首先要设置 ARCH、CROSS_COMPILE、PATH 这三个环境变量后,进入 ubuntu 上板子内核源码的目录,在Linux内核源码根目录下,执行如下命令即可编译 dtb 文件:

make dtbs V=1

编译好的文件在路径由DTC指定,移植设备树到开发板的共享文件夹中,先保存源文件,然后覆盖源文件,重启后会挂载新的设备树,进入该目录查看是否有新添加的设备节点

cd /sys/firmware/devicetree/base 

编译驱动程序,在Makefile文件目录下执行make指令,此时,目录下有编译好的内核模块gpio_key_drv.ko和可执行文件button_test文件移植到开发板上

确定一下烧录系统:cat /proc/mounts,查看boot分区挂载的位置,将其重新挂载在boot分区:mount /dev/mmcblk2p2 /boot,然后将共享文件夹里面的设备树文件拷贝到boot目录下,这样的话设备树文件就在boot目录下

cp /mnt/stm32mp157c-100ask-512d-lcd-v1.dtb /boot

重启后挂载,运行

insmod -f gpio_key_drv.ko // 强制安装驱动程序
ls /dev/my_gpio_key
./button_test /dev/my_gpio_key & //后台运行,此时prink函数打印的内容看不到

然后按下按键

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/44322.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

【TypeScript】类型推断与类型别名的使用方式。

什么是类型推断&#xff1f; 在 TypeScript 中&#xff0c; 如果声明变量时&#xff0c;没有明确的指定类型&#xff0c;那么 TypeScript 会依照类型推论&#xff08;Type Inference&#xff09;的规则推断出一个类型。 以下代码虽然没有明确指定类型&#xff0c;但是会在编译的…

【043】解密C++ STL:深入理解并使用 list 容器

解密C STL&#xff1a;深入理解并使用list容器 引言一、list 容器概述二、list容器常用的API2.1、构造函数2.2、数据元素插入和删除操作2.3、大小操作2.4、赋值操作2.5、数据的存取2.6、list容器的反转和排序 三、使用示例总结 引言 &#x1f4a1; 作者简介&#xff1a;一个热爱…

浮点型在内存中的存储

目录 1.浮点数是什么&#xff1f; 2. 浮点数存储规则 1.浮点数是什么&#xff1f; 就是数学中的小数。 常见的浮点数&#xff1a; 3.14159 1E10&#xff08;1*10^10&#xff09; 浮点数家族包括&#xff1a; float、double、long double 类型。 浮点数表示的范围&#x…

Bean的生命周期

目录 1、实例化Bean 2、设置Bean的属性 3、初始化Bean &#xff08;1&#xff09;、执行通知 &#xff08;2&#xff09;、初始化的前置方法 &#xff08;3&#xff09;、初始化方法 &#xff08;4&#xff09;、执行自定义方法 &#xff08;5&#xff09;、初始化的后置…

API接口:如何通过使用手机归属地查询

随着手机普及率的不断增加&#xff0c;手机号码的信息查询也成为了一个非常实用的功能。本文将介绍如何通过使用手机归属地查询API接口实现查询手机号码所在地的功能。 首先&#xff0c;我们需要一个可以查询手机号码所在地的API接口。目前市面上有很多免费或付费的API接口可供…

《Ansible自动化工具篇:ubuntu操作系统基于ansible工具一键远程离线部署之K8S1.24.12二进制版集群》

一、部署背景 由于业务系统的特殊性&#xff0c;我们需要针对不同的客户环境部署二进制版K8S集群&#xff0c;由于大都数用户都是专网环境&#xff0c;无法使用外网&#xff0c;为了更便捷&#xff0c;高效的部署&#xff0c;针对业务系统的特性&#xff0c;我这边编写了 基于a…

uni-app中的uni.requireNativePlugin()

这个方法是用来引入原生插件的方法&#xff0c;自 HBuilderX 1.4 版本起&#xff0c;uni-app 支持引入原生插件&#xff0c;使用方式如下&#xff1a; const PluginName uni.requireNativePlugin(PluginName); // PluginName 为原生插件名称 引入插件的类型有三种&#xff1…

【idea工具】idea工具,build的时候提示:程序包 com.xxx.xx不存在的错误

idea工具&#xff0c;build的时候提示:程序包 com.xxx.xx不存在的错误&#xff0c;如下图&#xff0c;折腾了好一会&#xff0c; 做了如下操作还是不行&#xff0c;idea工具编译的时候&#xff0c;还是提示 程序包不存在。 a. idea中&#xff0c;重新导入项目&#xff0c;也还…

Mysql-主从复制与读写分离

Mysql 主从复制、读写分离 一、前言&#xff1a;二、主从复制原理1.MySQL的复制类型2. MySQL主从复制的工作过程;3.MySQL主从复制延迟4. MySQL 有几种同步方式&#xff1a;5.Mysql应用场景 三、主从复制实验1.主从服务器时间同步1.1 master服务器配置1.2 两台SLAVE服务器配置 2…

小程序自定义步骤条实现

效果展示&#xff1a; 支持背景颜色自定义 <view class"hl_steps"><view class"hl_steps_item" wx:for"{{steps}}" wx:key"id"><view class"hl_steps_item_circle_out" style"background-color: {{col…

【Linux网络】 网络套接字(三)socket编程_TCP网络程序

目录 TCP网络程序服务端创建套接字并绑定服务端监听服务端获取连接服务器处理请求 客户端客户端创建套接字客户端连接服务器客户端发起请求测试 服务器存在的问题多进程版的TCP网络程序多线程版的TCP网络程序线程池版的TCP网络程序 TCP网络程序总结图 TCP网络程序 服务端 创建…

踩坑_vertical-align

目录 问题&#xff1a;vertical-align属性语法父元素的基线怎么找呢&#xff1f;特殊元素的基线行盒 解决 问题&#xff1a; 今天在做一个需求时遇到了如下问题&#xff1a; 代码 <style>*{margin:0;padding:0;}#app{width: 300px;height: 117px;background: #FFFFFF;bo…

通过v-for生成的input无法连续输入

部分代码&#xff1a;通过v-for循环生成el-form-item&#xff0c;生成多个描述输入框 更改之前的代码&#xff08;key绑定的是item&#xff09;&#xff1a; <el-form-item class"forminput" v-for"(item,index) in formdata.description" :key"…

打造高效便捷的采购管理平台,提升企业采购效率

随着企业规模的扩大和供应链的日益复杂&#xff0c;传统的手工采购管理方式已经不能满足企业的需求。采购管理平台的出现为企业提供了一个集中、高效、便捷的采购管理工具。本文将重点探讨采购管理平台的意义与作用&#xff0c;并介绍如何打造一个高效便捷的采购管理平台。 一、…

PHY芯片的使用(三)在linux下网络PHY的移植

1 前言 配置设备树请参考上一章。此次说明还是以裕太的YT8511芯片为例。 2 需要配置的文件及路径 a. 在 .. /drivers/net/phy 目录下添加 yt_phy.c 文件&#xff08;一般来说该驱动文件由厂家提供&#xff09;&#xff1b; b. 修改.. /drivers/net/phy 目录下的 Kconfig 文…

欧盟新规,燃油噩梦?2025年起,高速公路每60公里设立一处快充站

根据外媒The Verge报道&#xff0c;欧洲电动汽车用户将获得更多便捷的待遇&#xff0c;同时还能减少有害温室气体排放&#xff0c;这得益于欧盟理事会最新通过的法规。 根据欧盟的法规要求&#xff0c;自2025年起&#xff0c;TEN-T高速公路系统在欧洲将需要每隔60公里设立一座高…

C# List 详解六

目录 35.MemberwiseClone() 36.Remove(T) 37.RemoveAll(Predicate) 38.RemoveAt(Int32) 39.RemoveRange(Int32, Int32) 40.Reverse() 41.Reverse(Int32, Int32) C# List 详解一 1.Add(T)&#xff0c;2.AddRange(IEnumerable)&#xff0c;3…

【Linux】冯诺依曼体系结构思想

冯诺依曼体系结构 冯诺依曼体系结构冯诺依曼体系结构的五大部分冯诺依曼体系结构的运行过程存储器中的木桶效应扩展&#xff1a;计算机存储设备金字塔实例&#xff1a;qq聊天数据传输过程 &#x1f340;小结&#x1f340; &#x1f389;博客主页&#xff1a;小智_x0___0x_ &…

手机+App=电脑静音无线鼠标 - WiFimouse初体验

应用情景 大晚上的别人在睡觉&#xff0c;自己又不得不使用电脑&#xff08;台式&#xff09;&#xff0c;鼠标点点点又吵。 专门买个静音鼠标又没钱&#xff0c;咋办~ 效果图 手机app 电脑无线触控板&#xff0c;零噪音&#xff01; 可以单击、移动鼠标光标、可以上下滚动…
最新文章