Hi everyone, I'm writing a very simple program to test how fast the arduino uno work by usuing the timer inturrept, my first code is as follow:
#include <MsTimer2.h>
unsigned long c = 0;
void setup(void){
MsTimer2::set(1000, intProc); //trigger intProc every 1 second
MsTimer2::start();
Serial.begin(9600);
}
void loop(void){
while(true) c++;
}
void intProc(void){
Serial.println(c); //send the contents of c via serial port
}
But the serial monitor shows the value of the global variable c is always 0, I don't know why.
Then, I modified the code, the intProc just set a global boolean variable to indicates the main loop to output the value of c:
#include <MsTimer2.h>
boolean p = false;
unsigned long c = 0;
void setup(void){
MsTimer2::set(1000,intProc);
MsTimer2::start();
Serial.begin(9600);
}
void loop(void){
while(true) {
c++;
if(p) {
Serial.println(c);
p = false;
}
}
}
void intProc(void) {
p = true;
}
But this time the serial monitor show nothing, Serial.println was not executed at all.
The most strangest thing happens, when I move the delcaration of variable c inside the loop() function, the program works! I get the value of c once a second in the serial monitor, just one line modified:
#include <MsTimer2.h>
boolean p = false;
void setup(void){
MsTimer2::set(1000,intProc);
MsTimer2::start();
Serial.begin(9600);
}
void loop(void){
unsigned long c = 0;
while(true) {
c++;
if(p) {
Serial.println(c);
p = false;
}
}
}
void intProc(void) {
p = true;
}
After that I add a one line to reset c to zero after Serial.println is executed, but the program does not work a gain, the serial monitor get nothing at all:
#include <MsTimer2.h>
boolean p = false;
void setup(void){
MsTimer2::set(1000,intProc);
MsTimer2::start();
Serial.begin(9600);
}
void loop(void){
unsigned long c = 0;
while(true) {
c++;
if(p) {
Serial.println(c);
p = false;
c = 0;
}
}
}
void intProc(void) {
p = true;
}
Strange and interesting problem, I can't fine the reason, can anybody give me an explaination to me? Thank you very much.