//* ****************************************************************************
//
//    210623 UART LM35
//
//    PIC16F18345, LM35 (0.01V/degC)
//
//    2021/06/23
//
//    inja
//
//* ****************************************************************************

#include    <16f18345.h>
#device     ADC=10
#fuses      HS,NOMCLR
#use        delay (clock = 20000000)
    
//******************************************************************************
//*** Declear Pin for UART Communication ***************************************
#pin_select      U1TX = PIN_B7
#pin_select      U1RX = PIN_B5
#use             rs232 (baud=19200, parity=N, xmit=PIN_B7, rcv=PIN_B5)
    
float read_temp (void)                             //* ADC 10bit, VREF_ADC_1v024
{   int16   adc_value, volt_mv ;
    int8    idx_avg ;
    int32   sum_value ;
    float   ret_temp ;
 
    sum_value = 0 ;
    for (idx_avg = 0;idx_avg <= 9;idx_avg++) {        
        sum_value = sum_value + read_adc () ;
    }
    adc_value = sum_value / 10 ;

    volt_mv = (float)adc_value * (1024. / 1023.) ;
    ret_temp = (float)volt_mv / 10 ;                //* volt_mv = 0mV + 10.0mV/C

    return (ret_temp) ;
}

//*** Start Main Function ******************************************************
void main (void)
{   float   temp ;
    
    delay_ms (1000) ;
    setup_adc_ports (sAN2, VSS_FVR) ;
    setup_vref (VREF_ON | VREF_ADC_1v024) ;         //* set voltage refernce (1.024V))
    setup_adc (ADC_CLOCK_INTERNAL) ;
    set_adc_channel (2) ;

    printf ("** LM35 Test **\n") ;

    while (1) {
        temp = read_temp () ;
        printf ("Temp: %4.1f C \n", temp) ; 
        delay_ms (500) ;
    }
}
//******************************************************************************