I found three errors in your code (corrected in red) .Code:' Read and write hardware USART B1 var byte Done var byte TxBuf var byte[3] SendBuf var byte[6] STX var byte ETX var byte Period var byte i var byte tmpval var byte A var byte 'for for next loop DatAvg var word CounterA var Word DataA var Word RawData var Word [16] ' Initialize USART TRISC = %10111111 ' Set TX (PortC.6) to out, rest in ' Set receive register to receiver enabled DEFINE HSER_RCSTA 90h ' Set transmit register to transmitter enabled DEFINE HSER_TXSTA 20h ' Set baud rate DEFINE HSER_BAUD 2400 DEFINE HSER_SPBRG 25 'Hser spbrg init ' Define ADCIN parameters Define ADC_BITS 10 ' Set number of bits in result Define ADC_CLOCK 1 ' Set clock source to 1.6 us Tad @ Fosc/8 (xtal = 4 MHz) Define ADC_SAMPLEUS 50 ' Set sampling time in uS adval var word ' Create adval to store result TRISA = %11111111 ' Set PORTA to all input ADCON1 = %10000010 ' Set PORTA analog and right justify result Pause 500 ' Wait .5 second ' Echo received characters in infinite loop STX = 2 ETX = 3 Period = 46 TxBuf[1] = 51 TxBuf[2] = 54 TxBuf[3] = 56 mainloop: 'Collect 17 AD samples for A = 0 to 15 ADCIN 0, RawData[A] ' Read channel 0 to array Next A 'Now Lets sort the array Gosub SortArray 'Now Sum the middle 8 values DatAvg = 0 ' set DatAvg to zero for A = 4 to 11 ' pick out middle 8 readings DatAvg = DatAvg + RawData[A] NEXT A 'Now Divide by 8 (by shifting) too get an average DatAvg = DatAvg >>3 'Now put data in TxBuf For A=0 to 3 txbuf[A]= DatAvg DIG (3-A) next A for A = 0 to 3 TxBuf[A] = TxBuf[A] + 48 next A 'Send it! Gosub SendString ' Send character to serial output pause 500 ' Wait half second Goto mainloop ' Do it forever ' ' Sort Array ' ---------- SortArray: CounterA=0 SortLoop: If RawData(CounterA+1) < RawData(CounterA) then DataA=RawData(CounterA) RawData(CounterA)=RawData(CounterA+1) RawData(CounterA+1+0)=DataA If CounterA > 0 then CounterA=CounterA-2 endif CounterA=CounterA+1 If CounterA < 15 then goto SortLoop Return ' Subroutine to send a character string to USART transmitter 'First Send STX (02) then 2 digits, then period (46), then 1 digit, then ETX (03) SendString: 'Build Buffer SendBuf[0] = STX SendBuf[1] = TxBuf[0] SendBuf[2] = TxBuf[1] SendBuf[3] = TxBuf[2] SendBuf[4] = Period SendBuf[5] = TxBuf[3] SendBuf[6] = ETX 'Now Send it HSEROUT[STR SendBuf \ 7] Return ' Go back to caller
The ADC clock source must be set the closesest possible to 1.6 us Tad.
Very likely the fact you didn't reset DatAvg to zero was responsible for the non stable reading.
As far as the baud rate is concerned you can use 4800 as the maximum baud rate with your 4 MHz oscillator.
Tray and see you should have rock stable reading now, good luck.
Al.




Bookmarks