Go Down

Topic: millis(); not updating with the same loop (Read 804 times) previous topic - next topic

Viraco

im trying to determine how much time has elapsed for a few lines of code:
Code: [Select]

//Read Flow Meter
  countA=0;
  cTime=millis();
  for(int xCount=0; xCount<10001; xCount++){
    int signalA = digitalRead(rpm_rd3); //detects tachometer signal, flow pin goes high every time the magnet spins past the sensor. NOTE: must be int.
    if(signalA==1){
      countA++;
    }
  }
  pTime=millis();
  FLOWCALC = countA/((pTime-cTime)/1000)*60;


but cTime and pTime are returning the same time.

this is a portion of code. i know the values are the same as i have them reading out to a 20x4 LCD.

i know i could use interrupts for this but i am using a Arduino UNO IDE 1.0.3 and pins 2 and 3 are being used for capturing RPMs from a pump and a fan using interrupts 0 and 1.

original code idea from http://davebmiller.wordpress.com/2011/01/18/arduino-flowmeter/

bobthebanana

It's quite possible that your 10000 cycle loop takes less than a millisecond to execute

retrolefty

Instead of millis() try using micros() as a 16mhz AVR chip may run code a lot faster then you appreciate.  ;)

http://arduino.cc/en/Reference/Micros

Lefty

Viraco

thanks i'll give that a try.

also wondering if serial needs to be running as the examples i have seen have it running at 9600 or 19200.
not sure if that makes a difference.

tuxduino

What do you mean by "serial is running" ? It's not like Serial.begin() starts some kind of background process :)

PaulS

Code: [Select]
  FLOWCALC = countA/((pTime-cTime)/1000)*60;
Notice that this is ALL integer arithmetic. Unless the loop takes more than a second to execute (highly unlikely), (pTime - cTime)/1000 will always be 0. (pTime - cTime)/1000.0 would not.

robtillaart

digitalread takes in the order of 1-4 uSec  the loop should be above 10 millisecs at least. using micros() is OK but won't solve the error I expect..

Note you are doing 10001 iterations, and divide by 1000
for(int xCount=0; xCount<10001; xCount++){

FLOWCALC = countA/((pTime-cTime)/1000)*60;

I don't know the datatypes of the vars used but if ptime and ctime are int/long and √£pprox 40 apart, dividing by 1000 will return zero * 60 is still zero.
Integer math is not forgiving.

Try this formula instead (make ptime and ctime and flowcalc unsigned long )

FLOWCALC = (countA * 60000L)/(pTime-cTime);

Style remark:
It is quite common in C/C++ to write constants/#defines only in upper case and variables not. So FLOWCALC is misleading because of its style.



Rob Tillaart

Nederlandse sectie - http://arduino.cc/forum/index.php/board,77.0.html -
(Please do not PM for private consultancy)

Go Up
 


Please enter a valid email to subscribe

Confirm your email address

We need to confirm your email address.
To complete the subscription, please click the link in the email we just sent you.

Thank you for subscribing!

Arduino
via Egeo 16
Torino, 10131
Italy