10 Eylül 2017 Pazar

ADC: How to convert analog voltage to digital and show on LCD


Analog to digital conversion example:

MCC: Set RA0 pin as analog and PORTB pins as output. disable MCLR. 
select ADC peripheral and set reference voltages to VDD and VSS. Generate MCC files. you can look at adc.h to see possible ADC functions and examples. Depending on version and compiler there are many different examples which may not work for you. I am using XC8 version 1.43 OSC clocks also creating unexpected results, for this example I used 8MHz for internal osc, and FOSC/8 for ADC and 8 for acq time.



Proteus: connect a variable pot to RA0. We will measure the voltage and display the value on LCD. you can look how to use LCD example at this blog.

XC8: 
I included stdio.h for sprintf() function, so include files:

#include "mcc_generated_files/mcc.h"
#include "myxlcd.h"
#include "delays.h"
#include <stdio.h>

and the program. ADC is 10 bit converter but converted value cV is 16 bit number, thus I divide to 65536=2^16 and multiply by 5V. sprintf() converts the number to string to display on LCD. That's all.


  unsigned char v[12];
    uint16_t cV = 0;
    float  volt;

    
    void main(void)
{
    SYSTEM_Initialize();
    
    while (1)
    {
        
        ADC_StartConversion(channel_AN0);
        while(!ADC_IsConversionDone());
        cV = ADC_GetConversionResult(); 
        volt=cV*5.0/65536;
        sprintf(v, "%.1f", volt); 
        

        OpenXLCD(FOUR_BIT & LINES_5X7);
        WriteCmdXLCD(DON&CURSOR_OFF&BLINK_OFF); 
        while(BusyXLCD());
        putrsXLCD("LCD Voltmeter");
        SetDDRamAddr(0x40); // goto second line
        while(BusyXLCD());
        putrsXLCD("Voltage=");putrsXLCD(v);putrsXLCD("V");
        __delay_ms(500);

        
    }
}

download the example

Hiç yorum yok:

Yorum Gönder