measure pulse width using : pin change interrupt & millis()

Hello, i am trying to measure multiple PWM from a receiver. After a bit of searching i find that i can use the pin change interrupt so as to find the begin and end of my pulse and measure the time duration using micros().

So i made a test code using a button and millis() so as to measure a slower pulse and see if this
method could work.

volatile unsigned long t_b;
volatile unsigned long result;

void int_Setup(){

  PCICR = PCICR | (1<<PCIE0); //enable interrupt 0 -> for port b
  PCMSK0 = PCMSK0 | (1<<PCINT1);  //unmask interrupt pin 9
}


ISR(PCINT0_vect){
  if(digitalRead(9)){
    result = millis()-t_b;
  }else{
    t_b = millis();
  }
}




void setup() {
  // put your setup code here, to run once:
  cli();
  Serial.begin(9600);  
  pinMode(9,INPUT); //9 as input
  digitalWrite(9,HIGH); //enable pull-ups
  int_Setup();
  sei();
}

void loop() {
  // put your main code here, to run repeatedly:
    Serial.println(result);    
    delay(100);
}

The code works fine most of the time but randomly fails!
it gives pulses of 1-5 millisecond duration which is impossible to achieve with a pushbutton.

I am probably missing something.
Below i have a printscreen photo of my serial monitor the time it fails

if you have any suggestions pls let me know

thanks

euri:
The code works fine most of the time but randomly fails!
it gives pulses of 1-5 millisecond duration which is impossible to achieve with a pushbutton.

You're probably measuring the switch bouncing - the noisy fraction of a second that happens when a switch makes or breaks contact.

thanks for fast reply.

So if i understand right the code is ok but the method to test it with a switch gives
random spikes which i measure while making or breaking contact.

I think so, yeah. The sketch could probably be improved but I the overall logic is OK as far as I can see.

If you needed more accuracy you should think about:

  1. using micros() instead of millis()
  2. Reading the pin registers directly

It depends on the frequency of the PWM signal you're interested in really.