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.
Serial.println(...)
in an ISR is not good practice. - cleblanc