LED程序


功能:实现A9实验系统中8个LED灯按顺序依次亮灭。


ledx.c
#include"ledx.h"
 
int main(int argc, char const *argv[])
{
	int fd;	
	fd = port_open(); 
 
	while(1) 
	{	
		if ( (port_write(16, fd)) < 0 ) 
		{
			exit(1); 
		}
		else
		{
			/* 以下往GPX0_DAT寄存器写值,注意先要设置GPX0_DAT的地址 */
			*GPX0_DAT = 0xFE;
			printf("LED1\n"); 
			sleep(1);
			*GPX0_DAT = 0xFD;
			printf("LED2\n"); 
			sleep(1);
			*GPX0_DAT = 0xFB;
			printf("LED3\n"); 
			sleep(1);
			*GPX0_DAT = 0xF7;
			printf("LED4\n"); 
			sleep(1);
			*GPX0_DAT = 0xEF;
			printf("LED5\n"); 
			sleep(1);
			*GPX0_DAT = 0xDF;
			printf("LED6\n"); 
			sleep(1);
			*GPX0_DAT = 0xBF;
			printf("LED7\n"); 
			sleep(1);
			*GPX0_DAT = 0x7F;
			printf("LED8\n"); 
			sleep(1);
		}
	}
 
	port_close(16, fd);
	return 0;
}

ledx.h
#include<stdio.h>
#include<stdlib.h> 
#include<fcntl.h> 			
#include<sys/mman.h> 		
#include<unistd.h> 		
 
#define DEV_NAME 	"/dev/mem"
#define BaseAddress 	0x11000000	
#define GPX0CON_OFFSET 	0x0C00		
#define GPX0DAT_OFFSET 	0x0C04		
#define GPX0_WR_CON 	0x11111111	
 
volatile void *Addr_start = NULL; 
volatile unsigned *GPX0_DAT = NULL; 
 
/************************ 内存映射+寄存器地址确定 ***************************/
int port_write( unsigned n, unsigned fd) 
{
 
	Addr_start = (volatile void *)mmap(NULL, 1024*n, PROT_READ | PROT_WRITE, MAP_SHARED, fd, BaseAddress);
 
	if (Addr_start == NULL) 
	{
		printf("内存映射出错!\n");
		return -1;
	}
 
	*(volatile unsigned *)(Addr_start+GPX0CON_OFFSET) = GPX0_WR_CON;
 
	GPX0_DAT = (volatile unsigned *)(Addr_start+GPX0DAT_OFFSET);
	return 0;
}
 
/********************* 打开一个设备文件,标志符为fd ***************************/
int port_open()
{
	int fd;
	fd = open(DEV_NAME, O_RDWR);
	if ( fd < 0 ) 
	{
		exit(1);
	}
	return fd;
}
 
/************************ 关闭标志符为fd的设备文件 ***************************/
int port_close(int n, int fd)
{
	munmap( (void *)Addr_start, 1024*n ); 
	close(fd);
	return 0;
}

makefile
CC		= arm-linux-gcc
INSTALL		= install
TARGET		= ledx
 
all : $(TARGET)
 
$(TARGET):ledx.c ledx.h
	$(CC) -static $< -o $@
 
clean :
	rm -rf *.o $(TARGET)