手头上有一块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
运行结果如下: