/* THIS IS THE FILE THAT writes to LEDs and reads from switches..linux
 * Copyright (c) 2012 Xilinx, Inc.  All rights reserved.
 *
 * Xilinx, Inc.
 * XILINX IS PROVIDING THIS DESIGN, CODE, OR INFORMATION "AS IS" AS A
 * COURTESY TO YOU.  BY PROVIDING THIS DESIGN, CODE, OR INFORMATION AS
 * ONE POSSIBLE   IMPLEMENTATION OF THIS FEATURE, APPLICATION OR
 * STANDARD, XILINX IS MAKING NO REPRESENTATION THAT THIS IMPLEMENTATION
 * IS FREE FROM ANY CLAIMS OF INFRINGEMENT, AND YOU ARE RESPONSIBLE
 * FOR OBTAINING ANY RIGHTS YOU MAY REQUIRE FOR YOUR IMPLEMENTATION.
 * XILINX EXPRESSLY DISCLAIMS ANY WARRANTY WHATSOEVER WITH RESPECT TO
 * THE ADEQUACY OF THE IMPLEMENTATION, INCLUDING BUT NOT LIMITED TO
 * ANY WARRANTIES OR REPRESENTATIONS THAT THIS IMPLEMENTATION IS FREE
 * FROM CLAIMS OF INFRINGEMENT, IMPLIED WARRANTIES OF MERCHANTABILITY
 * AND FITNESS FOR A PARTICULAR PURPOSE.
 *
 */

#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
#include <string.h>
#include <sys/types.h>
#include <sys/mman.h>


int main()
{
	volatile unsigned int *leds;
	volatile unsigned int *switches;
	volatile unsigned int *buttons;

	unsigned int leds_val = 0;
	unsigned int switches_val = 0;
	unsigned int buttons_val = 0;

	int i = 0;

	int fd = open("/dev/mem", O_RDWR|O_SYNC);

	if (fd < 0) {
		printf("Error...");
		exit (1);
	}

    printf("Hello World! \n");
    printf("This program will run an infinite loop. \r\n");
    printf("To end the program, press any of the five directional buttons. \r\n");

	switches = mmap(0, getpagesize(), PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0x41200000);
	printf("Switches mmap Good... \r\n");

	leds = mmap(0, getpagesize(), PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0x41220000);
	printf("LEDs mmap Good... \r\n");

	buttons = mmap(0, getpagesize(), PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0x41240000);
	printf("Buttons mmap Good... \r\n");

	while(1){
		switches_val = *switches;
		buttons_val = *buttons;

		printf("Readback value of the switches is %x \r\n", switches_val);
		*leds = switches_val;

		if (buttons_val != 0){
			break;
		}

		for (i = 0; i < 99999; i++){}
	}

	printf("BYE! \r\n");
    return 0;
}