🌐
Rip Tutorial
riptutorial.com › measure how long something took, using elapsedmillis and elapsedmicros
arduino Tutorial => Measure how long something took, using...
#include <elapsedMillis.h> void setup() { Serial.begin(115200); elapsedMillis msTimer; elapsedMicros usTimer; long int dt = 500; delay(dt); long int us = usTimer; long int ms = msTimer; Serial.print("delay(");Serial.print(dt);Serial.println(") took"); Serial.print(us);Serial.println(" us, or"); Serial.print(ms);Serial.println(" ms"); } void loop() { }
🌐
PJRC
pjrc.com › teensy › td_timing_elaspedMillis.html
Using elapsedMillis & elapsedMicros
#include <Bounce.h> Bounce myButton = Bounce(2, 10); // pushbutton on pin 2 elapsedMillis sincePrint; void setup() { Serial.begin(9600); pinMode(2, INPUT_PULLUP); } void loop() { myButton.update(); if (myButton.fallingEdge()) { Serial.println("Button Press"); } if (myButton.risingEdge()) { Serial.println("Button Release"); } if (sincePrint > 2500) { // "sincePrint" auto-increases sincePrint = 0; Serial.println("Print every 2.5 seconds"); } }
Discussions

How to implement elapsed millis as the timer for my motor spinning time?
First of all, put 4 spaces in front of every line. That's how you format for code on reddit. You can implement a timer like this... unsigned long startTime = 0; const unsigned long delayTime = 1000; // how long you want your delay to be, in this case 1000 mS loop() { unsigned long currentTime = millis(); unsigned long elapsedTime = currentTime - startTime; if (elapsedTime > delayTime) { // Do the stuff you were waiting for startTime = currentTime; // reset your delay timer } // Do the other stuff you wanted to do } Be aware that at some point, the microprocessor delay timer is going to roll over from max value to 0. At that point this code is going to stop working. If you are going to run this code for days at a time you will need to handle that case. edit: I really should have used unsigned long More on reddit.com
🌐 r/arduino
3
2
April 8, 2017
arduino uno - How to implement elapsed millis as the timer for my motor spinning time? - Arduino Stack Exchange
As for managing the servo stages, simplest thing would be to write a finite state machine. I would write it with four states: IDLE, STAGE1, STAGE2 and STAGE3. The transitions STAGE1 → STAGE2 → STAGE3 → IDLE would be time-based, using the elapsedMillis object to track the time spent in ... More on arduino.stackexchange.com
🌐 arduino.stackexchange.com
April 8, 2017
millis - Question about ElapsedMillis() library and state machines - Arduino Stack Exchange
I'm making a sort of state machine with 3 states, and I'm actually doing some tests by configuring at the start of my code state=3. I've wired on each pin 2 leds, for a total of 12 leds. I'm using More on arduino.stackexchange.com
🌐 arduino.stackexchange.com
December 11, 2021
elapsedMillis and elapsedMicros library
Folks, for anyone interested, here is elapsedMillis and elapsedMicros (adapted by pfeerick from work done by Paul Stoffregen) simplifies timing loops a lot. This codes required NO adaptation for the Spark so I take no credit :smile: Here it is with an simple LED blink example. More on community.particle.io
🌐 community.particle.io
9
4
February 7, 2014
🌐
Arduino
arduino.cc › reference › en › libraries › elapsedmillis
elapsedMillis | Arduino Documentation
May 8, 2022 - elapsedMillis · Home / Programming / Library / elapsedMillis · Timing · MIT License · V1.0.6 · Paul Stoffregen · 08/01/2024 · Peter Feerick <peter.feerick@gmail.com> http://github.com/pfeerick/elapsedMillis/wiki · peter.feerick@gmail.com · Makes coding responsive sketches easier.
🌐
Codebender
codebender.cc › example › elapsedMillis › GettingStarted
Library example: elapsedMillis : GettingStarted
Arduino IDE in the Cloud. Codebender includes a Arduino web editor so you can code, store and manage your Arduino sketches on the cloud, and even compile and flash them.
🌐
GitHub
github.com › pfeerick › elapsedMillis
GitHub - pfeerick/elapsedMillis: Arduino 'port' of the elapsedMillis library · GitHub
Initial code derived from Paul Stoffregen's elapsedMillis and elapsedMicros helper code for the Teensy USB developer board.
Starred by 89 users
Forked by 26 users
Languages   C++
🌐
GitHub
github.com › pfeerick › elapsedMillis › blob › master › elapsedMillis.h
elapsedMillis/elapsedMillis.h at master · pfeerick/elapsedMillis
elapsedMillis(void) { ms = millis(); } elapsedMillis(unsigned long val) { ms = millis() - val; } elapsedMillis(const elapsedMillis &orig) { ms = orig.ms; } operator unsigned long () const { return millis() - ms; } elapsedMillis & operator = (const elapsedMillis &rhs) { ms = rhs.ms; return *this; } elapsedMillis & operator = (unsigned long val) { ms = millis() - val; return *this; } elapsedMillis & operator -= (unsigned long val) { ms += val ; return *this; } elapsedMillis & operator += (unsigned long val) { ms -= val ; return *this; } elapsedMillis operator - (int val) const
Author   pfeerick
🌐
Codebender
codebender.cc › example › elapsedMillis › timingComparison
Library example: elapsedMillis : timingComparison
Arduino IDE in the Cloud. Codebender includes a Arduino web editor so you can code, store and manage your Arduino sketches on the cloud, and even compile and flash them.
🌐
Reddit
reddit.com › r/arduino › how to implement elapsed millis as the timer for my motor spinning time?
r/arduino on Reddit: How to implement elapsed millis as the timer for my motor spinning time?
April 8, 2017 -

I have been using delay() as the function for my motor spinning time. However, at the same time, I need to calculate the rpm of my motor. Delay() function have to make it impossible for me to get the rpm whilst the motor spin. I have learned that I needed to use Elapsed millis as a replacement for delay() for my timing.

I have tried it and to no avail, I did not get the result in wanted. Yes, the motor spin according to the speed that I desired, however, it does not spin according to the time I wanted. It kept on spinning non-stop till I have to disconnect the power supply.

So, my question is, how do I implement the elapsed millis as my timer for my spinning motor? please, guys, help me with this... Just guide me through and give me guidance.

This is my code that I have tried using elapsed millis. Any suggestion is welcome.

include <elapsedMillis.h>

include <Keypad.h>

include <Wire.h> // Comes with Arduino IDE

include <LiquidCrystal_I2C.h>

include <Servo.h>

Servo myservo; LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE); // Set the LCD I2C address elapsedMillis timeElapsed;

const byte ROWS = 4; //four rows const byte COLS = 3; //three columns char keys[ROWS][COLS] = { {'1', '2', '3'}, {'4', '5', '6'}, {'7', '8', '9'}, {'*', '0', '#'} };

byte rowPins[ROWS] = {9,8,7,6}; //row pinouts of the keypad (L1, L2, L3, L4) byte colPins[COLS] = {5,4,3}; //column pinouts of the keypad (R1, R2, R3) Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );

void setup() {

Serial.begin(9600); lcd.begin(20,4); myservo.attach(11);

lcd.setCursor(0,0); lcd.print("S="); lcd.setCursor(0,1); lcd.print("T="); lcd.setCursor(0,2); lcd.print("S="); lcd.setCursor(0,3); lcd.print("T="); lcd.setCursor(10,0); lcd.print("S="); lcd.setCursor(10,1); lcd.print("T="); lcd.setCursor(10,2); lcd.print("RPM");

}

void loop()

{

int stage1speed = getTheNumber(); lcd.setCursor(2,0); lcd.print(stage1speed); lcd.print("sv"); int stage1time = getTheNumber(); lcd.setCursor(2,1); lcd.print(stage1time); lcd.print("sec");

int stage2speed = getTheNumber(); lcd.setCursor(2,2); lcd.print(stage2speed); lcd.print("sv"); int stage2time = getTheNumber(); lcd.setCursor(2,3); lcd.print(stage2time); lcd.print("sec");

int stage3speed = getTheNumber(); lcd.setCursor(12,0); lcd.print(stage3speed); lcd.print("sv"); int stage3time = getTheNumber(); lcd.setCursor(12,1); lcd.print(stage3time); lcd.print("sec");

if ( stage1speed > 0 && stage1time > 0 && stage2speed > 0 && stage2time > 0 && stage3speed > 0 && stage3time > 0 )

{

if(timeElapsed <= 1000*stage1time)

{

 myservo.write(stage1speed);

 }

if(timeElapsed <= 1000*stage2time)

{

 myservo.write(stage2speed);

 }

if(timeElapsed <= 1000*stage3time)

{

 myservo.write(stage3speed);

 }

}

}

int getTheNumber() { char buffer[4]; // Input up to 3 numbers until we find a * or # int i=0; while (1) { char key = keypad.getKey();

    // If it's a number AND we have space left, add to our string
    if ('0' <= key && key <= '9' && i < 3)
    {
        buffer[i] = key;
        i++;        
    }
    // If it's a * or #, end
    else if ('#' == key && i > 0)
    {
        // Null terminate
        buffer[i] =0; 
       int value = atoi(buffer);  // Convert to an integer
        break;
    } 

}
return atoi(buffer);
}
Find elsewhere
Top answer
1 of 1
1

delay() is only the tip of the iceberg. The problem with delay() is that it is a blocking function: nothing else can be done during the delay. If you want to control your motor and at the same time be responsive to the user, you must avoid blocking your program. This means not only getting rid of delay(), but also getting rid of any blocking function.

Here your problem is on getTheNumber(). This function blocks until the user is done typing the number. Try to rewrite it in a non-blocking fashion. For example, it could return -1 on every call as long as the user is not done typing the number. On the first call after the user is done it would return the valid value. If you manage to write everything non-blocking, then you loop() will restart very often, and the program will work with no significant latency.

As for managing the servo stages, simplest thing would be to write a finite state machine. I would write it with four states: IDLE, STAGE1, STAGE2 and STAGE3. The transitions STAGE1 → STAGE2 → STAGE3 → IDLE would be time-based, using the elapsedMillis object to track the time spent in each state. The transition IDLE → STAGE1 would be triggered by the user input.

static enum { IDLE, STAGE1, STAGE2, STAGE3 } state;
switch (state) {
    case IDLE:
        if (userRequestedToStartAgain()) {
            myservo.write(stage1speed);
            state = STAGE1;
            timeElapsed = 0;
        }
        break;
    case STAGE1:
        if (timeElapsed >= stage1time) {
            myservo.write(stage2speed);
            state = STAGE2;
            timeElapsed = 0;
        }
        break;
    case STAGE2:
        if (timeElapsed >= stage2time) {
            myservo.write(stage3speed);
            state = STAGE3;
            timeElapsed = 0;
        }
        break;
    case STAGE3:
        if (timeElapsed >= stage3time) {
            myservo.write(idleValue);
            state = IDLE;
        }
        break;
}
🌐
Thekurks
thekurks.net › blog › 2016 › 4 › 8 › tutorial-delay-vs-timer
Tutorial: How and Why to use Timers instead of the Delay() Function — The Arduino Maker Man
March 14, 2018 - I created 2 example sketches to show the effects of the delay() function and what happens when using the elapsedMillis.h library.
Address   Vancouver, BC Canada
🌐
GitHub
github.com › pfeerick › elapsedMillis › blob › master › examples › timingComparison › timingComparison.ino
elapsedMillis/examples/timingComparison/timingComparison.ino at master · pfeerick/elapsedMillis
set. When you set an elapsedMillis variable to 0 (zero), 1 · millisecond later it will contain 1, not 0. 1385 milliseconds · later, it will contain 1385. · You can set/reset these variables to whatever value you want, whenever you ...
Author   pfeerick
🌐
GitHub
github.com › pfeerick › elapsedMillis › wiki
Home · pfeerick/elapsedMillis Wiki · GitHub
When elapsedMillis is created as a local variable (inside the function), it automatically starts at zero each time the function executes.
Author   pfeerick
Top answer
1 of 1
2

You need to maintain more state information to have 'case 3' work like a KITT-style back and forth LED scanner. I think you can do it with three state variables, j for which pair of LEDs is active, backwardsScan to say which way to go, and timer4 to remember where in the 91ms cycle we are with the active pair of LEDs.

Try something like this:

...
int backwardsScan = 0;
...

case 3: // KITT-like scanning back and forth 90us/1us
  // j remembers which LED pair is active
  // backwardsScan remembers which direction to scan
  // timer4 handles the 90ms/1ms on-off cycle.
  // 
  // reset output leds appropriately for (j,timer4):
  for(int ii=0;ii<=5;ii++){
    digitalWrite(ledArray[ii],( (ii==j) && (timer4 <90))); 
  }
  // update KITT state based on (j,backwardsScan,timer4)
  if(timer4 > 91){ 
     j += backwardsScan? -1 : 1 ;
     if (j > 5){
        backwardsScan = 1;
        j = 5;
        }
     if (j < 0) {
        backwardsScan = 0;
        j = 0;
        }
     timer4 = 0;
     }

  break;

The main trick with state machines is being able to fully determine the complete state from what you are keeping track of--It should be memoryless, in that the state variable(s) fully specify the state, and you don't need to remember the prior state. If you find you need to know more than one thing, you might need a vector or set of state variables. One could map the whole led-backwardsScan-timer4 state vector into a single state variable (timer4, modulo 182ms for example,) but that would be unnecessarily complicated. Recognizing all the variables required to fully specify the state is important.

🌐
GitHub
github.com › PaulStoffregen › cores › blob › master › teensy › elapsedMillis.h
cores/teensy/elapsedMillis.h at master · PaulStoffregen/cores
elapsedMillis(void) { ms = millis(); } elapsedMillis(unsigned long val) { ms = millis() - val; } elapsedMillis(const elapsedMillis &orig) { ms = orig.ms; } operator unsigned long () const { return millis() - ms; } elapsedMillis & operator = (const elapsedMillis &rhs) { ms = rhs.ms; return *this; } elapsedMillis & operator = (unsigned long val) { ms = millis() - val; return *this; } elapsedMillis & operator -= (unsigned long val) { ms += val ; return *this; } elapsedMillis & operator += (unsigned long val) { ms -= val ; return *this; } elapsedMillis operator - (int val) const
Author   PaulStoffregen
🌐
Arduino Libraries
arduinolibraries.info › libraries › elapsed-millis
elapsedMillis - Arduino Libraries
December 2, 2019 - https://github.com/pfeerick/elapsedMillis/wiki · Github · https://github.com/pfeerick/elapsedMillis · Category · Timing · License · MIT · Library Type · Contributed · Architectures · Any · When using delay(), your code can not (easily) respond to user input while the delay is happening ...
🌐
Particle
community.particle.io › firmware › libraries
elapsedMillis and elapsedMicros library - Libraries - Particle
February 7, 2014 - Folks, for anyone interested, here is elapsedMillis and elapsedMicros (adapted by pfeerick from work done by Paul Stoffregen) simplifies timing loops a lot. This codes required NO adaptation for the Spark so I take no credit 😄 Here it is with an simple LED blink example.
🌐
Arduino Forum
forum.arduino.cc › projects › programming
How to implement elapsed millis as the timer for my motor spinning time? - Programming - Arduino Forum
April 8, 2017 - I have been using delay() as the function for my motor spinning time. However, at the same time, I need to calculate the rpm of my motor. Delay() function have to make it impossible for me to get the rpm whilst the motor spin. I have learned that I needed to use Elapsed millis as a replacement for delay() for my timing.
🌐
GitHub
github.com › PaulStoffregen › cores › blob › master › teensy4 › elapsedMillis.h
cores/teensy4/elapsedMillis.h at master · PaulStoffregen/cores
elapsedMillis(void) { ms = millis(); } elapsedMillis(unsigned long val) { ms = millis() - val; } elapsedMillis(const elapsedMillis &orig) { ms = orig.ms; } operator unsigned long () const { return millis() - ms; } elapsedMillis & operator = (const elapsedMillis &rhs) { ms = rhs.ms; return *this; } elapsedMillis & operator = (unsigned long val) { ms = millis() - val; return *this; } elapsedMillis & operator -= (unsigned long val) { ms += val ; return *this; } elapsedMillis & operator += (unsigned long val) { ms -= val ; return *this; } elapsedMillis operator - (int val) const
Author   PaulStoffregen