Skip to content

Instantly share code, notes, and snippets.

@ElectricImpSampleCode
Last active October 21, 2020 11:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ElectricImpSampleCode/d0e284e61ba01b01b8a1222b56159679 to your computer and use it in GitHub Desktop.
Save ElectricImpSampleCode/d0e284e61ba01b01b8a1222b56159679 to your computer and use it in GitHub Desktop.
Example code demonstrating pulse counting and pulse interval timing via imp UART
/*
* Demonstrate pulse counting using an imp UART
*
* This code uses the falling edge of the input signal to trigger a UART receive.
* A framing error will be generated, but we ignore this - and the data -
* and just use the event information.
*
* Copyright 2020, Twilio.
*
*/
/*
* Use a PWM pin to send out pulses that are simulating
* the input you'd be receive in a real-world situation
* PPS = Pulses Per Second
*/
const SIMULATED_PPS = 100.0;
const COUNT_DURATION = 60;
/*
* Pins J and B are connected with a wire; J is the simulated pulse signal
* NOTE This code is for the imp006 - check the Pin Mux in the Dev Center
* to port this code to other imps
*/
uart <- hardware.uartABCD;
pwm <- hardware.pinJ;
pulseCount <- 0;
isCounting <- false;
countDown <- 5;
intervalTotal <- 0;
/*
* Callback triggered on each UART receive
*/
function counter() {
// Read the byte: result is an integer in the form:
// Bits 31-8 : microsecond interval since last byte
// Bits 7-0 : the data bytes itself, which we ignore
local interval = uart.read() >> 8;
if (isCounting) {
intervalTotal += interval;
pulseCount++;
}
}
/*
* Callback triggered to display countdown in the log
*/
function countdown() {
server.log(countDown + "...");
countDown--;
if (countDown > 0) imp.wakeup(1.0, countdown);
}
/*
* Configure the UART for receive only
*/
uart.configure(115200,
8,
PARITY_NONE,
1,
NO_TX | NO_CTSRTS | TIMING_ENABLED,
counter);
/*
* Set up PWM to simulate a certain number of pulses per second
*/
pwm.configure(PWM_OUT,
1.0 / SIMULATED_PPS,
0.9);
/*
* Wait five seconds and then begin counting
*/
imp.wakeup(5.0, function() {
server.log("Counting for " + COUNT_DURATION + " seconds");
// Prep countdown warning to user
imp.wakeup(COUNT_DURATION - 5, countdown);
// Set flag to start counting
isCounting = true;
// Wake up to end counting
imp.wakeup(COUNT_DURATION, function() {
isCounting = false;
server.log(pulseCount + " pulses counted in " + COUNT_DURATION + " seconds");
if (pulseCount > 0) server.log(format("Average pulse interval: %i microseconds", intervalTotal / pulseCount));
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment