你好!这里是风筝的博客,
欢迎和我一起交流。
//应用程序:
#include
#include
#include
#include
/* leddrvtest on
* leddrvtest off
*/
int main(int argc, char **argv)
{
int fd;
int val = 1;
fd = open("/dev/led", O_RDWR);
if (fd < 0)
{
printf("can't open!\n");
}
if (argc != 2)
{
printf("Usage :\n");
printf("%s \n", argv[0]);
return 0;
}
/*如果输入了leddrvtest on*/
if (strcmp(argv[1], "on") == 0)
val = 1;
else
val = 0;
/*写val*/
write(fd, &val, 4);
return 0;
}
//驱动程序:
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
static struct class *leddrv_class;
static struct class_device *leddrv_class_dev;
volatile unsigned long *gpfcon = NULL;
volatile unsigned long *gpfdat = NULL;
static int led_drv_open(struct inode *inode, struct file *file)
{
/* 配置GPF4,5,6为输出 */
*gpfcon &= ~((0x3<<(4*2)) | (0x3<<(5*2)) | (0x3<<(6*2)));
*gpfcon |= ((0x1<<(4*2)) | (0x1<<(5*2)) | (0x1<<(6*2)));
return 0;
}
static ssize_t led_drv_write(struct file *file, const char __user *buf, size_t count, loff_t * ppos)
{
int val;
copy_from_user(&val, buf, count); // copy_to_user();
if (val == 1)
{
// 点灯
*gpfdat &= ~((1<<4) | (1<<5) | (1<<6));
}
else
{
// 灭灯
*gpfdat |= (1<<4) | (1<<5) | (1<<6);
}
return 0;
}
static struct file_operations led_drv_fops = {
.owner = THIS_MODULE, /* 这是一个宏,推向编译模块时自动创建的__this_module变量 */
.open = led_drv_open,
.write = led_drv_write,
};
int major;
/*insmod 时调用*/
static int led_drv_init(void)
{
major = register_chrdev(0, "led_drv", &led_drv_fops); // 注册, 告诉内核
leddrv_class = class_create(THIS_MODULE, "leddrv");
leddrv_class_dev = device_create(leddrv_class, NULL, MKDEV(major, 0), NULL, "led"); /* /dev/led */
gpfcon = (volatile unsigned long *)ioremap(0x56000050, 16);
gpfdat = gpfcon + 1;
return 0;
}
/*rmmod 时调用*/
static void led_drv_exit(void)
{
unregister_chrdev(major, "led_drv"); // 卸载
device_destroy(leddrv_class,MKDEV(major, 0));
class_destroy(leddrv_class);
iounmap(gpfcon);
}
module_init(led_drv_init);
module_exit(led_drv_exit);
MODULE_LICENSE("GPL");