led.h
#ifndef __HEAD_H__
#define __HEAD_H__
typedef struct
{
unsigned int MODER;
unsigned int OTYPER;
unsigned int OSPEEDR;
unsigned int PUPDR;
unsigned int IDR;
unsigned int ODR;
unsigned int BSRR;
} gpio_t;
#define PHY_LED1_ADDR 0X50006000
#define PHY_LED2_ADDR 0X50007000
#define PHY_LED3_ADDR 0X50006000
#define PHY_RCC_ADDR 0X50000A28
#define PHY_PWN_ADDR 0X50003000
#define PHY_FAN_ADDR 0X50006000
#define PHY_MOTOR_ADDR 0X50007000
// 定义功能码
#define LED_ON _IOW('l', 1, int) // 开灯
#define LED_OFF _IOW('l', 0, int) // 关灯
#define PWN_ON _IO('l', 1) // 开蜂鸣器
#define PWN_OFF _IO('l', 0) // 关蜂鸣器
#define FAN_ON _IO('l', 1) // 开风扇
#define FAN_OFF _IO('l', 0) // 关风扇
#define MOTOR_ON _IO('l', 1) // 开马达
#define MOTOR_OFF _IO('l', 0) // 关马达
#endif
灯.c
#include <linux/init.h>
#include <linux/module.h>
#include<linux/fs.h>
#include<linux/io.h>
#include<linux/device.h>
#include"led.h"
int major;
char kbuf[128]={0};
gpio_t *vir_led1;
gpio_t *vir_led2;
gpio_t *vir_led3;
unsigned int *vir_rcc;
struct class *cls;
struct device *dev;
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__);
unsigned long ret;
//向用户空间读取拷贝
if(size>sizeof(kbuf))//用户空间期待读取的大小内核满足不了,那就给内核支持的最大大小
size=sizeof(kbuf);
ret=copy_to_user(ubuf,kbuf,size);
if(ret)//拷贝失败
{
printk("copy_to_user filed\n");
return ret;
}
return 0;
}
ssize_t mycdev_write(struct file *file, const char *ubuf, size_t size, loff_t *lof)
{
unsigned long ret;
//从用户空间读取数据
if(size>sizeof(kbuf))//用户空间期待读取的大小内核满足不了,那就给内核支持的最大大小
size=sizeof(kbuf);
ret=copy_from_user(kbuf,ubuf,size);
if(ret)//拷贝失败
{
printk("copy_to_user filed\n");
return ret;
}
return 0;
}
//ioctl
long mycdev_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
{
int which,ret;
//将ioctl第三个参数的数值拷贝给which;
ret=copy_from_user(&which,(void *)arg,sizeof(int));
if(ret)
{
printk("copy_from_user filed\n");
return -EIO;
}
//根据功能码进行硬件功能控制
switch(cmd)
{
case LED_ON:
switch(which)
{
case 1:
vir_led1->ODR |= (1<<10);
break;
case 2:
vir_led2->ODR |= (1<<10);
break;
case 3:
vir_led3->ODR |= (1<<8);
break;
}
break;
case LED_OFF:
switch(which)
{
case 1:
vir_led1->ODR &= (~(1<<10));
break;
case 2:
vir_led2->ODR &= (~(1<<10));
break;
case 3:
vir_led3->ODR &= (~(1<<8));
break;
}
break;
}
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,
.unlocked_ioctl=mycdev_ioctl,
.release=mycdev_close,
};
int all_led_init(void)
{
//寄