Reading width of pulses

Hi

my Arduino (as master) sends some different pulses likes this:

int output_pin = 13;


void setup()
{
  pinMode(output_pin, OUTPUT);
}

void loop(){
   digitalWrite(output_pin,HIGH) ; 
   delayMicroseconds(500);
   digitalWrite(output_pin,LOW);  
   delayMicroseconds(300);
   digitalWrite(output_pin,HIGH) ; 
   delayMicroseconds(600);
   digitalWrite(output_pin,LOW) ; 
   delayMicroseconds(400);
}

i have another arduino (as slave) that i want to read the width of that pulses

int input_pin = 13;
int pulse_width[4];

void setup()
{
  pinMode(input_pin, INPUT);
  Serial.begin(115200);
}

void loop(){
pulse_width[0]=pulseIn(input_pin, HIGH); //read the high width
pulse_width[1]=pulseIn(input_pin, LOW);  //read the low width

Serial.print(" H:");
Serial.println(pulse_width[0]);
Serial.print(" L:");
Serial.println(pulse_width[1]);


}

in serial monitor i get only these:

H:598
L:302
H:610
L:304
H:603
L:309
H:608
L:304
H:603
L:304
H:603
L:297
...
...

so it reads only the half pulses (High 600 and low 300) and not the rest (High 500 and low 400)

what is the reason of this problem?

hm....if it try it with some bigger values like 2000,4000,5000,3000 it got them all,

so the problem is in serial speed with the PC? does the varaibles take the correct data? or they loses it only when it send them to serial monitor?

The pulseIn command waits for a change in the signal, then it times how long the signal is in that state, returning when the signal changes to the desired state.

For instance, if a pin is currently HIGH, and you call pulseIn to measure how long the pin is HIGH, it has no idea when the pin went HIGH, so it waits for the pin to go LOW, then HIGH, then LOW, and tells you how long the pin was HIGH.

There is no way to measure consecutive HIGH/LOW sections of the same wave.

so how can i read the width?

You can read the width of the next HIGH pulse or the width of the next LOW pulse, but not the width of EVERY pulse.

it sounds very limited

then how it works when i am using bigest width?

is there any other solution? maybe something with millis?

use a pin interrupt like this:

#define INT_PIN 3  //input pulse pin

extern volatile unsigned long timer0_millis;
volatile unsigned long t, now, prev;

void setup() {
  Serial.begin(9600);
  
  //init interrupt
  pinMode(INT_PIN, INPUT);
  attachInterrupt(1, PulseInterrupt, FALLING);  //0 = digital pin 3
}

void PulseInterrupt(void) {
  now = timer0_millis;
  t = now - prev;
  prev = now;
}

void loop() {
  Serial.println(t);
  delay(1000);
}

You could set an interrupt to fire on CHANGE then record the micros() value and do your work based on that.


Rob