PDA

View Full Version : Help to setup ADC for 16F1826



SOTASOTA
- 9th February 2014, 23:47
I am pulling what hair is left out of my head.
For PIC16F1826, I am trying to get the ADC setup.
I have a voltage INPUT on RA2 (pin1).
This is where I want to ADC to be controlled (AN2).
I referred to the datasheet (page 139), but cannot get this thing to work.
I also have INPUTS on RA3 (pin2) and RA5 (pin4)
Here is my code:



'= PIC16F1826 =
'================================================= =======
'Initialize variable
#CONFIG
__config _CONFIG1, _FOSC_HS & _WDTE_OFF & _PWRTE_OFF & _MCLRE_OFF & _CP_OFF & _CPD_OFF & _BOREN_OFF & _CLKOUTEN_OFF & _IESO_OFF & _FCMEN_OFF
__config _CONFIG2, _PLLEN_OFF & _LVP_OFF & _STVREN_OFF
#ENDCONFIG

'_MCLRE_OFF = MCLR pin functions as INPUT RA5, MCLR internally tied to VDD

DEFINE OSC 4
DEFINE ADC_BITS 8 ' 8 bit A/D Conversion
DEFINE ADC_CLOCK 3
DEFINE ADC_SAMPLEUS 50 ' 50 uS A/D sample time

PORTA = 0
PORTB = 0
TRISA = %00101100
TRISB = %00000000
ADCON0 =%00001001
ADCON1 =%11000000 'Right justified

ANSELA =%00000100 ' AN2 on PortA.2 analog
ANSELB =%00000000 ' Digital inputs

FVRCON = 0
DACCON0 = 0
DACCON1 = 0
INTCON = 0
CM1CON1 = 0

adval var word

mainloop:
adcin 2, adval
if adval<18 then PortB.3 = 1
if adval>28 then PortB.3 = 0
goto mainloop
end


Help please!!
Thx!

Aussie Barry
- 10th February 2014, 06:43
Two things I have noticed in your code:

1/. The 16F1826 has a 10 bit ADC whereas you have defined an 8 bit setup
2/. ADCCON0 = %00001001 sets the ADC channel to be AN9 where you are trying to use AN2

Cheers
Barry
VK2XBP

SOTASOTA
- 10th February 2014, 18:16
Hey Barry!
Thanks so much!!!
This did it!


DEFINE OSC 4
DEFINE ADC_BITS 10 ' 10 bit A/D Conversion
DEFINE ADC_CLOCK 4
DEFINE ADC_SAMPLEUS 50 ' 50 uS A/D sample time

PORTA = 0
PORTB = 0
TRISA = %00101100
TRISB = %00000000
ADCON1 =%11000000 'Right justified

ANSELA =%00000010 ' AN2 on PortA.2 analog
ANSELB =%00000000 ' Digital inputs


I actually thought you could tell a 10-bit ADC to work as an 8-bit. But no worries! All is perfect once again!!

Sherbrook
- 11th February 2014, 17:35
Hi SOTATOSA
10 bit A/D converters do work in 8 bit mode. Just set LEFT justified and the 8 MSBs are held in the ADRESH register and the 2 LSBs are held in the ADRESL register bits 6 and 7 which you ignore. ADRESH register contains the 8 bit result. I think this is how DEFINE ADC_BITS 8 works. Setting 8 bit conversion AND RIGHT justified would cause some confusion. Hope this helps.
Phil

Heckler
- 11th February 2014, 22:30
this tutorial helped me understand A/D a little better...

http://www.microcontrollerboard.com/analog-to-digital-converter.html

and here is another good tutorial...

http://www.edaboard.com/nextoldesttoentry1570.html

SOTASOTA
- 12th February 2014, 00:06
Thanks for all the replies. Making some kind of sense now! :-)