#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
int main ()
{
	int exportfd;
	int valuefd_led, value_pin, valuefd_but1, valuefd_but0;
	int directionfd_led, directionfd_pin, directionfd_but0, directionfd_but1;
	char read_value0, read_value1 ;
	int counter = 0;
//Export GPIO ports
	exportfd = open ( "/sys/class/gpio/export" , O_WRONLY );
	if ( exportfd < 0)
	{
		printf ( "Cannot open GPIO to export it \n");
		exit (1);
	}
		write ( exportfd , "913" , 4);	// base_address + led_addres. 906+7 = 913
		write ( exportfd , "919" , 4);	// base_address + led_addres. 906+13 = 919
		write ( exportfd , "956" , 4);	// base_address + button_addres. 906+50 = 956
		write ( exportfd , "957" , 4);	// base_address + button_addres. 906+51 = 957
		close ( exportfd );

		printf ( "GPIO exported successfully \n " );

// Set the direction of the GPIO as an output or input
		directionfd_led = open  ( "/sys/class/gpio/gpio913/direction" , O_RDWR );
		directionfd_pin = open  ( "/sys/class/gpio/gpio919/direction" , O_RDWR );
		directionfd_but0 = open ( "/sys/class/gpio/gpio956/direction" , O_RDWR );		
		directionfd_but1 = open ( "/sys/class/gpio/gpio957/direction" , O_RDWR );		
	if ( directionfd_led < 0)
	{
		printf ( " Cannot open GPIO direction it \n " );
		exit (1);
	}
		write ( directionfd_led , "out" , 4);
		close ( directionfd_led );
	if ( directionfd_pin < 0)
	{
		printf ( " Cannot open GPIO direction it \n " );
		exit (1);
	}
		write ( directionfd_pin , "in" , 3);
		close ( directionfd_pin);	
	if ( directionfd_but0 < 0)
	{
		printf ( " Cannot open GPIO direction it \n " );
		exit (1);
	}
		write ( directionfd_but0 , "in" , 3);
		close ( directionfd_but0);
	if ( directionfd_but1 < 0)
	{
		printf ( " Cannot open GPIO direction it \n " );
		exit (1);
	}
		write ( directionfd_but1 , "in" , 3);
		close ( directionfd_but1 );
			


printf ( " GPIO direction set to led, pin JF1, button 0 and button 1 as output successfully \n" );
		
	
	/* Get the GPIO handler */
		valuefd_led = open ( "/sys/class/gpio/gpio913/value" , O_RDWR );
		value_pin = open ( "/sys/class/gpio/gpio919/value" , O_RDWR );
		valuefd_but0 = open ( "/sys/class/gpio/gpio956/value" , O_RDWR );
		valuefd_but1 = open ( "/sys/class/gpio/gpio957/value" , O_RDWR );
	if ( valuefd_led < 0)
	{
		printf ( " Cannot open GPIO value \n " );
		exit (1);
	}
	if ( value_pin < 0)
	{
		printf ( " Cannot open GPIO value 957\n " );
		exit (1);
	}
	if ( valuefd_but0 < 0)
	{
		printf ( " Cannot open GPIO value 956 \n " );
		exit (1);
	}
	if ( valuefd_but1 < 0)
	{
		printf ( " Cannot open GPIO value 957\n " );
		exit (1);
	}
	

while (1)
	{
		write(valuefd_led, "1",2);		//Write the led value
		write(valuefd_pin, "1",2);		//Write the pin value
//poll button status
		lseek(valuefd_but0 ,0,SEEK_SET);
		read(valuefd_but0, &read_value0,1);
		lseek(valuefd_but1 ,0,SEEK_SET);
		read(valuefd_but1, &read_value1,1);

		printf("but_0 = %d but_1 = %d \n", read_value0, read_value1); //Buttons status


	}
}
