Mimicking a Capture Timer Feature

Hi Imp Team, I’ve recently begun working with the Imp product and am excited by the progress you’ve made.

One feature that I have often used in microcontroller based projects is measuring pulse widths to an high resolution. The example shown for hardware.micros() shows how you can take a reading from the clock at the beginning of the callback function for a pin configured as an input. As the documentation warns, this callback is queued, so precise and reliable measurement is doubtful when program control might not reach the callback function until milliseconds(??) after the pin has changed state.

As a means of improving this, why not consider a callback that passes the hardware.micros() value as parameter to the callback function? That microsecond value could be trapped and stored at an interrupt level and the callback function can either use it or ignore it. That would eliminate some of the concern about the queueing of the callback. This seems particularly relevant now that new real-time functionality is available at the pin level for pulse counting and pulse generation.

The example for hardware.micros() would instead look like this:

`imp.configure(“Pulse”, [], []);

pulseStart <- 0;
hardware.pin1.configure(DIGITAL_IN, function (microsecs) {
// callback function passes clock microsecond value, captured at moment pin1 changes state
if (hardware.pin1.read()) {
pulseStart = microsecs;
} else {
server.log(“Pulse on pin1 lasted " + (microsecs - pulseStart) + " microseconds”);
}
});`

1 Like

I 2nd this. it could potentially be helpful but of course there is still the issue of speed. I think it would be ok if the number returned is simply clock ticks and not necessarily an exact multiple of microseconds.

I have seen this called ICP, input capture unit and have used it to read an optical encoder spinning on a shaft. Normal interrupts do not work because even the fastest can be delayed by some variable number of clock cycles and this messes with the timing.

The way I would use it is to get a time (clock ticks) stamped callback of each downward transition on a pin.

however, if there is not enough time in between the events to do all the other things squirrel needs to do then it is all for naught.