/************************************************/
/* Demo Program For ET-BASE PIC40/1939(ICSP)    */
/* MCU Control : PIC16F1939                     */
/*             : Run 32MHz(Internal 8MHz + PLL) */
/* Compiler    : PIC-CCS Version 4.120          */
/* Function    : Demo ADC Display UART1(RS232)  */
/************************************************/
#include <16F1939.h>
#include <stdlib.h>

// Fuses: PIC16F1939(CCS Compiler)
// Fuses: LP,XT,HS,RC,INTRC_IO,ECL,ECM,ECH,NOWDT,WDT_SW,WDT_NOSL,WDT
// Fuses: PUT,NOPUT,NOMCLR,MCLR,PROTECT,NOPROTECT,CPD,NOCPD,NOBROWNOUT
// Fuses: BROWNOUT_SW,BROWNOUT_NOSL,BROWNOUT,CLKOUT,NOCLKOUT,NOIESO
// Fuses: IESO,NOFCMEN,FCMEN,WRT,WRT_EECON2000,WRT_EECON200,NOWRT
// Fuses: VCAP_A0,VCAP_A5,VCAP_A6,NOVCAP,PLL_SW,PLL,NOSTVREN,STVREN
// Fuses: BORV25,BORV19,DEBUG,NODEBUG,NOLVP,LVP

//Select Jumper RA6,RA7(XTAL/GPIO) = XTAL
//#fuses   HS,PLL,NOWDT,NOPROTECT,NOLVP                                       // X-TAL 8MHz + PLL(x4)
//#use     delay(clock=32000000)                                              // 32.00 MHz

//Select Jumper RA6,RA7(XTAL/GPIO) = GPIO
#fuses   INTRC_IO,PLL,NOWDT,NOPROTECT,NOLVP                                   // Internal RC Clock 8MHz + PLL(4)
#use     delay(clock=32000000)                                                // 32.00 MHz

/* Config and Enable Hardware UART1(RC6=TX1,RC7=RX1 */
#use rs232(uart1, baud=9600)

//ADC0:RA0:VR1 -> Demo Test ADC
#define ADC0_PIN    PIN_A0                                                    //ADC0(VR1)

//LED Barfraph Display Scale ADC Result
const unsigned char LED[8] =
{
  0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F, 0xFF                              // 8 Bit LED Test
};

/****************/
/* Main Program */
/****************/
void main() 
{ 
  int8 AN0_Value;
  
  setup_oscillator(OSC_8MHZ|OSC_PLL_ON);                                      //Sets the Internal Oscillator to 32MHz (PLL Enabled)  
  delay_ms(500);
  output_float(ADC0_PIN);                                                     // ADC Input
  setup_adc_ports(sAN0);                                                      // Assign Analog pin
  setup_adc(ADC_CLOCK_INTERNAL);                                      
  
  //Used RD[7..0]= Bargraph Display
  set_tris_d(0b00000000);                                                     // RD[7..0]=Output
  
  printf("\n\n\n\r");
  printf("Demo ADC ET-BASE PIC40/1939(ICSP)\n\r");
  printf("Run 32MHz(Internal 8MHz + PLL[4])\n\n\r");  
  
  while(true)
  { 
    set_adc_channel(0);                                                       // Select Channel AN0
    delay_us(10);                                                             // Wait Multiplex Stable     
    AN0_Value = read_adc();                                                   // Read adc channel 0 

    printf("ADC[0] : AN0 = %3u \r",AN0_Value);
    output_d(~LED[AN0_Value/32]);
    delay_ms(250);
  }  
}

