Manejo de Timers

Dependencies:   mbed

main.cpp

Committer:
lscordovar
Date:
2020-02-07
Revision:
0:57171dc76fb5

File content as of revision 0:57171dc76fb5:

#include "mbed.h"
Timer timer1; // define timer object
DigitalOut output1(p5); // digital output

void task1(void); // task function prototype

int main()
{
    timer1.start(); // start timer counting
    while(1) {
        if (timer1.read_ms()>=200) { // read time in ms
            task1(); // call task function
            timer1.reset(); // reset timer
        }
    }
}
void task1(void)  // task function
{
    output1=!output1; // toggle output
}

/*
Using multiple timers
*/
//*** main code
int main()
{
    timer1.start(); // start timer1 counting
    timer2.start(); // start timer2 counting
    while(1) {
        if (timer1.read_ms()>=200) { // read time
            task1(); // call task1 function
            timer1.reset(); // reset timer
        }
        if (timer2.read_ms()>=1000) { // read time
            task2(); // call task2 function
            timer2.reset(); // reset timer
        }
    }
}
// continued...
// ...continued
//*** task functions
void task1(void)
{
    output1=!output1; // toggle output1
}
void task2(void)
{
    output2=!output2; // toggle output2
}

/*
Using the mbed Ticker object
Exercise:
Use two tickers to create square wave outputs.
Use an LED or an oscilloscope on the
mbed pins to check that the two tickers
are executing correctly.
*/

#include "mbed.h"
Ticker flipper1;
Ticker flipper2;
DigitalOut led1(p5);
DigitalOut led2(p6);

void flip1()   // flip 1 function
{
    led1 = !led1;
}

void flip2()   // flip 2 function
{
    led2 = !led2;
}

int main()
{
    led1 = 0;
    led2 = 0;

    flipper1.attach(&flip1, 0.2); // the address of the
// function to be attached
// and the interval (sec)
    flipper2.attach(&flip2, 1.0);
// spin in a main loop
// flipper will interrupt it to call flip

    while(1) {
        wait(0.2);
    }
}

/*
External interrupts on the mbed
*/


#include "mbed.h"
InterruptIn button(p18); // Interrupt on digital pushbutton input p18
DigitalOut led1(p5); // digital out to p5

void toggle(void); // function prototype

int main()
{
    button.rise(&toggle); // attach the address of the toggle
} // function to the rising edge

void toggle()
{
    led1=!led1;
}

/*
Switch debouncing for interrupt control
*/

#include "mbed.h"
InterruptIn button(p18); // Interrupt on digital pushbutton input p18
DigitalOut led1(p5); // digital out to p5
Timer debounce; // define debounce timer

void toggle(void); // function prototype

int main()
{
    debounce.start();
    button.rise(&toggle); // attach the address of the toggle
} // function to the rising edge

void toggle()
{
    if (debounce.read_ms()>200) // only allow toggle if debounce timer
        led1=!led1; // has passed 200 ms
    debounce.reset(); // restart timer when the toggle is performed
}