mychrdev.c
#include
#include
#include
#include
#include
#include "head.h"
unsigned int major; // 保存主设备号
char kbuf[128]={0};
unsigned int *vir_rcc;
unsigned int *vir_moder;
unsigned int *vir_odr;
// 封装操作方法
int mycdev_open(struct inode *inode, struct file *file)
{
printk("%s:%s:%d\n",__FILE__,__func__,__LINE__);
return 0;
}
ssize_t mycdev_read(struct file *file, char *ubuf, size_t size, loff_t *lof)
{
printk("%s:%s:%d\n",__FILE__,__func__,__LINE__);
int ret;
ret=copy_to_user(ubuf,kbuf,size);
if(ret){
printk("copy_to_user err\n");
return -EIO;
}
return 0;
}
ssize_t mycdev_write(struct file *file, const char *ubuf, size_t size, loff_t *lof)
{
printk("%s:%s:%d\n",__FILE__,__func__,__LINE__);
int ret;
ret=copy_from_user(kbuf,ubuf,size);
if(ret){
printk("copy_from_user err\n");
return -EIO;
}
//拿取用户在串口输入的内容, 第0位字符. 若1, vir_odr [10] = 1 亮. 不为1, vir_odr [10] = 0 灭.
printk("内核打印:%s",kbuf);
if(kbuf[0]=='1'){
//开灯逻辑
(*vir_odr) |= (0x1 << 10);
}else {
//关灯逻辑
(*vir_odr) &= (~(0x1 << 10));
}
return 0;
}
int mycdev_close(struct inode *inode, struct file *file)
{
printk("%s:%s:%d\n",__FILE__,__func__,__LINE__);
return 0;
}
// 定义一个操作方法结构体对象并且初始化
struct file_operations fops = {
.open=mycdev_open,
.read=mycdev_read,
.write=mycdev_write,
.release=mycdev_close,
};
static int __init mycdev_init(void)
{
// 字符设备驱动的注册
major = register_chrdev(0, "mychrdev", &fops);
if (major < 0)
{
printk("字符设备驱动注册失败\n");
return major;
}
printk("字符设备驱动注册成功major=%d\n",major);
//进行相关寄存器的内存映射
vir_rcc=ioremap(LED1_RCC,4);
if(vir_rcc==NULL){
printk("LED1_RCC物理内存映射失败%d\n",__LINE__);
return -EFAULT;
}
vir_moder=ioremap(LED1_MODER,4);
if(vir_moder==NULL){
printk("LED1_MODER物理内存映射失败%d\n",__LINE__);
return -EFAULT;
}
vir_odr=ioremap(LED1_ODR,4);
if(vir_odr==NULL){
printk("LED1_ODR物理内存映射失败%d\n",__LINE__);
return -EFAULT;
}
printk("寄存器内存映射成功\n");
//硬件寄存器的初始化
//RCC使能 vir_rcc [4]=1
(*vir_rcc) |= (0x1 << 4);
//设置PE10为输出模式 vir_moder [21:20]=01
(*vir_moder) &= (~(0x3 << 20));
(*vir_moder) |= (0x1 << 20);
//设置默认关灯 vir_odr [10]=1
(*vir_odr) &= (~(0x1 << 10));
return 0;
}
static void __exit mycdev_exit(void)
{
//取消物理内存映射
iounmap(vir_rcc);
iounmap(vir_moder);
iounmap(vir_odr);
// 字符设备驱动注销
unregister_chrdev(major, "mychrdev");
}
module_init(mycdev_init);
module_exit(mycdev_exit);
MODULE_LICENSE("GPL");
test.c
#include
#include
#include
#include
#include
#include
#include
int main(int argc, char const *argv[])
{
char buf[128] = {0};
int fd = open("/dev/mychrdev", O_RDWR);
if (fd < 0)
{
printf("设备文件打开失败\n");
exit(-1);
}
while(1){
printf("请输入对LED1的控制命令1(开灯) 0(关灯)>");
fgets(buf,sizeof(buf),stdin);//在终端输入数据传递到buf
buf[strlen(buf)-1]='\0';//替换末尾的'\n'
write(fd,buf,sizeof(buf));
memset(buf,0,sizeof(buf));//清空数组
read(fd, buf, sizeof(buf));
printf("buf:%s\n",buf);
}
close(fd);
return 0;
}
head.h
#ifndef __HEAD_H__
#define __HEAD_H__
#define LED1_MODER 0X50006000
#define LED1_ODR 0X50006014
#define LED1_RCC 0X50000A28
#endif