Skip to end of metadata
Go to start of metadata

You are viewing an old version of this content. View the current version.

Compare with Current View Version History

Version 1 Next »

Purpose

Delay a task in time or make it repeat periodically without blocking the CrcDuino.

When to use

When you want to run something after x ms or each x ms.

Where to use

Inside the loop function, after having declared a variable with the correct type.

The timer needs to retain its value and, as such, should generally be declared in the global scope.

Returns

Timer.Start() and Timer.Next() do not return anything. Timer.IsFinished() returns true if the requested time has elapsed or false if it has not.

Main prototype and parameters

void Crc::Timer::Start(unsigned long delay_ms)

The following parameters must be passed to the function for it to work properly:

  • The delay the timer wants to wait for, in milliseconds.

bool Crc::Timer::IsFinished()

The following parameters must be passed to the function for it to work properly:

  • No parameters needed.

void Crc::Timer::Next()

The following parameters must be passed to the function for it to work properly:

  • No parameters needed.

Overloads

This function does not have any overloads. It can only be used as described by the main prototype.

Examples

 #1: Perform an action each 10 ms
#include <CrcLib.h>

using namespace Crc;

Timer timer;
void setup() {
    CrcLib::Initialize();
    
    // Start the timer with a period of 10 ms
    timer.Start(10);

    /* 
    The rest of your setup code
    ...
     */
}
void loop() {
    CrcLib::Update();
    
    if (timer.IsFinished()) { // 10 ms has elapsed
        timer.Next(); // Start the next period of the timer
        
        // Do the logic you want to do each 10 ms
    }
    
    /* 
    The rest of your looping code
    ...
    */
}
 #2: Perform an action 1s after a button press (advanced)
#include <CrcLib.h>

using namespace Crc;

void setup() {
    CrcLib::Initialize();

    /* 
    The rest of your setup code
    ...
     */
}

Timer timer;
bool waiting = false;
void loop() {
    CrcLib::Update();
    
    bool buttonPressed = CrcLib::ReadDigitalChannel(BUTTON::COLORS_LEFT);
    // If the left button of the "colors" block is pressed
    //   and we weren't already waiting
    if (!waiting && buttonPressed) {
        // Start the timer with a period of 1000 ms (1s)
        timer.Start(1000);
        waiting = true; // We are now waiting
    }
    
    // If we were waiting and 1s has elapsed
    if (waiting && timer.IsFinished()) {
        // We are no longer waiting
        waiting = false;
        
        // Do what you wanted to do after 1s here
        // ...
    }
    
    /* 
    The rest of your looping code
    ...
    */
}
  • No labels

0 Comments

You are not logged in. Any changes you make will be marked as anonymous. You may want to Log In if you already have an account.