http://learn.adafruit.com/basic-resisto ... ll-reading
and then written what I think is the equivalent code using the Pi4J library (looping 1000 times before quitting):
- Code: Select all
GpioController controller = GpioFactory.getInstance();
GpioPinDigitalOutput pin0 = controller.provisionDigitalOutputPin(
RaspiPin.GPIO_01, "GPIO_1");
for (int i = 0; i < 1000; i++)
{
int value = 0;
pin0.export(PinMode.DIGITAL_OUTPUT);
pin0.setState(PinState.LOW);
pin0.export(PinMode.DIGITAL_INPUT);
while (pin0.getState() == PinState.LOW)
{
value++;
}
System.out.println("Value: " + value);
System.out.println("Pin state: " + pin0.getState());
}
I realize from the explanation on the Adafruit site that this is a workaround to determine a relative light level by how long it takes for the capacitor to charge before a high level is detected (at least that's what I think is happening), so I'm not at this point interested in an exact reading, I'm just curious how this works.
Firstly, is my code above an equivalent implementation of the Python code example?
- Code: Select all
import RPi.GPIO as GPIO, time, os
DEBUG = 1
GPIO.setmode(GPIO.BCM)
def RCtime (RCpin):
reading = 0
GPIO.setup(RCpin, GPIO.OUT)
GPIO.output(RCpin, GPIO.LOW)
time.sleep(0.1)
GPIO.setup(RCpin, GPIO.IN)
# This takes about 1 millisecond per loop cycle
while (GPIO.input(RCpin) == GPIO.LOW):
reading += 1
return reading
while True:
print RCtime(18) # Read RC timing using pin #18
Secondly, there's a noticeable difference between how many iterations the Python code takes before it returns a high reading, compared with the Java code.
For example, for Java using Pi4J:
normal room light level: 0 iterations before returns high level
hand over sensor: 30-40 iterations before returns high level
For Python:
normal room light level: 50-60 iterations before returns high level
hand over sensor: 170-180 iterations before returns high level
I know Pi4J has an state change listener api that's probably preferable than this constant polling approach, but I'd like some thoughts/feedback on whether I'm using the Pi4J api correctly? (or should I just go straight to using the listener approach?)
Thanks! Kevin