Skip to content

Possible bug in micros() when called inside ISR? (Due) #1301

Closed
@cmaglie

Description

@cmaglie

Forum topic:
http://arduino.cc/forum/index.php/topic,148161.msg1136944.html#msg1136944

I had used the function micros() inside an interrupt, and sometimes it seem not work fine in arduino due.
I would like to acquire the frequency (or time beetwen rising edge, i.e. Period) of an input signal on pin 28  (in Arduino due). The signal is a square wave 0/3.3V with PWM 50%.
For example I set the frequency to 2000Hz ( period of 500 micro second ) with a function generation.
this is the simple code:

volatile unsigned long time, Time1, Time2, Period =0;
volatile int i=0;
int Signal=28;

void setup() {
  Serial.begin(9600);
  pinMode(Signal,INPUT); 
  attachInterrupt(Signal,InterruptSegnaleGiriT,FALLING);  //Interrupt on Falling Edge
  }

void loop() {
  if(Period<490 || Period >510){
      Serial.println(Period);
      Serial.println(Time1);
      Serial.println(Time2);
      Serial.println("");
  }
void InterruptSegnaleGiriT(){
      time=micros();
          if(i==0){ 
            Time1=time;
            i=1;
            return;
          }
          if(i==1){
            Time2=time;
            Period=(Time2-Time1);
            i=0;
            return; 
      }
}

If the function micros work fine, this code does not print anything.
The problem is that sometimes the Period print is 1500 micro.
While sometimes Period print is a number near to the limit of an unsigned long,
maybe the Time1 is greater than Time2.

I Have try to put the code on arduino uno, the code work fine!!!
Maybe is a bug on Arduino due micros...

Metadata

Metadata

Assignees

No one assigned

    Labels

    Component: CoreRelated to the code for the standard Arduino APIType: Bug

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions