Linux字符驱动学习之LED

已经实习三周了,但还是感觉进入不了状态。以前学习方法严重错误,一些东西并没有真正理解而草草了事,以后坚持写博客,就权当是对知识的回顾和总结
字符驱动流程图
驱动代码:

#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 +主设备号+次设备号

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值