本文章参考正点原子相关教程,仅学习记录使用
驱动代码流程流程
//打开文件
static int chrdevbase_open(struct inode *inode, struct file *flip)
//读文件
static ssize_t chrdevbase_read(struct file *filp, char __user *buf, size_t cnt, loff_t *offt)
//写文件
static ssize_t chrdevbase_write(struct file *flip, const char __user *buf, size_t cnt, loff_t *offt)
//关闭文件
static int chrdevbase_release(struct inode *inode, struct file *filp)
//驱动函数配置函数
static struct file_operations chrdevbase_fops = {
.owner = THIS_MODULE,
.open = chrdevbase_open,
.read = chrdevbase_read,
.write = chrdevbase_write,
.release = chrdevbase_release,
};
//驱动初始化
static int __init chrdevbase_init(void)
int register_chrdev_region(dev_t from, unsigned count, const char *name) // 注册驱动
//卸载驱动
static void __exit chrdevbase_exit(void)
int unregister_chrdev(dev_t from, const char *name)
//模块初始化驱动初始化、卸载函数
module_init(chrdevbase_init);
module_exit(chrdevbase_exit);
//协议、作者
MODULE_LICENSE("GPL");
MODULE_AUTHOR("TAN");
测试函数
//上述实现用户层函数与底层寄存器建立联系,使用linux用户层提供的open,read,write,close实现驱动操作。
#include "stdio.h"
#include "unistd.h"
#include "sys/types.h"
#include "sys/stat.h"
#include "fcntl.h"
#include "stdlib.h"
#include "string.h"
static char user_data[] = {"usr data!"};
int main(int argc, char const *argv[])
{
int fd , ret;
char *filename;
char readbuf[100], writebuf[100];
if(argc != 3){
printf("Error usage!\n");
return -1;
}
filename = argv[1];
fd = open(filename, O_RDWR);
if(fd < 0 ){
printf ( "can`t open file %s \n.", filename);
return -1;
}
**加粗样式**if(atoi(argv[2] == 1)){ /*read data */
ret = read(fd, readbuf, 50);
if(ret < 0 ){
printf("read data %s failed!\n", filename);
return -1;
}else{
printf("read data: %s \n",readbuf);
}
}else if(atoi(argv[2] == 2)){ /*write data */
memcpy(writebuf, user_data, sizeof(user_data));
ret = write(fd, writebuf, 50);
if( ret < 0 ){
printf("write file %s failed.\n", filename);
}
}
ret = close(fd);
if(ret < 0){
printf("close file %s failed.\n",filename);
return -1;
}
return 0;
return 0;
}