5 years, 10 months ago.

Ticker attach_us with <vector> messes the first item of <vector> up

I have 2 classes: Sample that holds a value of i and Trier that has a couple of Sample's in vector<Sample*> vec. The code below sends the values of i from a Sample in Trier::vec to the terminal via STM32 development board. The problem is as follows:

If you Trier::printI() just before before Ticker::attach_us(), I get the right value of i, but in the Ticker::attach_us, I get weird value printed in the terminal for vec[0]. The funny thing is that if you replace vec[0]->getI() in Trier::printI() to index of 1 like this vec[1]->getI(), the value of i for the 2nd Sample in vec is printed fine.

I broke my head on this. Could anyone tell what the heck if going on?

main.cpp

#include <iostream>
#include <vector>
#include "mbed.h"

class Sample
{
    public:
        Sample(int i) : i(i) {}
        int getI() {return i;}
    protected:
        int i;
};

class Trier
{
    protected:
        vector<Sample*> vec;
    public: 
        Trier(Sample* s1, Sample* s2, Sample* s3)
        {
            vec.push_back(s1);
            vec.push_back(s2);
            vec.push_back(s3);
        }
        
        void printI() 
        {
            printf("vector's i = %i\n", vec[0]->getI());
        }
        
        vector<Sample*> getVec() {return vec;}
};

Ticker t;

int main() 
{   
    Sample* s1;
    Sample* s2;
    Sample* s3;
    
    s1 = new Sample(10);
    s2 = new Sample(20);
    s3 = new Sample(30);

    Trier trier(s1, s2, s3);
    trier.printI();
    t.attach_us(callback(&trier, &Trier::printI), 1000000);
}

1 Answer

5 years, 10 months ago.

Hello Dima,

I believe you need an infinite while loop running when using Ticker. For instance:

    Trier trier(s1, s2, s3);
    trier.printI();
    t.attach_us(callback(&trier, &Trier::printI), 1000000);
}

//new code
while(1){
}

I added the empty while loop and it was working properly. Hope this helps!

-Karen, team Mbed

If this solved your question, please make sure to click the "Thanks" link below!

Hi Karen,

To say that you saved a poor man's life is to say nothing. :-) Thank you VERY much, Karen. I wonder why the while loop plays a role here? Do you have any clues?

posted by Dima Dzibrou 27 Jun 2018

Hi Dima,

I'm glad it worked out! I believe you need your program to be constantly running in order for the Ticker to properly interrupt, however I am not sure why only s1 was affected the way it was.

-Karen, team Mbed

posted by Karen Yen 27 Jun 2018

Thanks, Karen!

posted by Dima Dzibrou 01 Jul 2018