# Need help with using pulseInLong to time a sensor

I have a setup consisting of a magnet suspended above a sensor coil. It acts as a pendulum and creates a ~ 4 mV signal when it swings over the coil - this goes through two stages of an LM358 to generate a 5V signal. The signal is very messy with lots of 'ringing' This signal is fed into pin A0 of an Arduino Uno. I used MegunoLink.h and Filter.h which is an exponential filter library then applied constrain and map, finally converting to a clean 0 - 400 (units?) square wave of about 1 second with a varying duty cycle. This is the information I want as it tells me that the magnet is homing in on the sensor (the duty cycle increases as it gets close). But when I apply pulseInLong I only get a string of zeros on the serial monitor. What am I doing wrong? Here is the sketch:

``````//  Coding by Jeremy 130520
//  further development for ricochet module

#include "Filter.h"
// Create a new exponential filter with a weight of 5 and an initial value of 0.

int coilPin = 8;
unsigned long pulseLength;
unsigned long signal_1;

void setup()
{
pinMode(coilPin, OUTPUT);
Serial.begin(9600);
}

void loop()
{
signal_1 = constrain(signal_1,80, 200);
signal_1 = map(signal_1, 80, 200,0,400);
if (signal_1 >= 200) {signal_1 = 400; digitalWrite(coilPin, HIGH);}
if (signal_1 < 200) {signal_1 = 0; digitalWrite(coilPin, LOW);}

Serial.println(signal_1); //using the plotter

//pulseLength = pulseInLong(coilPin, HIGH);
//Serial.println(pulseLength);
delay(10);
}
``````

You cannot use `pulseInLong()` because it is a blocking function. It waits until the input rises, then waits until it falls again, and only then it returns a value. While it's waiting, the rest of the program cannot run. This means you will not be able to actually generate the signal you are trying to time.

The easiest solution is to time things yourself with `micros()`. You have to implement an edge detector, i.e. some logic that remembers the previous state of the signal and notices when it changes:

``````static bool is_high;  // is the input currently HIGH?
static uint32_t time_of_rise;  // when did it rise?

if (!is_high && signal_1 >= 200) {  // rising edge
time_of_rise = micros();
is_high = true;
} else if (is_high && signal_1 < 200) {  // falling edge
uint32_t pulse_width = micros() - time_of_rise;
is_high = false;
Serial.println(pulse_width);
}
``````
• Thanks Edgar that looks good - I shall try it tomorrow and get back to you May 14, 2020 at 13:07
• That worked very well. Clearly showing when the magnet gets close to the sensor coil allowing me to take some other action at that point. May 15, 2020 at 9:58