5.到这一步我们驱动程序就写好了
老规矩,makefile,make,拷贝到开发板,insmod led.ko
6.编写测试程序
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
int main(int argc, char **argv)
{
int fd;
int val = 1;
fd = open("/dev/xyz", O_RDWR);
if (fd < 0)
{
printf("can't open!\n");
}
if (argc != 2)
{
printf("Usage :\n");
printf("%s <on|off>\n", argv[0]);
return 0;
}
if (strcmp(argv[1], "on") == 0)
{
val = 1;
}
else
{
val = 0;
}
write(fd, &val, 4);
return 0;
}
编译,拷贝到开发板
./led_test on
1
灯全亮
谈一谈注册字符设备:
major = register_chrdev(0, "led", &led_fops);
//int register_chrdev(unsigned int major, const char *name,const struct file_operations *fops)
1
2
这个函数没有指定次设备号,所以主设备号下的所有次设备号(0~255)都是对应这个led_fops,非常的霸道,但是我喜欢
major:主设备号,如果写0,则让内核自动分配主设备号
name:名字
fops:自己编写的fops
******ledc.c*******
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/fs.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <asm/uaccess.h>
#include <asm/irq.h>
#include <asm/io.h>
#include <asm/arch/regs-gpio.h>
#include <asm/hardware.h>
static struct class *led_class;
static struct class_device *led_class_dev;
volatile unsigned long *gpfcon = NULL;
volatile unsigned long *gpfdat = NULL;
static int led_open(struct inode *inode, struct file *file)
{
*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_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_fops = {
.owner = THIS_MODULE,
.open = led_open,
.write = led_write,
};
int major;
static int led_init(void)
{
major = register_chrdev(0, "led_drv", &led_fops);
firstdrv_class = class_create(THIS_MODULE, "leddrv");
firstdrv_class_dev = class_device_create(led_class,NULL, MKDEV(major, 0), NULL, "xyz"); /* /dev/xyz */
gpfcon = (volatile unsigned long *)ioremap(0x56000050, 16);
gpfdat = gpfcon + 1;
return 0;
}
static void first_drv_exit(void)
{
unregister_chrdev(major, "led_drv");
class_device_unregister(led_class_dev);
class_destroy(led_class);
iounmap(gpfcon);
}
module_init(led_init);
module_exit(led_exit);
MODULE_LICENSE("GPL"); |