Important changes to forums and questions
All forums and questions are now archived. To start a new conversation or read the latest updates go to forums.mbed.com.
5 years, 9 months ago.
What's wrong with my code? Only works with an extra printf in main().
So I'm a bit of a noob when it comes to C/C++ to go easy on me. However, I've been playing around with some of the examples and am trying to get the following simple NTP example working. I'm using mbed-cli 1.8.3 with a nucleo_f767zi. I'm using the USER_BUTTON on the board to toggle an LED via InterruptIn and also to set a flag that should request and print out the current time.
However, it only works if I add some dummy printf to the main while loop outside of the flag test. What is going on?
#include "mbed.h" #include "stats_report.h" #include "ntp-client/NTPClient.h" #include "EthernetInterface.h" DigitalOut led1(LED1); InterruptIn btn(USER_BUTTON); Serial usb(USBTX, USBRX); EthernetInterface eth; int flag = 0; void buttonIsr() { flag = 1; led1 = !led1; } // main() runs in its own thread in the OS int main() { eth.connect(); usb.printf("ip address = %s\n\r", eth.get_ip_address()); btn.rise(&buttonIsr); NTPClient ntp(ð); time_t timestamp = ntp.get_timestamp(); usb.printf("Current time is %s\n\r", ctime(×tamp)); while (1) { if (flag == 1) { usb.printf("button pushed\n\r"); timestamp = ntp.get_timestamp(); while(timestamp < 0) { wait(1); timestamp = ntp.get_timestamp(); } usb.printf("Current time is %s\n\r", ctime(×tamp)); flag = 0; } } }
1 Answer
5 years, 9 months ago.
Hello, Shareef
Since the compiler does not know anything about interrupts and the interrupt service routine isn't called directly at any point in your code, it concludes that it's a good candidate for code optimization/reduction. You can prevent such optimization by declaring the flag
variable as volatile
.
volatile int flag = 0;
It will mean for the compiler that such variable can change its value any time during the program execution and it won't optimize the related code.
NOTE: When you tried to print the flag
variable in the main
function the compiler was prevented to optimize the flag
related code as well that's why it worked as expected.