/* ADC and Serial UART Test Program Date: 7-21-05 Author: Evan Dudzik This program is an example of interfacing with two pieces of hardware within the PIC: the analog to digital converter, and the UART, as well as using interrupts. The program continuously reads the ADC value, and when it changes, outputs it via serial. The output can be either a single character (0-255), or encoded to ASCII decimal for easy viewing in a terminal, by simply commenting out the appropriate line in the main function. As a simple test, the program also echos recieved characters back to the host. This way you can type in a terminal program to check the serial communication. */ #include #pragma DATA 0x2007, 0x3F50//_INTRC_IO & _WDT_OFF & _LVP_OFF //important bits in SFR's for ADC, UART, and interrupt. volatile bit go @ ADCON0.GO; volatile bit gie @ INTCON.GIE; volatile bit rcie @ PIE1.RCIE; volatile bit peie @ INTCON.PEIE; volatile bit rcif @ PIR1.RCIF; volatile bit trmt @ TXSTA.TRMT; char data_in; bit newdata; //interrupt service routine void interrupt(void) { if(rcif) //UART Recieve Interrupt { data_in = rcreg; newdata = 1; rcreg = 0; } } //Function: Reads one value from the ADC //Returns: most significant byte of result inline char adc_read() { go=1; while(go); return adresh; } //Function: sends a single byte with the hardware serial UART. inline void sendbyte(char b) { txreg=b; while(!trmt) {}; } //Function: Sends a character as ASCII decimal void senddecimal(char b) { char temp, temp2; temp=b; temp2=temp/100; sendbyte('<'); sendbyte(temp2+'0'); temp=temp%100; temp2=temp/10; sendbyte(temp2+'0'); temp=temp%10; sendbyte(temp+'0'); sendbyte('>'); } void main() { //*********************// // configure I/O ports // //*********************// portb = 00000000b; trisb = 11111111b; //0 = Output, 1 = Input porta = 00000000b; trisa = 11111111b; //0 = Output, 1 = Input //***************// // configure ADC // //***************// osccon = 01110000b; //internal oscillator @ 8MHz cmcon = 00000111b; //comparators off ansel = 00000001b; //AN0 on (RA0) adcon1 = 00000000b; //left justified, fosc/2 clock, Vdd & Vss ref voltages adcon0 = 00000001b; //set to AN0, ADC operating //*****************// // configure USART // //*****************// spbrg = 51; //9600 baud @ 8MHz txsta=00100100b; //full duplex asynchronous rcsta=10010000b; //full duplex asynchronous rcie = 1; //enable RX interrupt peie = 1; //enable peripheral interrupts (needed for RX) gie = 1; //global interrupt enable char adcval,temp; while(1) { temp=adc_read(); if(temp!=adcval) { adcval=temp; sendbyte(adcval); //senddecimal(adcval); //use this instead for clearer output in hyperterminal } if(newdata){newdata=0; sendbyte(data_in);} delay_ms(5); } }