11 months, 1 week ago.

Trouble changing a number with an interrupt

Hello fellow coders.

I've been working with the STM32 and the project shield for a while now and have been struggling with a simple case of interrupts and pointers for a while now. The aim of the below program is simply to set the the variable 'number' to 1 and display it on the lcd, and then, after the joystick on the application shield has been pressed in the up direction, the variable 'number' would change to 2 and would be displayed.

The program seems to compile correctly and display 1 but the number 2 never appears, regardless of whether i press up or not

  1. include "mbed.h"
  2. include "C12832.h"

C12832 lcd(D11, D13, D12, D7, D10);

class Time{ public:

int number;

void setnum(){ number=1; }

void setnum2(){ number=2; }

int getno(){ return number; }

private:

};

class joystick{ public: InterruptIn up; Time* Timep;

joystick(PinName uppin,Time* Timepointer):up(uppin),Timep(Timepointer){ up.rise(callback(Timep, &Time::setnum2)); };

void callnum2(){ Timep->setnum2(); } }; int main (void){ Time* Timepointer = new Time(); joystick(A2,Timepointer); Timepointer-> setnum(); lcd.cls(); lcd.locate(40,10); lcd.printf("%d",Timepointer->number); int n; while(1){ n = Timepointer->getno(); lcd.locate(40,10); lcd.printf("%d",n); }

}

Comment on this question

1 Answer

11 months, 1 week ago.

Hello Zachary,

Try to declare the number variable as volatile.

volatile int number;

This is necessary because the compiler does not know anything about interrupts and thinks that functions you designed to handle interrupts (interrupt service routines) will never be called (they aren't directly called at any point in your code). Hence it will optimize your code and discard those functions to save memory. However, when you declare a variable as volatile it means for the compiler that such variable can change its value (for a reason that is a mistery for the compiler) any time during the program execution and prevents the compiler to optimize the related code.

ADVISE: To have a more readable code after pasting it here (to mbed pages) try to mark it up as below (with <<code>> and <</code>> tags, each on separate line at the begin and end of your code)

<<code>>
text of your code
<</code>>


You need to log in to post a question