Problem with going from analogue to digital reading from sensor output

When reading the analogue output from the sensor with help of the serial communication I get the attached output.txt.

Plotting the output in matlab shows that the sensor detects 24 object which is correct.

Changing the configuration to a digital pin, putting a simple interrupt routine when the input goes from low to high to count the objects, the logic calculate it wrong. Sometimes it is correct but most of the time it calculate to many object. Is the digital reading slower than the analogue reading?

I would be so happy if someone could help me out here, what to do or in which direction to work. Going crazy here.

graph.jpg

output.txt (7.31 KB)

It looks like it should work with the interrupt. It is difficult to say what is causing the problem. Don't think digital reading is slower, because in that case your sensor should detect less object and not more. Hope someone else know some things to do that will help you! Best luck!

Thank you Raun for your answer! I guess you are right.

I normally have 2 sensors giving both of them an interrupt routine, calculating the objects, on the same arduino. If I try to change the logic configuration to go with analogue reading, maybe have continues reading on both sensors, calculating every time it goes to the highest value (1023) and it will not count until the value has gone down to zero again and back up to 1023. Is that a good way of solving it? Or should I have a micro controller for each sensor when reading analogue values?

I was thinking of something like this (but this is just for one sensor):

int analogPin = 0;  
int val = 0;        
int count = 0; 
int flag = 0; 

void setup()

{
  Serial.begin(9600);  
}

void loop()
{

  val = analogRead(analogPin);   
  if(val == 1023 && flag == 0){
    count = count + 1;
    flag = 1;
  }
   if(val == 0 && flag == 1){
     flag = 0;
   }
  Serial.println(count);   
}

Is this really a smart way to solve the problem? For me it sounds a bit unsafe, especially when using 2 senors... Any one?

I thought this would be a super easy question for you guys! No?

I think you need to "debounce" your sensor signal, on the analog readout it looks the signal does not drop cleanly from HIGH to LOW, a fast processor might see 2 or more counts.

Search on "switch debounce".