Issue
I have the sensor working on an Arduino UNO. I'm having trouble translating the code over. I can get the pi to receive input from the sensor, but I'm not sure how to get it to read the rising pulses for a specific amount of time (10 seconds) to give a certain number of pulses.
In this code the arduino is still receiving pulses from the sensor during the 10 second delay, but the number will vary based on how much light is getting through, which is what I want. I want the pi to do the same thing.
Also please understand I'm very much a novice, so if you can explain in detail I'd appreciate it.
#define TSL237 2
volatile unsigned long pulse_cnt = 0;
void setup() {
attachInterrupt(0, add_pulse, RISING);
pinMode(TSL237, INPUT);
Serial.begin(9600);
}
void add_pulse(){
pulse_cnt++;
return;
}
unsigned long Frequency() {
pulse_cnt = 0;
delay(10000);// this delay controlls pulse_cnt read out. longer delay == higher number
// DO NOT change this delay; it will void calibration.
unsigned long frequency = pulse_cnt;
return (frequency);
pulse_cnt = 0;
}
void loop() {
unsigned long frequency = Frequency();
Serial.println(frequency);
delay(5000);
}
here is what I have tried in MU, but I'm not as skilled.
import threading
import time
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
TSL237 = 16
GPIO.setup(TSL237, GPIO.IN, pull_up_down=GPIO.PUD_OFF)
class TSL237():
def __init__(self,TSL237):
self.TSL237 = TSL237
def Frequency(self):
self.pulse = 0
i=0
while i < 10:
i += 1
if GPIO.input(TSL237):
pulse += 1
return self.pulse
Reading = TSL237(TSL237)
GPIO.add_event_detect(TSL237, GPIO.RISING, Reading.Frequency())
#threading.Thread(target=TSL237(Frequency)).start()
Solution
You have mixed up the interrupt code with the readout code. The Frequency
method in the arduino code does nothing but wait a certain time (10 seconds) for the ticks to increase. The actual increase of ticks happens in the interrupt handler add_pulse
, though.
In the python code, the Frequency
method is now the interrupt handler, and you're waiting inside it for some event as well. This doesn't work, because the interrupt handler won't fire again while it's active.
Change your code to something like this (untested, since I don't have such a sensor)
import threading
import time
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
TSL237Pin = 16
GPIO.setup(TSL237Pin, GPIO.IN, pull_up_down=GPIO.PUD_OFF)
class TSL237():
def __init__(self, pin):
self.pin = pin
self.pulses = 0
def OnRisingEdge(self):
self.pulses += 1 # Increase the pulse count and immediately return
def Frequency(self):
self.pulses = 0 # Reset pulse count
time.sleep(10) # wait 10 seconds
return self.pulses # return new value of pulse count
Reading = TSL237(TSL237Pin)
GPIO.add_event_detect(TSL237Pin, GPIO.RISING, callback=Reading.OnRisingEdge)
result = Reading.Frequency()
print(result)
Answered By - PMF Answer Checked By - David Goodson (WPSolving Volunteer)