linux驱动之按键驱动

目的:编写按键驱动

原理图:

按键与引脚对应关系:



1、编写驱动程序框架

2、查看原理图与s3c2440手册

3、编写open函数

配置引脚

4、编写read函数功能

驱动代码:

#include <linux/init.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/fs.h>
#include <asm/io.h>
#include <linux/cdev.h>
#include <linux/device.h>
#include <asm/uaccess.h>
MODULE_LICENSE("Dual BSD/GPL");

static struct class *buttondrv_class;
static struct class_devices *buttondrv_class_dev;

volatile unsigned long *gpfcon = NULL;
volatile unsigned long *gpfdat = NULL;

static int button_dev_open(struct inode *inode ,struct file* file)
{
	//配置按键的引脚 GPF0,1,2,4为输入引脚
	*gpfcon &= ~((0x3<<0*2)|(0x3<<1*2)|(0x3<<2*2)|(0x3<<4*2));

	return 0;
}
ssize_t button_dev_read(struct file *file,char __user *buf,size_t size,loff_t *ppos)
{
	/*返回四个引脚的电平*/
	unsigned char key_vals[4];
	int regval;
	if(size !=sizeof(key_vals))
	{
		return -EINVAL;
	}
	regval = *gpfdat;
	/*读四个引脚的电平*/
	key_vals[0] = (regval &(1<<0))? 1 : 0;
	key_vals[1] = (regval &(1<<1))? 1 : 0;
	key_vals[2] = (regval &(1<<2))? 1 : 0;
	key_vals[3] = (regval &(1<<4))? 1 : 0;
	copy_to_user(buf,key_vals,sizeof(key_vals));
	return sizeof(key_vals);
}
static struct file_operations button_sdv_fops =
{
	.owner = THIS_MODULE,
	.open  = button_dev_open,
	.read = button_dev_read,
};
int major;
static int button_dev_init(void)//入口函数
{
	major = register_chrdev(0,"button_drv",&button_sdv_fops);

	buttondrv_class = class_create(THIS_MODULE,"button_drv");
	if(IS_ERR(buttondrv_class))
		return PTR_ERR(buttondrv_class);
	buttondrv_class_dev= device_create(buttondrv_class,NULL,MKDEV(major,0),NULL,"wq_button");
		if(unlikely(IS_ERR(buttondrv_class_dev)))
			return PTR_ERR(buttondrv_class_dev);

	/*映射物理地址*/
	gpfcon = (volatile unsigned long *) ioremap(0x56000050 ,16);
	gpfdat = gpfcon + 1;

	return 0;
}
static void button_dev_exit(void)
{
	unregister_chrdev(major,"button_drv");
	device_unregister(buttondrv_class_dev);
	class_destroy(buttondrv_class);

	iounmap(gpfcon);
}
module_init(button_dev_init);
module_exit(button_dev_exit);

测试程序代码:

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
/*
 * wq_device <dev> <on|off>
 */
int main(int argc, char **argv)
{
	int cnt=0;
	int fd;
	unsigned char key_vals[4];
	fd = open("/dev/wq_button",	O_RDWR);
	if(fd<0)
	{
		printf("can't open \n");
	}
	while(1)
	{
		read(fd,key_vals,sizeof(key_vals));
		if(!key_vals[0]||!key_vals[1]||!key_vals[2]||!key_vals[3])
		{
			printf("%04d k1 k2 k3 k4  is %d %d %d %d \n",cnt++,key_vals[0],key_vals[1],key_vals[2],key_vals[3]);
		}
	}
	return 0;
}



  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值