/* 
 * Project name:
     HID_Read_Write (USB HID Read & Write Test)
 * Copyright:
     (c) Mikroelektronika, 2012.
 * Revision History:
     20120810:
       - initial release (FJ);
 * Description:
     This example establishes connection with the HID terminal that is active
     on the PC. Upon connection establishment, the HID Device Name will appear
     in the respective window. The character that user sends to PIC from the HID
     terminal will be re-sent back to user.
 * Test configuration:
     MCU:             P33EP512MU810
                      http://ww1.microchip.com/downloads/en/DeviceDoc/70616F.pdf
     Dev.Board:       EasyPIC Fusion v7 - ac:USB
                      http://www.mikroe.com/easypic-fusion/
     Oscillator:      XT-PLL, 140.0000MHz
     Ext. Modules:    None.
     SW:              mikroC PRO for dsPIC
                      http://www.mikroe.com/eng/products/view/231/mikroc-pro-for-dspic/
 * NOTES:  
     - None.
 */

char cnt;
char readbuff[64];
char writebuff[64];

void USB1Interrupt() iv IVT_ADDR_USB1INTERRUPT{
  USB_Interrupt_Proc();
}

void main(void){
  int Count = 0;
  TRISB.RB0 = 0; PORTB.RB0 = 0;
  // Setting output frequency to 140MHz
  PLLFBD = 70;             // PLL multiplier M=70
  CLKDIV = 0x0000;         // PLL prescaler N1=2, PLL postscaler N2=2

  // Setring USB frequency to 48MHz
     // Using primary oscillator (8MHz) with APLL
  ACLKCON3 = 0xB4C1;       // Use primary oscillator (8MHz), APLL prescaler N1=2, APLL postscaler N2=2
  ACLKDIV3 = 0x0007;       // APLL multiplier M=24

  ANSELA = 0x00;           // Convert all I/O pins to digital
  ANSELB = 0x00;
  ANSELC = 0x00;
  ANSELD = 0x00;
  ANSELE = 0x00;
  ANSELG = 0x00;

  HID_Enable(&readbuff,&writebuff);

  while(1){
    while(!HID_Read())
      ;

    for(cnt=0;cnt<64;cnt++)
      writebuff[cnt]=readbuff[cnt];
      
      LATB.RB0 = readbuff[63];
      writebuff[0] = ++Count;

    while(!HID_Write(&writebuff,64))
      ;
  }
}