#include <xc.h>
#include "config_bits.h"
void setupClock(void);
void configurarADC(void);
void configurarUSART(void);
void interrupt ADC_int(void);
unsigned int lecturaADC;
void main(void) {
setupClock(); // configuramos oscilador interno a 8 MHz
configurarADC(); // configuramos modulo ADC
configurarUSART(); // configuramos el modulo USART
INTCONbits.PEIE = 1; // activamos interrupcion de perifericos
PIE1bits.ADIE = 1; // habilitamos interrupcion de A/D
INTCONbits.GIE = 1; // activamos interrupcion global
while(1){
TXSTAbits.TXEN = 1; // habilitamos transmision
ADCON0bits.ADON = 1; // habilitamos el modulo ADC
ADCON0bits.GO_DONE = 1; // iniciamos la conversion
}
}
void setupClock(){
OSCCONbits.IRCF0 = 1;
OSCCONbits.IRCF1 = 1;
OSCCONbits.IRCF2 = 1;
OSCCONbits.SCS = 0b10;
}
void configurarADC(){
ADCON1bits.PCFG = 0b1110; // configuramos AN0 como entrada analogica
ADCON1bits.VCFG = 0b00; // seleccionamos voltajes de referencia (Vdd, Vss)
ADCON0bits.CHS = 0b0000; // seleccionamos canal analogico
ADCON2bits.ACQT = 0b010; // tiempo de adquisicion (4Tad)
ADCON2bits.ADCS = 0b001; // tiempo de conversion (Fosc/8)
ADCON2bits.ADFM = 0; // justificacion a la izquierda
//ADCON0bits.ADON = 1; // habilitamos el modulo ADC
}
void interrupt ADC_int(void){ //rutina de atención a las interrupciones
if(PIR1bits.ADIF == 1){ // ha ocurrido una interrupcion
ADCON0bits.ADON = 0; // desactivamos el ADC
lecturaADC = ADRESH; // leemos el valor del ADC
//lecturaADC = (lecturaADC << 8)+ADRESL;
while(TXSTAbits.TRMT==0);// mientras el registro TSR esté lleno espera
TXREG = lecturaADC;//cuando el registro TSR está vacio se envia la conversion
PIR1bits.ADIF = 0; // limpiamos bandera de interrupcion
}
}
void configurarUSART()
{
TRISCbits.RC6 = 0; // configuramos TX como salida
//TRISCbits.RC7 = 1; // configuramos RX como entrada
TXSTAbits.SYNC = 0; // habilitamos modo asincrono
TXSTAbits.BRGH = 1;
BAUDCONbits.BRG16 = 0; // configuramos para alta velocidad
SPBRG = 51; // 9600 baud
RCSTAbits.SPEN = 1; // habilitamos el puerto serie
TXSTAbits.TX9 = 0; // seleccionamos tx a 8 bits
//TXSTAbits.TXEN = 1; // habilitamos transmision
}