I modified your code a little like this:Pin numbers in RPI.GPIO can be BOARD or BCM. BOARD are the header pin numbers, BCM are the chip GPIO numbers. See https://pinout.xyz/Python only works with 'structure by indendation', so no explicit 'end' needed (and not available).I noted in the code that it ends with a while loop, which seems not to be closed, so that may be a problem (no end for the while...)
The code is not written to be robust. Perhaps better:
Code:
import RPi.GPIO as GPIOimport timeGPIO.setmode(GPIO.BCM)resistorPin = 18TIMEOUT = 3.0while True: GPIO.setup(resistorPin, GPIO.OUT) GPIO.output(resistorPin, GPIO.LOW) #time.sleep(0.1) time.sleep(1) GPIO.setup(resistorPin, GPIO.IN) currentTime = time.time() diff = 0 while(GPIO.input(resistorPin) == GPIO.LOW): diff = time.time() - currentTime if diff > TIMEOUT: print("9999") diff = 0 break print( f"low -> high time [ms] {diff * 1000:.1f}") time.sleep(1)
Code:
$ python photoResistorTest2.pylow -> high time [ms] 10.4low -> high time [ms] 17.9low -> high time [ms] 18.0low -> high time [ms] 17.8low -> high time [ms] 17.5low -> high time [ms] 17.2^CTraceback (most recent call last): File "/home/pi/projects/photoresistor/photoResistorTest2.py", line 27, in <module> time.sleep(1)KeyboardInterrupt
And there is a strange error message too referencing different lines:
Code:
photoResistorTest2.py:10: RuntimeWarning: This channel is already in use, continuing anyway. Use GPIO.set warnings(False) to disable warnings.photoResistorTest2.py:9: RuntimeWarning: This channel is already in use, continuing anyway. Use GPIO.set warnings(False) to disable warnings.
Then I could use this function in my shellscript to get the current light level to decide if to turn on the outdoors lights or not.
Of course I have to calibrate the function by determining the value corresponding to the light level for switch-on and switch-off with some hysteresis.
But it must be a function that will reliably output the same (single) value each time it it is called for the same light level.
So:
1) How do I change the code to make a single measurement (or two if the first is consistently erroneously low).
2) How to make the output not contain any decimals? Just integer milliseconds.
3) If it is so dark that the 1-level is not reached in a sensible time, I guess I could print for instance 9999 as shown?
4) How to exit cleanly when the reading is done (it seems like the library holds some resource as it is now, maybe because of the failure to exit cleanly so I have to use Ctrl-C all the time?
Statistics: Posted by Bosse_B — Tue Dec 03, 2024 11:14 am