incrementing a variable by a sub() attached to Ticker

15 Mar 2012

Is it possible to increment a variable by a sub() attached to ticker and how. Some code please

15 Mar 2012

Hi Markos, below is a modified example from the handbook. The code will toggle the LED and increment variable 'a' once every 2 seconds. The variable counts up to 99 and then resets.

#include "mbed.h"

Ticker flipper;
DigitalOut led1(LED1);
DigitalOut led2(LED2);

int a=0;

void flip() {
    led2 = !led2;
    a=a+1;
    if (a==100) { a=0 };
}

int main() {
    led2 = 1;
    flipper.attach(&flip, 2.0); // the address of the function to be attached (flip) and the interval (2 seconds)

    // spin in a main loop. flipper will interrupt it to call flip
    while(1) {
        led1 = !led1;
        wait(0.2);
    }
}

17 Mar 2012

Hi Wim Thank you very much Markos What I am trying is to sample mains using ticker, find zero crossing and control the speed of a fan by PWM

17 Mar 2012

Hi Wim I run the following code. On putty a see the first print out.The second print out when a==10 never appears on putty. How can I check that "a" really changes each time ticker ticks ?

#include "mbed.h"
Serial pc(USBTX,USBRX);
Ticker flipper;
DigitalOut led1(LED1);
DigitalOut led2(LED2);

int a=0;

void flip() {
    led2 = !led2;
    a=a+1;
   // if (a==100) { a=0; };
}

int main() {

pc.printf(" \n,\r begining of 10 ticks  \t  ");

    led2 = 1;
    flipper.attach(&flip, 2.0); // the address of the function to be attached (flip) and the interval (2 seconds)

    // spin in a main loop. flipper will interrupt it to call flip
    //while(1) {
      //  led1 = !led1;
       // wait(0.2);
    //}
    
    if (a==10) {pc. printf(" \n,\r end of 10 ticks  \t  %d, \n,\r",a);} ;
}


17 Mar 2012

Markos,

Your main() routine no longer has any loop, so it just ends before 'a' reaches 10. Try -

  /* if (a==10) */ while (a < 10) ; pc.printf(" \n,\r end of 10 ticks  \t  %d, \n,\r",a);

The semicolon in front of the pc.printf() will provide the necessary delay.

17 Mar 2012

Fred thank you for your valuable remark Markos

18 Mar 2012

I am trying to understand Ticker and if a global variable modified by function attached to Ticker can be seen from other parts of main().The programm never exits while(k<100).Why variable k is invisible? Using wait(2) the program exits normally

#include "mbed.h"
Serial pc(USBTX, USBRX);
int k;

Ticker ten_millisec;

void  test_global_var() {    k++; };

main()  {  k=0;  pc.printf(" \n,\r beginng of interrupt time \t  %d, \n,\r",k);
      
     ten_millisec.attach_us( &test_global_var ,10000); //wait(2);
     
       while (k<100)  {   };
            
    pc.printf(" \n,\r end of interrupt time \t  %d, \n,\r",k);
}
18 Mar 2012

Hi,

I think you should define k as volatile variable like following.

volatile int k;
18 Mar 2012

Hi Yuji Thank you.Volatile worked beatifully Markos