Rising Edge Interrupts for Speedometer

Hello

I am making an object counter, as can be seen in the attached picture. The structure of the code is as follows.

void loop()
{
  // read the inputs
  readInputs();
  
  // evaluate valA and valB
  evalInputs();
  
  // show output on LCD (and serial)
  displayOutput();
  
  // set value of prevCtr, ready for next loop  
  prevCtr=ctr;

}

It performs the basic duties of a object counter. The first function readInputs reads the analog inputs A1 and A2 using the analogRead function. The second function evalInputs compares valA and valB with the threshold - in this case 900. displayOutput hands the display of the counter on the attached 16*2 LCD as well as sending debugging info via serial.

The complete code is as below.

/*

IR Counter with Serial and LCD output

*/

// include the library code:
#include <LiquidCrystal.h>

LiquidCrystal lcd(9,8,7,6,5,4);  // pins for RS, E, DB4, DB5, DB6, DB7

// General Operation Varibles
const int inputA=1;  //Pot on analog pin 1
const int inputB=2;  //Pot on analog pin 2
int valA = 0;      //variable to hold the analog reading from inputA
int valB = 0;      //variable to hold the analog reading from inputB
int ctr=0;          //variable to hold counter
int prevCtr=0;
int thresh=0;

void setup()
{
  Serial.begin(9600);  //Initiate serial connection
  lcd.begin(16, 2);    //define LCD
  lcd.clear();         //Clear LCD display
}
void loop()
{
  // read the inputs
  readInputs();
  
  // evaluate valA and valB
  evalInputs();
  
  // show output on LCD (and serial)
  displayOutput();
  
  // set value of prevCtr, ready for next loop  
  prevCtr=ctr;

}

void readInputs() {
  valA = analogRead(inputA);      //read analogue inputA
  valB = analogRead(inputB);      //read analogue inputB
}

void evalInputs() {
  
  thresh = 900;                                  // sensor threshold depends on ambient light
  if(valA<thresh && valB>thresh)
  {
    ctr=ctr+1;      //  increment counter by one
    delay(800);
  }
  else{
    ctr=ctr;
  }

  if(valA>thresh && valB<thresh)
  {
    ctr=ctr-1;      // decrease counter by one
    delay(800);
  }
  else
  {
    ctr=ctr;
  }
  
}

void displayOutput() {
  //Print data to Serial

  Serial.print("valA is :  ");
  Serial.print(valA   ); 
  Serial.print("      valB is :  ");
  Serial.print(valB    );
  Serial.print("     counter :  "); 
  Serial.print(ctr); 
  Serial.print("  thresh val : ");
  Serial.println(thresh);

// Only refresh the LCD if the counter is updated
// This reduces flickering

if (ctr == 0 || ctr != prevCtr)
  {
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("Counter: ");         //print varA on LCD
    lcd.print(ctr);
  }
}

While the above configuration works, there are two additional features that I am looking to implement.

  • Stable behaviour when an object is held between the sensors
  • Display of speed on LCD

To do this I understand that I will need to use some sort of interrupts to achieve the required pseudo-multitasking required. This is what I came up with.

/*

This is a rewrite of the Arduino Optocounter + Speedometer.
Interrups according to Jermey Blum's Book, pg 268 are used.

*/



// Variables
const int gateA      =0;          //Pin 2 on Arduino
const int gateB      =1;          //Pin 3 on Arduino
volatile boolean gateAActive  =false;      // Status of gateA
volatile boolean gateBActive  =false;      // Status of gateB

volatile int ctr=0;;                           // variable to store count

volatile unsigned long prevMillis;    //CPU time at end of loop
volatile unsigned long deltaMillis;   //time difference measured
volatile unsigned long currMillis;

unsigned long distance = 3;                // distance between gates in mm
unsigned long itemSpeed;              // speed of object in mm/ms (m/s)

void setup()
{
  
  Serial.begin(9600);  //Initiate serial connection
  
  attachInterrupt(gateA ,evalGateA , RISING);  //Upon Rising edge interrupt for gateA run function evalGateA
  attachInterrupt(gateB ,evalGateB , RISING);  //Upon Rising edge interrupt for gateB run function evalGateB
}


void evalGateA()                  // detect gate
{
  if (gateBActive == false)
  {
    if (gateAActive == true)      // In this case, the object came through gateA and left through gateA
    {
      gateAActive=false;          // Pretend it never even entered
    }
    else
    {
      gateAActive=true;
      prevMillis=millis();
    }
  }
  else if (gateAActive == false && gateBActive == true)
  {
    ctr=ctr-1;
    currMillis=millis();
    deltaMillis=currMillis-prevMillis;
  }
}

void evalGateB()                  // detect gate
{
  if (gateAActive == false)
  {
    if (gateBActive == true)      // In this case, the object came through gateA and left through gateA
    {
      gateBActive=false;          // Pretend it never even entered
    }
    else
    {
      gateBActive=true;
      prevMillis=millis();
    }
  }
  else if (gateBActive == false && gateAActive == true)
  {
    ctr=ctr-1;
    currMillis=millis();
    deltaMillis=currMillis-prevMillis;
  }
}


void calcSpeed() {
 if (deltaMillis>50)
 {
    //Calculate speed
    itemSpeed = distance / deltaMillis; // v=x/t
    Serial.println(itemSpeed);
    Serial.println(ctr);
 }
}
void loop()
{
  calcSpeed();
}

Interrupt 0 and 1, corresponding to pins 2 and 3 on the arduino are used. However, I am not able to detect the rising edge when an object passes through the sensor. When there is no object between the sensor, analogRead gives me a steady number about 800. When an object is between the sensor, it gives me 1023. I have used a 560 ohm pull-up resistor.

I'd appreciate any pointers in the right direction.

I should mention that the Arduino platform has been my first introduction to C. I have also worked with Matlab and Fortran before.

I'm confused because your first example uses analog inputs but the code with interrupts uses digital inputs.

Why can't you just add timing to the first example?
You really only need interrupts if things happen extremely frequently or are only visible for an extremely short instant.

What is the shortest time interval between your objects?

...R

Can you describe your goal without presenting confusing code? What's the time you want to measure?

I'd try to get sensors with digital output, then you can use digitalRead or interrupts (PCI) as you like.

salehgeek:
To do this I understand that I will need to use some sort of interrupts to achieve the required pseudo-multitasking required.

Why would you think that? Why not just use code that continuously reads (polls) the inputs?

Why would you want to read analog inputs for a digital function? Perhaps you do not know that analog inputs are actually digital input/ output pins?

Robin2:
I'm confused because your first example uses analog inputs but the code with interrupts uses digital inputs.

I used analog inputs in my first (counter only) example (E1) but in order to use the interrupts for improving accuracy and implementing a speedometer, I used the digital pins 2 and 3 (INT 0 and INT 1 correspondingly) instead (E2). Arduino - AttachInterrupt

Robin2:
Why can't you just add timing to the first example?

Inside the evalInputs() function I wrote:

if(valA<thresh && valB>thresh)
  {
    ctr=ctr+1;      //  increment counter by one
    delay(800);
  }

I could not get the delay function to play nicely with interrupts or timers. In any case, it only detects when an object passes through the first gate, but not the other. Plus, it will only work if it takes less than 800 millisecond for an object to pass through. Do you have a specific timer library in mind?

Robin2:
What is the shortest time interval between your objects?

The time interval for objects is 100ms.


DrDiettrich:
Can you describe your goal without presenting confusing code? What's the time you want to measure?

I'd try to get sensors with digital output, then you can use digitalRead or interrupts (PCI) as you like.

Goal:

  • Assemble and build an Arduino based object counter, with speedometer.
  • Gain experience with working with the Arduino, especially since I have...
  • ...to be able to explain to my professor what I have done and why. :cold_sweat:

Consider this:
Prof: Why did you use digital sensors?
Me: I can't use analog sensors.
Prof: You, sir, are a genius [Prof scribbles down that-what-should-not-be-written :wink: ]

This is the picture of my circuit in E1 configuration.

Paul__B:
Why would you think that? Why not just use code that continuously reads (polls) the inputs?

Why would you want to read analog inputs for a digital function? Perhaps you do not know that analog inputs are actually digital input/ output pins?

I wanted to detect the rising edge of the input. Can you clarify what you mean by digital function please?


Your comments all have been food for thought: thanks. :slight_smile:

salehgeek:
I used analog inputs in my first (counter only) example (E1) but in order to use the interrupts for improving accuracy and implementing a speedometer, I used the digital pins 2 and 3 (INT 0 and INT 1 correspondingly) instead (E2). Arduino - AttachInterrupt

I know that attachInterrupt uses digital pins. All that means is that you can't use attachInterrupt() if you have an input that must be read using analogRead(). Your first example suggests that analogRead() is necessary.

I could not get the delay function to play nicely with interrupts or timers. In any case, it only detects when an object passes through the first gate, but not the other.

Now you have lost me completely. What has delay() got to do with measuring time. Delay() would prevent you from measuring time.

The time interval for objects is 100ms.

That is a long time by Arduino standards.

I think we would make more progress if you explain how your system is supposed to work.
It seems to me it takes two analog readings and figures out if an object is coming into view or going out of view depending on which of the values is darker or brighter than a threshold.

If I am correct then you cannot use interrupts to do anything useful.

And if you want to measure the time between objects, then you just need to save the value of millis() [or micros() if you want more precision] when an object leaves the view and record it again when the next object comes into view. The difference between the two saved values will be the time between the objects.

...R

Let me think about what you have and the others have said and I'll get back to you tomorrow.

"delay()" is not a function to be used in serious programs.

It may have some use in the setup{} procedure.

From the look of it, you're trying to get around your own delay() by using interrupts.

If that's the case then there's a MUCH better way to task but it might take days to learn.

I think we would make more progress if you explain how your system is supposed to work.

My high-level goal is to make a device that can measure the speed and number of passing objects. To make things clear, I've made a Fritzing diagram and schematic of my circuit.


I haven't connected a wire between the pull-up resistors and sensor in the above pictures, to avoid confusion. In my first approach I used the A1 and A2 pins, while I used pins 2 and 3 (the interrupt pins) on my second approach.

It seems to me it takes two analog readings and figures out if an object is coming into view or going out of view depending on which of the values is darker or brighter than a threshold.

If I am correct then you cannot use interrupts to do anything useful.

(Correct me if I'm wrong, but) I see two (useful) ways to read the values from between the sensor and pull-up resistor.

  • analogRead
  • attachInterrupt

While using interrupts may not the only way forward, they might just make life easier for us.

attachInterrupt(gateA ,evalGateA , RISING);

What the above code does is to check gateA (INT0 = Pin 2) for a rising edge. Should a rising edge be detected, it runs the evalGateA function. Even if I am to compare analogRead to a threshold, I still need to ensure that it only counts each object once, when the value rises.

Paul__B:
"delay()" is not a function to be used in serious programs.

It may have some use in the setup{} procedure.

According to the Arduino delay reference :

While it is easy to create a blinking LED with the delay() function, and many sketches use short delays for such tasks as switch debouncing, the use of delay() in a sketch has significant drawbacks. No other reading of sensors, mathematical calculations, or pin manipulation can go on during the delay function, so in effect, it brings most other activity to a halt.

That is why my second approach doesn't use the delay function at all.

GoForSmoke:
From the look of it, you're trying to get around your own delay() by using interrupts.

If that's the case then there's a MUCH better way to task but it might take days to learn.

I tried to get around delay by using the millis function (Using millis() for timing | Multi-tasking the Arduino - Part 1 | Adafruit Learning System).

Do you know a alternative approach that you could share? I'm at this for a couple of months now, a few more days is no big deal. :smiley:

salehgeek:
My high-level goal is to make a device that can measure the speed and number of passing objects.

There is a huge difference if the passing objects are motor cars on a quiet country road or peas rattling down a chute into a bag. Tell us about the project - not how you think it should be solved.

(Correct me if I'm wrong, but) I see two (useful) ways to read the values from between the sensor and pull-up resistor.

  • analogRead
  • attachInterrupt

These are NOT simple alternatives. If you have a sensor that produces an analog signal you CANNOT use attachInterrupt().

In your original post you seemed to be using a sensor that produced an analog signal.

As I said above, tell us what you actually want to do and someone may know immediately what is the easiest way to do it.

...R

@R My prof is looking for a device that counts how many times he passes his bus pass between two sensors, in what direction, what speed. I don't plan on counting cars passing on the road, and there is no need for it too be super accurate. Just work reasonably.

The sensors do produce an analog signal, but there is a clear distinction when the sensor is blocked by paper (on) and open (off).

salehgeek:
@R My prof is looking for a device that counts how many times he passes his bus pass between two sensors, in what direction, what speed.

Then you will understand why I have been totally confused by your statement in Reply #4

The time interval for objects is 100ms.

I doubt very much your professor is that fast

The sensors do produce an analog signal, but there is a clear distinction when the sensor is blocked by paper (on) and open (off).

That distinction is only detectable after you have used analogRead() to measure the voltages. Hence you can't use attachInterrupt().

And if all you are doing is timing a person there is certainly no need for interrupts.

I explained what needs to be done in the final paragraph of Reply #6

...R

I see what you mean now. Maybe interrups are overkill.

And if you want to measure the time between objects, then you just need to save the value of millis() [or micros() if you want more precision] when an object leaves the view and record it again when the next object comes into view. The difference between the two saved values will be the time between the objects.

I'll try and see if I can get a code working using millis() by next Wednesday. If this works out, should I consider making an Instructable?

salehgeek:
I see what you mean now. Maybe interrups are overkill.

Not so much overkill, but difficult to code for properly and to no advantage, unnecessarily confusing the code.

salehgeek:
If this works out, should I consider making an Instructable?

Now there's a question! Do you value your reputation? :astonished:

Paul__B:
Now there's a question! Do you value your reputation? :astonished:

What do you mean? I am going through a lot of trouble trying to get this to work, and I thought that an Instructable would be a way to give back to the Arduino community.

Let me just say that "instructables" - as such - are somewhat notorious. :smiley: