Detecting Speed Using Two IR Sensors

Hello,

I would like to get some help on how can I read my robot's speed for two separate DC motors. If we only allow display for the reading for one DC motor, the values shown is logical. However if two motor readings are to be displayed, the reading shown on serial monitor is totally in accurate.

Example:

A) If only display one motor reading.
RPM = 215
B) If display reading for two motors at the same time
RPM Left = 5022 RPM Right= 5053

Attached is the coding.

#define in_1 2
#define in_2 3
#define in_3 4
#define in_4 5
#define pwmL 10
#define pwmR 11

const int dataIN = 6; //IR sensor INPUT
const int D = 6.5;

unsigned long prevmillis; // To store time
unsigned long duration; // To store time difference
unsigned long refresh; // To store time for refresh of reading

int rpm; // RPM value
int Speed;

boolean currentstate; // Current state of IR input scan
boolean prevstate; // State of IR sensor in previous scan

void setup()
{
pinMode(dataIN,INPUT);
prevmillis = 0;
prevstate = LOW;
Serial.begin(9600);
pinMode(pwmL,OUTPUT);
pinMode(pwmR,OUTPUT);
pinMode(in_1,OUTPUT);
pinMode(in_2,OUTPUT);
pinMode(in_3,OUTPUT);
pinMode(in_4,OUTPUT);

}

void loop()
{
Forward(70,73);

// RPM Measurement
currentstate = digitalRead(dataIN); // Read IR sensor state
if( prevstate != currentstate) // If there is change in input
{
if( currentstate == HIGH ) // If input only changes from LOW to HIGH
{
duration = ( micros() - prevmillis ); // Time difference between revolution in microsecond
rpm = (60000000/duration); // rpm = (1/ time millis)1000100060;
prevmillis = micros(); // store time for nect revolution calculation
}
}
prevstate = currentstate; // store this scan (prev scan) data for next scan
Speed = 3.14159
(D/100)*(rpm/60);
// LCD Display
if( ( millis()-refresh ) >= 100 )
{
Serial.println(rpm);
}

}

void Forward(int L, int R) {
digitalWrite(in_1, LOW);
digitalWrite(in_2, HIGH);
digitalWrite(in_3, LOW);
digitalWrite(in_4, HIGH);
analogWrite(pwmL, L);
analogWrite(pwmR, R);
}

If the motors have a different speed, your robot makes a curve. Use the appropriate geometric equations to determine the resulting speed and angle.

I assume you have two sensors?

You also need two duration variables and two prevmillis variables (i.e. durationL, durationR, prevmillisL, prevmillisR.) Of course, there is only one currentmillis.

And, you probably should make a function so your program can "go off" and check the RPM (running a loop for a few milliseconds or something) without doing anything else to mess-up the timing.

...You can only check the state & current millis when it gets-back to that point in your loop, so the more stuff you are doing the longer it takes to read the state and the time, and the bigger the error.