3
\$\begingroup\$

I'm using the picdem 18F4550 with microchip v8.63 with the C18 compiler.

I will enable PortA to set as input, I will connect a LDR on port RA0. Which is as following (I think):

TRISAbits.TRISA0 = 1; //<= set RA0 as input.

Now I want the value of the LDR (voltage/value if a led is on), can I say:

int colorLed = PortAbits.RA0;

And now in the variable of type int there is the value/voltage of my Led.

Correct me if I'm wrong.

Brian Carlton
13.4k6 gold badges46 silver badges66 bronze badges
asked Mar 28, 2011 at 19:31
\$\endgroup\$

2 Answers 2

7
\$\begingroup\$

Firstly, lets check that you have connected your LDR up correctly, it should be something like this...

LDR wiring

To read the value of PIN RA0/AN0, you need to do some initialisation to make sure the port is setup correctly. The datasheet explains how all this works, but these values should work:

TRISAbits.TRISA0 = 1; // Set RA0/AN0 to input
ADCON0 = 0b00000000; // Set channel select to AN0
ADCON1 = 0b00001110; // Configure RA0/AN0 as analogue
ADCON2 = 0b10101010; // Right justified result
 // TAD 12 and FOSC 32 - may need to adjust this
 // depending on your clock frequency (see datasheet)
ADCON0.ADON = 1; // Enable ADC

Now the port should be set up, you can now read the LDR value:

ADCON0bits.GO = 1; // Set the GO bit of the ADCON0 register to start
 // the conversion.
while (ADCON0bits.GO); // Wait until the conversion is complete.

You can now read the result of the LDR as a 10-bit value in ADRESH:ADRESL. If you only need 8-bit resolution, then set ADCON2.ADFM = 0 for left justification of the result, then you only need to read the ADRESH to get your result.

answered Apr 1, 2011 at 22:03
\$\endgroup\$
1
  • \$\begingroup\$ the plan that you signed, correct. The code that you write is what I wanted! Many thanks for your help!!! \$\endgroup\$ Commented Apr 4, 2011 at 16:39
5
\$\begingroup\$

To read an analogue voltage you need to use the PIC's ADC (Analogue to Digital Converter).

Here's a tutorial: http://www.roboticsguy.com/tutorials/pic-microcontrollers/configuring-the-pic18f4550-10-bit-adc-module

answered Mar 28, 2011 at 20:57
\$\endgroup\$
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.