您的位置:首页 > 运维架构 > Linux

Linux字符驱动学习之LED

2016-03-30 21:52 393 查看
已经实习三周了,但还是感觉进入不了状态。以前学习方法严重错误,一些东西并没有真正理解而草草了事,以后坚持写博客,就权当是对知识的回顾和总结



驱动代码:

#include <linux/module.h>
#include <linux/init.h>
#include <linux/cdev.h>
#include <linux/fs.h>
#include <linux/io.h>
#include "led.h"

#define LEDCON 0xA0000010
#define LEDDAT 0xA0000014
unsigned int *led_config;
unsigned int *led_data;

struct cdev cdev;
dev_t devno;

int led_open(struct inode *node, struct file *filp)
{
led_config = ioremap(LEDCON,4);
writel(0x11110000,led_config);

led_data = ioremap(LEDDAT,4);

return 0;
}

long led_ioctl(struct inode* node,struct file *filp, unsigned int cmd, unsigned long arg)
{
switch (cmd)
{
case LED_ON:
writel(0x00,led_data);
return 0;

case LED_OFF:
writel(0xff,led_data);
return 0;

default:
return -EINVAL;
}
}

static struct file_operations led_fops =
{
.open = led_open,
.ioctl = led_ioctl,
};

static int led_init()
{
cdev_init(&cdev,&led_fops);

alloc_chrdev_region(&devno, 0 , 1 , "myled");
cdev_add(&cdev, devno, 1);

return 0;
}

static void led_exit()
{
cdev_del(&cdev);
unregister_chrdev_region(devno,1);
}

module_init(led_init);
module_exit(led_exit);


Linux驱动程序中对硬件的操作都是采用虚拟地址,所以对物理地址都要采用ioremap()函数进行映射。

led.h

#define LED_MAGIC 'M'
#define LED_ON    _IO(LED_MAGIC,0)
#define LED_OFF   _IO(LED_MAGIC,1)


应用程序

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include "led.h"

int main(int argc, char *argv[])
{
int fd;
int cmd;

if (argc <2 )
{
printf("please enter the second para!\n");
return 0;
}

cmd = atoi(argv[1]);

fd = open("/dev/myled",O_RDWR);

if (cmd == 1)
ioctl(fd,LED_ON);
else
ioctl(fd,LED_OFF);

return 0;
}


最后 mknod /dev/myled +主设备号+次设备号
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: