I'm working with a TCRT5000 IR sensor that is mounted on a small circuit board. The board includes an LED that lights up when the sensor goes HIGH.
I'm using the sensor to count things. The counts can occur with a rate of 1 per second to as high as 500 per second.
I've put some code together to do the counting using Interrupts. See below.
The problem I'm having is the count jumps rather than incrementing sequentially. What I want is to increment the count by one each time the sensor goes HIGH. Currently the count jumps by a random amount typically by 4 or 5.
Here is the code:
#define sensorPIN 2 // Pin number for the sensors
unsigned long rawNumber = 0;
unsigned long prevMillis = 0;
volatile unsigned long interruptCounter = 0;
void setup ()
{
Serial.begin (9600);
// initialize the sensor pin as an input:
pinMode (sensorPIN, INPUT);
// set up the interrupt routine
attachInterrupt (0, SensorInterrupt, RISING);
}
void loop()
{
// read the state of the sensor
sensorState = digitalRead (sensorPIN);
if (millis () - prevMillis > 100)
{
rawNumber += interruptCounter;
interruptCounter = 0;
prevMillis = millis ();
}
Serial.println (rawNumber);
}
void SensorInterrupt ()
{
interruptCounter++;
}
Suggestions please.
Gary