我的第一个Linux开发板字符驱动程序

本文记录了作者在colibri-imx7开发板上实现Linux字符驱动程序的过程。从参考S3C2440的驱动程序开始,经过修改和交叉编译,最终成功加载模块并测试。在ubuntu16.04.4环境下,使用arm-linux-gnueabihf-gcc交叉编译工具,通过insmod加载ko模块,并通过cat /proc/devices验证设备注册。最后,创建设备节点并运行测试程序验证驱动功能。

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

    手头上有一块colibri-imx7开发板,闲暇时间学习linux,想让其跑起来,却苦于网上根本就没有现成的例程,怎么办呢?想起可以参考韦山东S3C2440的第一个字符驱动程序,实现在colibri-imx7开发板跑起来!经过不断的尝试和同学热忱的帮助,我的第一个字符驱动程序终于跑起来了。作为一个初学者,同时本人又健忘,所以记录下笔记。

    本人使用的是ubuntu16.04.4,colibri-imx7的交叉编译工具是arm-linux-gnueabihf-gcc,都已经配置好了。以下就是字符驱动程序的操作步骤。

    第一步,加载字符驱动程序模块

    直接拷贝韦山东的first_drv.c和Makefile文件到ubuntu中,修改文件最终如下:

    first_drv.c文件修改如下:

#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/fs.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <asm/uaccess.h>
#include <asm/irq.h>
#include <asm/io.h>
static int first_drv_open(struct inode *inode, struct file *file)
{
	printk("first_drv_open\n");
	return 0;
}
static ssize_t first_drv_write(struct file *file, const char __user *buf, size_t count, loff_t * ppos)
{
	printk("first_drv_write\n");	
	return 0;
}
static struct file_operations first_drv_fops = {
    .owner  =   THIS_MODULE,    /* 这是一个宏,推向编译模块时自动创建的__this_module变量 */
    .open   =   first_drv_open,     
	.write	=	first_drv_write,	   
};
static int first_drv_init(void)
{
  register_chrdev(111, "first_drv", &first_drv_fops); // 注册, 告诉内核
	return 0;
}
static void first_drv_exit(void)
{
	unregister_chrdev(111, "first_drv"); // 卸载
}
module_init(first_drv_init);
module_exit(first_drv_exit);


MODULE_LICENSE("GPL");

Makefile文件修改如下:

export ARCH=arm
export CROSS_COMPILE=arm-linux-gnueabihf-
KERN_DIR = /home/Tom/work/colibri-imx7/linux-toradex

all:
	make -C $(KERN_DIR) M=`pwd` modules 

clean:
	make -C $(KERN_DIR) M=`pwd` modules clean
	rm -rf modules.order

obj-m	+= first_drv.o
在makefile文件中增加了export...,路径要对应好linux SDK实际存放的路径,然后make下,生成first_drv.ko文件

first_drv.ko移到colibri-imx7开发板中,加载模块,运行命令

insmod first_drv.ko

然后cat /proc/devices查看一下,发现主设备号为111的first_drv字符型设备


 第二步,测试字符驱动程序模块

直接拷贝韦山东的firstdrvtest.c文件到ubuntu中,

firstdrvtest.c修改后如下:

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
/* firstdrvtest on
  * firstdrvtest off
  */
int main(int argc, char **argv)
{
	int fd;
	int val = 1;
	fd = open("/dev/xxx", O_RDWR);
	if (fd < 0)
	{
		printf("can't open!\n");
	}	
	write(fd, &val, 4);
	return 0;
}
编译,输入命令arm-linux-gnueabihf-gcc -o firstdrvtest firstdrvtest.c,生成firstdrvtest 文件,移到colibri-imx7开发板中

先创建设备节点,在colibri-imx7开发板中输入命令

mknod /dev/xxx c 111 0 

然后在运行测试程序

./firstdvtest

运行结果如下:





 

    

  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值