I am trying to read an input signal from a source that is a PWM signal. In my research I have found some useful articles out found here: http://www.instructables.com/id/Arduino-Frequency-Detection/?ALLSTEPS and here: http://www.camelsoftware.com/2015/12/25/reading-pwm-signals-from-an-rc-receiver-with-arduino/. The first article is a little beyond my experience level, and would not be helpful if I used anything other then a uno, although it seems to perform extremely well. The second shows a method I was better able to understand.
I have been using the following code somewhat successfully:
#define input_pin 2
volatile unsigned long timer_start;
volatile int pulse_time;
volatile int last_interrupt_time;
void calcSignal()
{
last_interrupt_time = micros();
if(digitalRead(input_pin) == HIGH)
{
timer_start = micros();
}
else {
if(timer_start != 0)
{
//record the pulse time
pulse_time = ((volatile int)micros() - timer_start);
//restart the timer
timer_start = 0;
}
}
}
void setup()
{
timer_start = 0;
attachInterrupt(0, calcSignal, CHANGE);
Serial.begin(115200);
}
void loop()
{
Serial.println(pulse_time);
delay(20);
}
The problem with this setup for my application is the interrupt is only triggered by a change in state, when realistically I need to know the duration of how long it is high and how long it is low. A picture of the ideal signals can be seen here with various duty cycles (https://www.arduino.cc/en/Tutorial/SecretsOfArduinoPWM). I tried changing the interrupt mode from CHANGE to LOW and HIGH, but did not get any creditable results, as it only output zeros on the serial monitor. Is there something I am missing or an alternative library/method that can be used? I am somewhat new to programming, so I have some understanding, but am by no means a programmer.