Get value from LDR

microcontroller

I'm using the picdem 18F4550 with microchip v8.63 and the c compiler. components that i'm use are: – 3 leds (red, green, blue); – a LDR (327700 NORPS-12 farnell).

I have connected 3 leds (red, green and blue), on RB4, RB5 and RB6 as output. I also connect the LDR on RB1.

My question is, when the green of another led lights up, how can I retrieve the value in my code that the LDR measures?

I included my code:

#include "p18cxxx.h"
#pragma config WDT = OFF 
void main(void) {     
    // turn off all LED latches     
    LATDbits.LATD0 = 0;     
    LATDbits.LATD1 = 0;     
    LATDbits.LATD2 = 0;     
    // make port d bits which drive LEDs outputs     
    TRISDbits.TRISD0 = 0;     
    TRISDbits.TRISD1 = 0;     
    TRISDbits.TRISD2 = 0;    
    TRISB = 0;    
    // RB port output.    
    PORTB = 0;    
    PORTB = 0b10001111; 
    // 0b01011010    
    if(PORTBbits.RB4 == 0) {        
        LATDbits.LATD0 = 1;         
    }    
    else if(PORTBbits.RB5 == 0) {        
        LATDbits.LATD1 = 1;    
    }    
    else if(PORTBbits.RB6 == 0) {        
        LATDbits.LATD2 = 1;    
    }       
    if(PORTBbits.RB1 == 1) {    
    }         
    while(1) {        ;    }   
}

Best Answer

You cannot read a resistance (directly) from a PIC input port. There are a few different ways to go here:

  1. If you connect another resistor to Vdd you can make a voltage divider, which has an output voltage determined by the two resistances. The ADC will give you the voltage, and some algebra will get you the resistance.

  2. You could build a constant-current source, and pass this current through the LDR. Then the voltage across the LDR will be exactly proportional to the resistance.

  3. You could use a capacitor from the LDR and connect it to another pin. When the capacitor pin is set high, you can watch the rise time on the capacitor-LDR connection. This technique does not require an ADC. (For more accuracy, charge the capacitor through a known resistance and discharge through the LDR, then use the charge time / discharge time ratio.)