#include #include #include #include /* Set up the configuration bits */ #pragma config OSC = HS #pragma config PWRT = OFF #pragma config BOR = OFF #pragma config WDT = OFF #pragma config LVP = OFF #define HIGH_LIMIT 200 #define LOW_LIMIT 80 // This program switches on the LED when the value read by the // A/D module is between LOW_LIMIT and HIGH_LIMIT. void usart_setup(void) { /* Configure all PORTB pins for output */ TRISB = 0; /* * Open the USART configured as * 8N1, 9600 baud. */ OpenUSART (USART_TX_INT_OFF & USART_RX_INT_OFF & USART_ASYNCH_MODE & USART_EIGHT_BIT & USART_SINGLE_RX & USART_BRGH_HIGH, 129); } void io_port_setup(void) { // RE2 for input and RE1 for output; TRISE = 0b00000100; // RE1 (LED) is on; PORTE = 0b00000010; // RA0 for input; TRISA = 0b00000001; // Select AN0 as Anolog and AN6/7 (RE1/2) as digital // We are using the internal reference (VDD) // PCFG3:0 = 0010 ADCON1 = 0b00001001; // Result is left aligned in ADRESH ADCON1bits.ADFM = 0; // Conversion clock set to Fosc/32 (ADCS2:0 = 010) // Fosc = 20Mhz ADCON1bits.ADCS2 = 0; ADCON0bits.ADCS1 = 1; ADCON0bits.ADCS0 = 0; // We are sampling AN0: CHS2:0 = 000 // ADCON0 = ((ADCON0 & 0b11100011) | 0b00000000); ADCON0bits.CHS2 = 0; ADCON0bits.CHS1 = 0; ADCON0bits.CHS0 = 0; // Powering the module ADCON0bits.ADON = 1; // acquisition delay? // Starting the fist conversion ADCON0bits.GO = 1; } void main( void) { // setup the ports io_port_setup(); // setup the USART usart_setup(); // Loop forever while (1) { while (ADCON0bits.GO == 1); // conversion in progress if ((ADRESH > HIGH_LIMIT) || (ADRESH < LOW_LIMIT)) { PORTEbits.RE1 = 0; } else { PORTEbits.RE1 = 1; } // print the current value printf("Current value: %d \r", ADRESH); // aquisition delay? // Start a new conversion ADCON0bits.GO = 1; } }