

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

#include "jz47xx_gpio.c"
#include "jz47xx_mmap.c"

#define CS2_PORT JZ_GPIO_PORT_B
#define CS2_PIN  26

int
main ()
{
#ifdef DOUBLE
  set_fpu (0x27F);  /* use double-precision rounding */
#endif

  int i;
  int pwm1=0xFF;		//PWM Led en SIE, entre 0 y 255
  int pwm2=0xFF;		//PWM Led fuera SIE, entre 0 y 255
  int pwm3=0xFF;		//PWM Led en SIE, entre 0 y 255
  int pwm4=0xFF;		//PWM Led fuera SIE, entre 0 y 255

  int dutycycle1;		//PWM Led en SIE
  int dutycycle2;		//PWM Led fuera SIE
  int dutycycle3;		//PWM Led en SIE
  int dutycycle4;		//PWM Led fuera SIE

  JZ_PIO *pio;
  int *virt_addr;

  // Set GPIOB26 as part of External Memory Controller
  pio = jz_gpio_map (CS2_PORT);
  jz_gpio_as_func (pio, CS2_PIN, 0);

  virt_addr = (int *) jz_mmap (0x13010000) + 0x18;

  printf ("\nIniciado: \nPrueba Beta Alpha3 UNROBOT \n");

  if (*virt_addr != 0xFFF7700)
    {                           // 0 WS, 8 bits
      *virt_addr = 0xFFF7700;
      printf ("Configuring CS2 8 bits \n");
    }
  else
    printf ("CS2, already configured\n");

  virt_addr = (int *) jz_fpga_map (0x14000000);

 dutycycle1=(int)((float)((100.0/255.0)*pwm1));
 dutycycle2=(int)((float)((100.0/255.0)*pwm2));
 dutycycle3=(int)((float)((100.0/255.0)*pwm3));
 dutycycle4=(int)((float)((100.0/255.0)*pwm4));


  printf ("DUTY1:%d%% \n", dutycycle1);
  printf ("DUTY2:%d%% \n", dutycycle2);
  printf ("DUTY3:%d%% \n", dutycycle3);
  printf ("DUTY4:%d%% \n", dutycycle4);


  printf ("Setting PWM..\n");
     virt_addr[1024] = pwm1+(pwm2<<8)+(pwm3<<16)+(pwm4<<24);//0xFFFFFFFF Cada dos digitos es un PWM
  usleep (1000 * 1000);


  printf ("Writing In Memory1 the Dutycycles and pwm references from 0x100 to 0x103..\n");

	virt_addr[1536] = pwm1;
	virt_addr[1537] = dutycycle1;
	virt_addr[1538] = pwm2;
	virt_addr[1539] = dutycycle2;	
	virt_addr[1540] = pwm3;
	virt_addr[1541] = dutycycle3;
	virt_addr[1542] = pwm4;
	virt_addr[1543] = dutycycle4;

  printf ("Reading from Memory1 the Dutycycles and pwm references..\n");

    printf("1- PWM_REF:%d, Duty Cycle:%d%% \n", virt_addr[1536], virt_addr[1537]);
    printf("2- PWM_REF:%d, Duty Cycle:%d%% \n", virt_addr[1538], virt_addr[1539]);
    printf("1- PWM_REF:%d, Duty Cycle:%d%% \n", virt_addr[1540], virt_addr[1541]);
    printf("2- PWM_REF:%d, Duty Cycle:%d%% \n", virt_addr[1542], virt_addr[1543]);

    printf("1- Encoder1:%d\n", virt_addr[0]);
    printf("1- Encoder2:%d\n", virt_addr[512]);

  return 0;
}
