Skip to content

Instantly share code, notes, and snippets.

@cat-haines
Last active December 16, 2015 20:19
Show Gist options
  • Save cat-haines/5492082 to your computer and use it in GitHub Desktop.
Save cat-haines/5492082 to your computer and use it in GitHub Desktop.
A simple Squirrel class for handeling pulses as a type of digital input and a simple example using it. NOTE: Accuracy has NOT been tested.
/*******************************************************************************
* Reads a pulse (either HIGH or LOW) on a pin. If the pulseValue is HIGH,
* the object will start timing when the pin goes HIGH, then waits for the pin
* to go LOW, and executes the callback (callback expects a function with one
* parameter, the length of the pulse in microseconds).
*
* The accuracy of this function has not been tested, and will have some
* variance because of how callbacks work.
******************************************************************************/
class Pulse {
pulsePin = null; // Pin to look for pulses on
pulseValue = null; // 1 for HIGH -> LOW, 0 for LOW -> HIGH
timer = null; // Time since start of pulse
callback = null; // callback function when pulse finished
constructor(_pulsePin, _inputType, _pulseValue, _callback) {
this.pulsePin = _pulsePin;
this.pulseValue = _pulseValue;
this.timer = 0.0;
this.callback = _callback;
this.pulsePin.configure(_inputType, pinChanged.bindenv(this));
}
function pinChanged() {
local p = pulsePin.read();
if (p == pulseValue) {
this.timer = hardware.micros();
}
else {
this.timer = hardware.micros() - timer;
this.callback(timer);
}
}
}
function pulsed(microseconds)
{
server.log("pulsed for " + microseconds + " microseconds");
}
pulsePin1 <- Pulse(hardware.pin1, DIGITAL_IN_PULLDOWN, 1, pulsed);
server.log("ready");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment