I am trying to read PWM signal through Arduino Nano using attachInterrupt() function as shown below. What I intent to do is, whenever a pwm pulse is read, write "1" to serial. Else write "0" to serial.
// Following code will read the pwm signal coming to pin D2
void setup() {
Serial.begin(115200);
// when pin D2 goes high, call the rising function
attachInterrupt(0, rising, RISING);
}
void loop() {
Serial.write("0");
delay(250);
}
void rising() {
Serial.write("1");
}
The problem I am having is that, sometimes I get multiple ''1" in serial for single PWM signal. And this behavior is not even consistent. On an average 10-20% of the times I get multiple "1" for single PWM signal. Am I doing anything wrong here?
I have followed the same link to read pwm. The only difference is that I am not reading the falling signal edge. That is because I dont want to get the pwm value. Just need to know when a pwm signal was sent.
Can you please point out, what exactly is wrong in my implementation
As PaulS noted PWM is not a single pulse but a continuous stream of pulses that varies in duty cycle. So you could say that it is always being sent over and over and over again. Which is why you got the results that you did.
Maybe your looking for a change in the signal? For that you need to get the value and compare it to the previous value.