The TCRT5000 IR sensor and interrupts

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

Did you check the signal you get from that sensor? Do you really get just one edge if such a count event occurs?
Check that with a scope. I'd expect multiple strikes per event so it might be more practical not to use an interrupt but simply polling the input and debouncing it in software. 500Hz is quite slow for an MCU as the one in the Arduino.

Did you check the signal you get from that sensor?

No. But when I did, the trace was exactly as you predicted. Each time I triggered the sensor, it gave me a random number of sloping curves. The trace seems to always be negative 5 volts decaying to zero followed by Positive 5 volts decaying to zero (repeated multiple times).

I substituted a Hall Effect sensor and my counter started behaving predictably.

Thanks for the suggestion.

Gary