创建led_mod.c、ledApp.c文件,并编写程序。这里程序参考《正点原子ZYNQ-LED开发实验教程》,有所不同的是这里由于使用AXI-GPIO,控制设备时无需配置寄存器等,获取地址后直接写入、读取即可。
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/delay.h>
#include <linux/ide.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/errno.h>
#include <linux/gpio.h>
#include <asm/mach/map.h>
#include <asm/uaccess.h>
#include <asm/io.h>
#define LED_MAJOR 200
#define LED_NAME "axi-led"
#define ZYNQ_AXI_GPIO_0_BASE 0x41210000
static void __iomem *data_addr;
static int led_open(struct inode *inode, struct file *filp)
{
return 0;
}
static ssize_t led_read(struct file *filp, char __user *buf,
size_t cnt, loff_t *offt)
{
return 0;
}
static ssize_t led_write(struct file *filp, const char __user *buf,
size_t cnt, loff_t *offt)
{
int ret;
int val;
char kern_buf[1];
ret = copy_from_user(kern_buf, buf, cnt);
if(0 > ret) {
printk(KERN_ERR "kernel write failed!\r\n");
return -EFAULT;
}
val = readl(data_addr);
printk("write-read:0x%x\r\n", val);
val = kern_buf[0];
printk("write 0x%x now\r\n", val);
writel(val, data_addr);
return 0;
}
static int led_release(struct inode *inode, struct file *filp)
{
return 0;
}
static struct file_operations led_fops = {
.owner = THIS_MODULE,
.open = led_open,
.read = led_read,
.write = led_write,
.release = led_release,
};
static int __init led_init(void)
{
u32 val;
int ret;
data_addr = ioremap(ZYNQ_AXI_GPIO_0_BASE, 4);
ret = register_chrdev(LED_MAJOR, LED_NAME, &led_fops);
if(0 > ret){
printk(KERN_ERR "Register LED driver failed!\r\n");
return ret;
}
printk("led-mod init now\r\n");
return 0;
}
static void __exit led_exit(void)
{
unregister_chrdev(LED_MAJOR, LED_NAME);
iounmap(data_addr);
printk("led-mod exit\r\n");
}
module_init(led_init);
module_exit(led_exit);
MODULE_AUTHOR("mlia");
MODULE_DESCRIPTION("ZYNQ AXI-GPIO LED Test Driver");
MODULE_LICENSE("GPL");
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[])
{
int fd, ret;
unsigned char buf[1];
if(3 != argc) {
printf("Usage:\n"
"\t./ledApp /dev/led 1 @ close LED\n"
"\t./ledApp /dev/led 0 @ open LED\n"
);
return -1;
}
fd = open(argv[1], O_RDWR);
if(0 > fd) {
printf("file %s open failed!\r\n", argv[1]);
return -1;
}
buf[0] = atoi(argv[2]);
ret = write(fd, buf, sizeof(buf));
if(0 > ret){
printf("LED Control Failed!\r\n");
close(fd);
return -1;
}
close(fd);
return 0;
}