0
点赞
收藏
分享

微信扫一扫

和菜鸟一起学OK6410之最简单字符驱动


 

       近来睡得都有些晚啊,早上却依旧早早地醒来,心里空空的,不知道可以做什么,既然没事做,那就继续玩OK6410吧,昨晚把最简单的hello world驱动搞定了,今天就把字符型设备驱动总结下吧,以前看过一片文章写得不错,代码都准备好了,就是没有去试过,现在就马上去试试吧。字符型设备驱动,OK6410,哥来了。

        驱动嘛,首先得写代码,不多说了,直接上代码吧:

 



#include <linux/init.h>

#include <linux/module.h>

#include <linux/kernel.h>

#include <linux/fs.h>

#include <asm/uaccess.h>



#define MY_MAJOR 240



int mychar_open(struct inode *inode, struct file *filp)

{

printk("$$$$$$$$$$$mychar_open$$$$$$$$$\n");

return 0;

}



ssize_t mychar_read(struct file *filp, char __user *buf, size_t count, loff_t *f_pos)

{

printk("$$$$$$$$$$mychar_read$$$$$$$$$\n");

return count;

}





ssize_t mychar_write(struct file *filp, char __user *buf, size_t count, loff_t *f_pos)

{

printk("$$$$$$$$$$mychar_write$$$$$$$$$\n");

return count;

}



int mychar_release(struct inode *inode, struct file *filp)

{

printk("$$$$$$$$$$mychar_release$$$$$$$$$\n");

return 0;

}



struct file_operations my_fops = {

.owner = THIS_MODULE,

.open = mychar_open,

.read = mychar_read,

.write = mychar_write,

.release = mychar_release,

};



static int mychar_init(void)

{

int rc;

printk("Test mychar dev\n");

rc = register_chrdev(MY_MAJOR, "eastmoon", &my_fops);

if(rc < 0)

{

printk("register %s mychar dev error\n", "eastmoon");

return -1;

}

printk("$$$$$$$$$ register mychar dev OK\n");

return 0;

}



static void mychar_exit(void)

{

unregister_chrdev(MY_MAJOR, "eastmoon");

printk("Good Bye!\n");

}



MODULE_LICENSE("GPL");

module_init(mychar_init);

module_exit(mychar_exit);

LDD3就好了。接着就是把这个代码编译成.ko模块了。

          Makefile代码




obj-m := mychar.o


makemod,代码如下



make -C /home/eastmoon/work/linux2.6.28/ M=`pwd` modules

source makemod就可以

 

        写好了驱动,怎么知道驱动好了呢,得写个测试程序才可以啊。



#include <stdio.h>

#include <sys/types.h>

#include <sys/stat.h>

#include <fcntl.h>



#define DEVICE "/dev/mychar"



int main(void)

{

int fd;

char buf1[10] = {0, 1};

char buf2[10];



fd = open(DEVICE, O_RDWR);

if(fd < 0)

{

printf("Open /dev/mychar");

return -1;

}



write(fd, buf1, 3);

read(fd, buf2, 3);

close(fd);



return 0;



}

 

接着makefile:

 

CC = /usr/local/arm/4.2.2-eabi/usr/bin/arm-linux-gcc 



mycharapp:mycharapp.o

$(CC) -o mycharapp mycharapp.o

mycharapp.o : mycharapp.c

$(CC) -c mycharapp.c



clean :

rm mycharapp.o

 

        然后开始板子上调试了。具体怎么搞到板子上什么的,前面两篇已经写过了,这里就不罗嗦了。

 

和菜鸟一起学OK6410之最简单字符驱动_struct

init函数已经进去了,设备也注册成功了

mdnod下

和菜鸟一起学OK6410之最简单字符驱动_测试_02

 

;

 

和菜鸟一起学OK6410之最简单字符驱动_makefile_03

i是不小心加进去的,上面代码中已经删除了。

come on。。。。。。

举报

相关推荐

0 条评论