leds_drv.h
[cpp]
#ifndef _MEMDEV_H_
#define _MEMDEV_H_
#include
/* 定义幻数 */
#define MEMDEV_IOC_MAGIC 'k'
/* 定义命令 */
#define MEMDEV_IOC_ON _IO(MEMDEV_IOC_MAGIC, 1)
#define MEMDEV_IOC_OFF _IO(MEMDEV_IOC_MAGIC, 2)
#define MEMDEV_IOC_MAXNR 2
#define LED_ON 0
#define LED_OFF 1
#endif /* _MEMDEV_H_ */
leds_drv.c
[cpp]
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include "leds_drv.h"
#define DEVICE_NAME "leds"
static unsigned long led_table[] = {
S3C2410_GPB(5),
S3C2410_GPB(6),
S3C2410_GPB(7),
S3C2410_GPB(8),
};
static unsigned int led_cfg_table[] = {
S3C2410_GPIO_OUTPUT,
S3C2410_GPIO_OUTPUT,
S3C2410_GPIO_OUTPUT,
S3C2410_GPIO_OUTPUT,
};
static int s3c2440_leds_ioctl(struct inode *inode,
struct file *file, unsigned int cmd, unsigned long arg)
{
/* 检测命令的有效性 */
if (_IOC_TYPE(cmd) != MEMDEV_IOC_MAGIC)
return -EINVAL;
if (_IOC_NR(cmd) > MEMDEV_IOC_MAXNR)
return -EINVAL;
/* 根据命令,执行相应的操作 */
switch (cmd)
{
case MEMDEV_IOC_OFF:
s3c2410_gpio_setpin(led_table[arg], LED_OFF);
return 0;
case MEMDEV_IOC_ON:
s3c2410_gpio_setpin(led_table[arg], LED_ON);
return 0;
default:
return -EINVAL;
}
}
/*文件操作结构体*/
static struct file_operations dev_fops = {
.owner = THIS_MODULE,
.ioctl = s3c2440_leds_ioctl,
};
static struct miscdevice misc = {
.minor = MISC_DYNAMIC_MINOR,
.name = DEVICE_NAME,
.fops = &dev_fops,
};
static int __init dev_init(void)
{
int ret;
int i;
/*设置GPIO控制寄存器,GPIO设置为输出模式,默认下灯全灭 */
for (i = 0; i < 4; i++)
{
s3c2410_gpio_cfgpin(led_table[i], led_cfg_table[i]);
s3c2410_gpio_setpin(led_table[i], 1);
}
/*注册混杂型字符设备驱动 */
ret = misc_register(&misc);
printk(DEVICE_NAME "tinitializedn");
return ret;
}
static void __exit dev_exit(void)
{
/*注销混杂型字符设备驱动 */
misc_deregister(&misc);
}
module_init(dev_init);
module_exit(dev_exit);
MODULE_AUTHOR("Cried Devil");
MODULE_LICENSE("GPL");
app-leds.c
[cpp]
#include
#include
#include
#include
#include "leds_drv.h" /* 包含命令定义 */
int main(int argc, char **argv)
{
int on;
int fd;
int num;
if (argc != 3 ||
sscanf(argv[1],
"%d",
&num) !=
1 || sscanf(argv[2], "%d", &on) != 1 || on < 0 || on > 1 || num < 0 || num > 3)
{
fprintf(stderr, "Usage: %s led_num off|onn", argv[0]);
fprintf(stderr, "Usage: %s 0|1|2|3 0|1n", argv[0]);
fprintf(stderr, "Ex : %s 0 1n", argv[0]);
exit(1);
}
fd = open("/dev/leds", 0);
if (fd < 0)
{
perror("open device leds");
exit(1);
}
if (on)
{
// printf("Turn on led %d!n", num);
ioctl(fd, MEMDEV_IOC_ON, num);
}
else
{
// printf("Turn off led %d!n", num);
ioctl(fd, MEMDEV_IOC_OFF, num);
}
close(fd);
-
return 0;