0
votes

Can someone explain the flow of this Arduino program shown below?

volatile int pwm_value = 0;
volatile int prev_time = 0;

void setup() {
  Serial.begin(115200);
  // when pin D2 goes high, call the rising function
  attachInterrupt(0, rising, RISING);
}

void loop() { }

void rising() {
  attachInterrupt(0, falling, FALLING);
  prev_time = micros();
}

void falling() {
  attachInterrupt(0, rising, RISING);
  pwm_value = micros()-prev_time;
  Serial.println(pwm_value);

I understand that PWM means looking for the length of time the signal remains high for each cycle.

In void setup(), the first rising edge of the signal will trigger the void rising(). So during void rising() the signal is at HIGH and prev_time = micros() is measuring the time of the signal at high (pulse width) right?

Then once the falling edge of the signal comes in, the attachInterrupt() function in void rising() will trigger void falling(). At this point the signal is at LOW, so micros() in void falling() is measuring the time of the signal at low? Then that will make no sense to take pwm_value = micros()-prev_time.

This will only make sense if prev_time is the measurement of the signal at LOW and micros() is the measurement of the period of the signal. Then pwm_value = micros()-prev_time is correct.

Based on my explanation, please explain to me what I am not getting.

1
Serial.println(...) in an ISR is not good practice. - cleblanc
This call would measure the size of the pulse, which is exactly the time spent between signal started being high to signal started being low. Not sure what you are confused about. - SergeyA

1 Answers

1
votes

This code will wait for a rising edge. Once the signal goes high it will store the current time in prev_time and start waiting for the signal to drop low. Once a falling edge is detected it will print the difference between prev_time and the current time which is your on-time in microseconds.

pwm_value is a misleading name. This is just a time measurement which is not related to PWM per se. PWM values are usually duty cycles. The on-time alone does not give you any information in terms of PWM. You further need the off-time or the total time to know the duty cycle.

As cleblanc mentioned in his comment using serial prints in an ISR is not very good.