作业:字符设备驱动,完成三盏LED灯的控制
驱动代码: mychrdev.c
unsigned int *vir_moder_e;
unsigned int *vir_moder_f;
int mycdev_open(struct inode *inode, struct file *file){
printk("%s:%s:%d\n", __FILE__, __func__, __LINE__);
ssize_t mycdev_read(struct file *file, char *ubuf, size_t size, loff_t *lof){
ret = copy_to_user(ubuf, kbuf, size);
printk("copy_to_user err\n");
ssize_t mycdev_write(struct file *file, const char *ubuf, size_t size, loff_t *lof){
ret = copy_from_user(kbuf, ubuf, size);
printk("copy_from_user err\n");
(*vir_odr_e) |= (0x1 << 10);
}else if(kbuf[0] == '2'){
(*vir_odr_e) &= (~(0x1 << 10));
}else if(kbuf[0] == '3'){
(*vir_odr_f) |= (0x1 << 10);
}else if(kbuf[0] == '4'){
(*vir_odr_f) &= (~(0x1 << 10));
}else if(kbuf[0] == '5'){
(*vir_odr_e) |= (0x1 << 8);
}else if(kbuf[0] == '6'){
(*vir_odr_e) &= (~(0x1 << 8));
int mycdev_close(struct inode *inode, struct file *file){
printk("%s:%s:%d\n", __FILE__, __func__, __LINE__);
struct file_operations fops = {
static int __init mycdev_init(void){
major = register_chrdev(0, "mychrdev", &fops);
printk("字符设备驱动注册成功 major = %d\n", major);
vir_odr_e = ioremap(GPIOE_ODR, 4);
printk("物理内存映射失败%d\n", __LINE__);
vir_rcc_e = ioremap(GPIOE_RCC, 4);
printk("物理内存映射失败%d\n", __LINE__);
vir_moder_e = ioremap(GPIOE_MODER, 4);
printk("物理内存映射失败%d\n", __LINE__);
vir_odr_f = ioremap(GPIOF_ODR, 4);
printk("物理内存映射失败%d\n", __LINE__);
vir_rcc_f = ioremap(GPIOF_RCC, 4);
printk("物理内存映射失败%d\n", __LINE__);
vir_moder_f = ioremap(GPIOF_MODER, 4);
printk("物理内存映射失败%d\n", __LINE__);
(*vir_rcc_e) |= (0x1 << 4);
(*vir_rcc_f) |= (0x1 << 5);
(*vir_moder_e) &= (~(0x3 << 20));
(*vir_moder_e) |= (0x1 << 20);
(*vir_moder_f) &= (~(0x3 << 20));
(*vir_moder_f) |= (0x1 << 20);
(*vir_moder_e) &= (~(0x3 << 16));
(*vir_moder_e) |= (0x1 << 16);
(*vir_odr_e) &= (~(0x1 << 10));
(*vir_odr_f) &= (~(0x1 << 10));
(*vir_odr_e) &= (~(0x1 << 8));
static void __exit mycdev_exit(void){
unregister_chrdev(major, "mychrdev");
module_init(mycdev_init);
module_exit(mycdev_exit);
应用代码:test.c
int fd = open("/dev/mychrdev", O_RDWR);
printf("请输入对LED的控制命令:1(LED1开灯) 2(LED1关灯) 3(LED2开灯) 4(LED2关灯) 5(LED3开灯) 6(LED3关灯) >");
fgets(buf, sizeof(buf), stdin);
buf[strlen(buf) - 1] = '\0';
write(fd, buf, sizeof(buf));
头文件:head.h
#define GPIOE_MODER 0x50006000
#define GPIOE_ODR 0x50006014
#define GPIOE_RCC 0x50000A28
#define GPIOF_MODER 0x50007000
#define GPIOF_ODR 0x50007014
#define GPIOF_RCC 0x50000A28