Hi, I am a noob and I have this very simple program, but "NbPulse" is stuck at 1.
void setup()
{
Serial.begin(9600);
}
void loop()
{
int NbPulse;
NbPulse++;
Serial.println (NbPulse);
delay(1000);
}
Can someone help me?
Hi, I am a noob and I have this very simple program, but "NbPulse" is stuck at 1.
void setup()
{
Serial.begin(9600);
}
void loop()
{
int NbPulse;
NbPulse++;
Serial.println (NbPulse);
delay(1000);
}
Can someone help me?
void loop()
{
int NbPulse;
You are reinitializing NbPulse at each loop.
Make it global by moving it above loop(), or
Make it static by static int NbPulse
Some reading material: scope - Arduino Reference.
Thanks it worked!
What is the initial value of NbPulse? How much it should be at time t0 sec? How much it should be after t0+1 sec? How much it should be after t0+2 sec?
Nope!
NbPulse is created each time loop() runs and gets destroyed each time loop() ends. But it is never initialised, never given an initial value.
Global and static variables are automatically initialized to zero as the sketch starts to run. But local variables, like this one, are not initialised to anything, they can contain any "random" value when they are created. Bytes of memory are allocated to hold the variable's value and those bytes might have been previously used for some other purpose, and contain some values left behind.
Often, in circumstances like this, the same bytes are allocated to a variable over and over, and it seems to a beginner like the previous value is being persisted from one call of loop() to the next. But that's just dumb luck, and should never be relied on. I was a little surprised that that isn't happening in this case.
It's wise to always explicitly initialise all variables, especially local variables, to a known value.
Thank you for clarifying this. The devil is in the details.
Worse than that, ask me how I know, is that using an unitialised variable doesn't only mean you get a random value, it means you've crossed a line called "undefined behaviour" and some truly inexplicable, bizarre and difficult to find errors can occur.
See
a7
This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.