#include "mbed.h"
#include <Callback.h>
InterruptIn up(p14);
void toggle1(int *player)
{
printf("%d \n", *player);
}
int main()
{
int player = 1;
up.rise(callback(toggle1, &player));
}
why the result is not 1? It is 12784.
#include "mbed.h"
#include <Callback.h>
InterruptIn up(p14);
void toggle1(int *player)
{
printf("%d \n", *player);
}
int main()
{
int player = 1;
up.rise(callback(toggle1, &player));
}
why the result is not 1? It is 12784.
Hello,
please see InterruptIn - API references and tutorials | Mbed OS 6 Documentation.
You can not pass any parameters directly to it, you can do it only via your own class or with global volatile variable.
BR, Jan
Hello Rui,
In addition to what Jan says the int player
variable is created on the stack in the main
function. Since there is no endless loop in the main
it is terminated after calling the up.rise
function and the player
variable goes out of scope (the stack is “destroyed/released”). So when you push the button later on there is no such valid memory location as the player
anymore (or its located elsewhere), hence its value is random. To prevent that, try to include an endless loop in the main
. For example:
int main()
{
int player = 1;
up.rise(callback(toggle1, &player));
while(1){};
}
But I want to use &toggle1 in different buttons, which gives different values of player
. How can I do this?
I cannot use while(1){};
in simulator. It will be stuck.
What a shame! Then try to declare the player
as global variable.
Ok, maybe something like this
#include "mbed.h" //Mbed2
DigitalOut myled(LED1);
class Player {
public:
Player(PinName pin, int playerId) : _interrupt(pin), _playerId(playerId)
{
_interrupt.rise(callback(this, &Player::printPlayerId));
}
void printPlayerId()
{
printf("%d \n", getPlayerId());
}
int getPlayerId()
{
return _playerId;
}
private:
InterruptIn _interrupt;
volatile int _playerId;
};
int main() {
printf("Buttons for players\n");
Player p1(USER_BUTTON, 1);
while(1) {
myled = !myled;
wait(0.2);
}
}
Because it is now possible compile Mbed2 projects with KeilStudio online and I wanted to try this, I tested the code above with Nucleo-F446RE and under Mbed2.
I do not know what rules or Mbed library are used for Simulator, but with full MbedOS (5.12 and up) is not able to use the printf directly in any interrupt context because of Mutex. You must use it with EventQueue or with a simple flag or with bare metal profile of MbedOS or any older version of MbedOs than 5.12 (Mbed2 included)
BR, Jan