#include <18F4550.h>

#fuses HSPLL,NOMCLR,NOWDT,NOPROTECT,NOLVP,NODEBUG,USBDIV,PLL5,CPUDIV1,VREGEN

#use delay (clock=48 000 000)
#use rtos (timer=0, minor_cycle=10ms)

//#define USB_CON_SENSE_PIN PIN_E3  //pin de MCLR

#define LED_D1 PIN_D0
#define LED_D2 PIN_D1
#define LED_D3 PIN_D2
#define LED_D4 PIN_D3
#define USB_CON_SENSE_PIN PIN_A1
#define BUTTON_PRESSED_S1() !input(PIN_E3)
#define BUTTON_PRESSED_S2() !input(PIN_B4)
#define BUTTON_PRESSED_S3() !input(PIN_B5)

#define USB_CONFIG_VID  0x0461//0x1234//0x0461
#define USB_CONFIG_PID  0x0030//0x5678//0x0030
#define USB_CONFIG_HID_TX_SIZE   32
#define USB_CONFIG_HID_RX_SIZE   32

#include <pic18_usb.h>   //Microchip PIC18Fxx5x hardware layer for usb.c
#include <usb_desc_hid.h>   //USB Configuration and Device descriptors for this UBS device
#include <usb.c>        //handles usb setup tokens and get descriptor reports

float Temperatura;
int8 in_data[32], out_data[32];

#task (rate=500ms, max=10ms)
void Tarea_GetTemp ();

#task (rate=100ms, max=10ms)
void Tarea_LED_USBConectado ();

#task (rate=10ms, max=10ms)
void Tarea_USB ();

#task (rate=1s, max=10ms)
void Tarea_USB_EnviarTemperatura ();

void main (void) 
{   
   output_d(0x00); 
      
   usb_init_cs();

   rtos_run();
}

void Tarea_LED_USBConectado ( ) 
{
   rtos_await(usb_enumerated());
   output_toggle(LED_D4); 
}

void Tarea_USB ()
{
   usb_task();

   if (usb_enumerated()) 
   {
   
      rtos_enable(Tarea_USB_EnviarTemperatura);
      
      if (usb_kbhit(1)) 
      {  
         usb_get_packet(1, in_data, 32);
            
         if (in_data[1] == 0x0A)
         {
            switch (in_data[2])
            {
               case 0x10: output_toggle(LED_D1); break;
               case 0x20: output_toggle(LED_D2); break;
               case 0x30: output_toggle(LED_D3); break;
            }
         }     
      }
   }
   else
   {
      rtos_disable(Tarea_USB_EnviarTemperatura);
   }
}

void Tarea_USB_EnviarTemperatura ()
{
      out_data[0] = (int8)1;
      out_data[1] = (int8)2;
      out_data[2] = (int8)3;
      out_data[3] = (int8)4;  
      usb_put_packet(1, out_data, 32, USB_DTS_TOGGLE);
}



void Tarea_GetTemp ()
{
   Temperatura = 20.5;
}

