r/pic_programming • u/l_CptChronic_l • Nov 24 '20
Please help with programming ADC
Hi,
PIC16F18325
MPLAB X using MCC
So im trying to use ADC to read a voltage from a hall sensor. When the sensor reaches a certain voltage, i want it to toggle an led by switching from input to output over and over while LATA5 = 0. (LED is always on so i want to turn it off and on repeatedly)
Ive done it all in MCC so all the back code is there
ADC is enabled
Using FOSC/4 or /2
Right aligned
Positive ref: VDD
Negative: VSS
No auto trigger
Heres my main code:
void main (void){SYSTEM_Initialize();
ADC_Initialize();
while(1)
{
if (ADC_GetConversion(RA0) > 100)
{
LATA5 = 0;
TRISA5 = 0;
__delay_ms(500);
TRISA5 = 1;
__delay_ms(500);
}
}
}
Now the problem im having is;
When coded like this: (ADC_GetConversion(RA0) > 100) The led will always flash until the number in the statement (100) is met.
I want to swap it around so the led doesnt flash until 100 is met.
If i change the statement to: "if (ADC_GetConversion(RA0) < 100)" changing the bigger than to smaller than, it just constantly flashes no matter where the trigger is positioned.
Ive tried all values from 0-1023 but it just flashes no matter what.
I really cant get my head around this, if i have it set to > 100 (if ADC_GetConversion(PotA0) > 100) the led flashes all the time until the trigger is pulled all the way in. (until its less than 100)
Which surely means all i need to do is change the > (more than) to < (less than).
Changing to < should make it...
If the conversion is less than 100, make the led flash
This should now mean that when the trigger is pulled in the led will flash....right??
What am i doing wrong? I have been trying for days now but cannot get it working the way i need it.
1
u/Coltouch2020 Nov 25 '20
Have a look at this. you don't ned to mess about with the LAT and TRIS bits, set the ports up in MCC and the Initialisation will do it all for you...
void main(void)
{
// initialize the device
SYSTEM_Initialize();
LED1_SetLow();
while (1)
{
if(ADCC_GetSingleConversion(channel_ANC0) > 100) {
LED1_SetHigh();
__delay_ms(100);
LED1_SetLow();
__delay_ms(100);
}
}
}I used different ADC pin, but the code should work.
0
u/l_CptChronic_l Nov 26 '20
But LED1_SetLow is the same as writing LATA0=0; so im still messing with the LAT and TRIS bits.
And this led will not flash by making it go high and low, it needs to go from its normal state to low which is why i am setting it low then changing from input to output.
Thanks for the input though
0
0
Nov 24 '20
[deleted]
1
u/l_CptChronic_l Nov 24 '20
MCC does most of the hard work with configuring names etc so RA0 is linked with ANA0 already in the settings.
1
u/[deleted] Nov 24 '20
I think you have implemented the tris register incorrectly