The pulseIn() Function gives me very inaccurate results, and when I try to use <PinChangeInt.h> library, it shows error:
No such file or directory #include <new.h>
I posted in installation and troubleshooting because of
"No such file or directory #include <new.h>" error.
good to know that there might be a problem with using pin change interrupt library on DUE
I connected my DUE to ESP32, which provides PWM 50% duty cycle at 5000Hz, so pulsein() should show 100, but it reads different values from 100 to 149 and I can't have such a big error.
@aixam If your pulsewidths aren't any shorter than a microsecond then here's a way to measure pulsewidth:
// Sketch to calculate pulsewidth from an input signal in microseconds
#define INPUT_PIN 10 // Arduino input pin number
volatile unsigned long isrPulsewidth; // Define Interrupt Service Routine (ISR) pulsewidth
unsigned long pulseWidth; // Define Pulsewidth variable
void setup()
{
pinMode(INPUT_PIN, INPUT); // Set the input pin
attachInterrupt(digitalPinToInterrupt(INPUT_PIN), calcPulsewidth, CHANGE); // Run the calcPulsewidth function on signal CHANGE
}
void loop()
{
noInterrupts(); // Turn off interrupts
pulseWidth = isrPulsewidth; // Copy the isr pulsewidth to the pulsewidth variable
interrupts(); // Turn on interrupts
// Work with pulsewidth here ...
// ...
}
void calcPulsewidth() // Interrupt Service Routine (ISR)
{
static unsigned long pulseStartTime; // Start time variable
if (digitalRead(INPUT_PIN) == HIGH) // If the change was a RISING edge
{
pulseStartTime = micros(); // Store the start time (in microseconds)
}
else // If the change was a FALLING edge
{
isrPulsewidth = micros() - pulseStartTime; // Calculate the pulsewidth
}
}
The period (frequency) could be measured by storing the time between pulses in a similar fashion.
I have not used ESP32, but my experience with ESP8266 shows that it generates PWM software, not hardware. When checking the signal with an oscilloscope, large deviations are observed.