Loading...
Pages: [1]   Go Down
Author Topic: micros() help  (Read 324 times)
0 Members and 1 Guest are viewing this topic.
Offline Offline
Newbie
*
Karma: 0
Posts: 2
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Here is my code.When i is 100,the result of the serial is 96.But When i is 10000,the result is still 96.If i change"a++" into "Serial.print(1)",the result changed. smiley-confuse
Code:
void setup(){
  Serial.begin(9600);
}
void loop(){
  long i,a;
  for(i=0;i<100;i++){a++;}
  Serial.println(micros());
  exit(1);
}
Logged

Newcastle, UK
Offline Offline
Newbie
*
Karma: 0
Posts: 20
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Shouldn't you be declaring "a=0" instead of just "a" ?
Logged

0
Offline Offline
God Member
*****
Karma: 0
Posts: 592
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

probably an optimization issue, the compiler probably knew that "a" was useless and didn't bother running your for-loop, but if you tell it to output "1", then it's forced to actually send that out the serial port, thus the for-loop remained in that case

solve the problem by using a NOP instruction in the for-loop, that's what I would do. Or make "i" volatile.
« Last Edit: February 27, 2011, 08:41:54 pm by frank26080115 » Logged

I'm an electrical engineering student. I designed the USnooBie (V-USB dev kit) which is sold at Seeed Studio

Offline Offline
Newbie
*
Karma: 0
Posts: 2
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

I got the result after added "Serial.println(a)"and change "a++" into "a+=2".
It proves that the compiler is smart! smiley
Thanks for your time!
Logged

Global Moderator
UK
Online Online
Brattain Member
*****
Karma: 143
Posts: 19366
I don't think you connected the grounds, Dave.
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Qualify 'a' as "volatile".
Logged

Pete, it's a fool looks for logic in the chambers of the human heart.

Pages: [1]   Go Up
Print
 
Jump to: