代码demo
#include <linux/fs.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/device.h>
#include <linux/uaccess.h>
#include <linux/types.h>
#include <asm/io.h>
static struct class *pin4_class;
static struct device *pin4_class_dev;
static dev_t devno;
static int major =231;
static int minor =0;
static char *module_name="pin4";
static int pin4_open(struct inode *inode,struct file *file)
{
printk("pin4_open\n");
return 0;
}
static ssize_t pin4_write(struct file *file,const char __user *buf,size_t count, loff_t *ppos)
{
printk("pin4_write\n");
return 0;
}
static struct file_operations pin4_fops = {
.owner = THIS_MODULE,
.open = pin4_open,
.write = pin4_write,
};
int __init pin4_drv_init(void)
{
int ret;
devno = MKDEV(major,minor);
ret = register_chrdev(major, module_name,&pin4_fops);
pin4_class=class_create(THIS_MODULE,"myfirstdemo");
pin4_class_dev =device_create(pin4_class,NULL,devno,NULL,module_name);
return 0;
}
void __exit pin4_drv_exit(void)
{
device_destroy(pin4_class,devno);
class_destroy(pin4_class);
unregister_chrdev(major, module_name);
}
module_init(pin4_drv_init);
module_exit(pin4_drv_exit);
MODULE_LICENSE("GPL v2");
驱动代码编译
xm@ubuntu:~/SYSTEM/linux-rpi-4.14.y/drivers/char$ ls
agp ds1302.c hw_random mem.o nvram.c pin4driver.mod.c raw.c tb0219.c virtio_console.c
apm-emulation.c ds1620.c ipmi misc.c nwbutton.c pin4driver.mod.o raw.o tile-srom.c xilinx_hwicap
applicom.c dsp56k.c Kconfig misc.o nwbutton.h pin4driver.o rtc.c tlclk.c xillybus
applicom.h dtlk.c lp.c modules.builtin nwflash.c powernv-op-panel.c scx200_gpio.c toshiba.c
bfin-otp.c efirtc.c Makefile modules.order pc8736x_gpio.c ppdev.c snsc.c tpm
broadcom generic_nvram.c mbcs.c mspec.c pcmcia ps3flash.c snsc_event.c ttyprintk.c
bsr.c hangcheck-timer.c mbcs.h mwave pin4driver.c random.c snsc.h ttyprintk.o
built-in.o hpet.c mem.c nsc_gpio.c pin4driver.ko random.o sonypi.c uv_mmtimer.c
xm@ubuntu:~/SYSTEM/linux-rpi-4.14.y/drivers/char$ vi Makefile
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/603e8cee8485175a6f5d40e3d2e1e895.png#pic_center)
xm@ubuntu:~/SYSTEM/linux-rpi-4.14.y$ ARCH=arm CROSS_COMPILE=arm-linux-gnueabihf- KERNEL=kernel7 make modules
- 编译完成以后将在字符目录下生成.ko文件,利用scp传递到树莓派中去
树莓派测试驱动
#include "stdio.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int main()
{
int fd=open("/dev/pin4",O_RDWR);
if(fd<0){
printf("open failed\n");
perror("reason:");
}else printf("open success\n");
write(fd,"1",1);
return 0;
}
~
- 检查有无.ko文件,然后输入下列命令加载到内核驱动
sudo insomd pin4driver.ko
- 加载完成后可输入lsmod查看是否加载进去的驱动,然后将测试代码编译后执行发现open失败,这时我们输入dmesg查看内核态打印信息,没任何消息,因此我们需要将驱动文件加访问权限
sudo chmod 666 /dev/pin4
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/b4547b7897127d9948faffba3b287067.png#pic_center)
- 若要删除驱动 sudo rmmod pin4driver //不需要加.ko