Want to thank everyone for their help on this! I'm posting my code as of right now for review and comments.
Al, Even with the multiple collections, sorting and averaging routines put in, I'm still getting a wider variance of data than I think I should ]. Do I have the code right? If so, could my voltage divider be the wrong value?
Also, I tried to increase the baudrate to 9600 and it seemed to stop transmitting, does my serial setup code look OK? I am using a 4 mhz crystal.
Thanks again Everyone!
Dave
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 3 ' Set clock source (3=rc)
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 16
ADCIN 0, RawData[A] ' Read channel 0 to array
Next A
'Now Lets sort the array
Gosub SortArray
'Now Sum the middle 8 values
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
Bookmarks