Skip to content

Instantly share code, notes, and snippets.

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 futureshocked/d604a9e2cc0a7d288625159f64cdf4f1 to your computer and use it in GitHub Desktop.
Save futureshocked/d604a9e2cc0a7d288625159f64cdf4f1 to your computer and use it in GitHub Desktop.
This program demonstrates how to configure counters, with debounce, using DIO channels.
--[[
LJ - 09.90 - counter_with_debouncing.lua
This program demonstrates how to configure counters, with debounce, using DIO
channels. The debounce time for each counter will be between debounceInt and
2*debounceInt milliseconds. The debounce time is determined by the duration
of the interval and when in the interval the first input is received.
Original script:
https://labjack.com/support/software/examples/lua-scripting/counter-examples/23-counters-debounce
Components
----------
- LabJack T4
- Momentary button
- Pin 1 to GND
- Pin 2 to FIO4
- Wires
- Breadboard
Course
------
Data acquisition and automation with LabJack
https://app.techexplorations.com/courses/labjack/
--]]
print("Create and read a counter with debounce.")
local debounceInt = 50 --50 ms debounce interval
local mbRead = MB.R --Local functions for faster processing
local mbWrite = MB.W
--1 = Rising edge, 0 = falling
local edge = 1
local bits = 0
local bits_new = 99
local count = 0
local debouncedCount = 0
--0 will mean that the counter has not recently been incremented
local recentIncr = 0
--The throttle setting can correspond roughly with the length of the Lua
--script. A rule of thumb for deciding a throttle setting is
--throttle = (3*NumLinesCode) + 20
local throttleSetting = 100 --Default throttle setting is 10 instructions
LJ.setLuaThrottle(throttleSetting)
ThrottleSetting = LJ.getLuaThrottle()
print ("Current Lua Throttle Setting: ", throttleSetting)
LJ.IntervalConfig(0, debounceInt) --set interval to debounceInt (ms)
local checkInterval=LJ.CheckInterval
while true do
bits_new = mbRead(2004, 0) -- Read FIO4
if bits ~= bits_new then
if edge == 1 then
if bits == 0 then
count = count + 1
end
else
if bits == 1 then
count = count + 1
end
end
bits = bits_new
end
--update debounced counter
if checkInterval(0) then --interval completed
if recentIncr == 0 then
if count > debouncedCount then
recentIncr = 1
debouncedCount = debouncedCount + 1
count = debouncedCount
if edge == 1 then
print ("Rising total: ", debouncedCount)
else
print ("Falling total: ", debouncedCount)
end
mbWrite(46000, 3, debouncedCount) --Save in User RAM
end
else
count = debouncedCount
recentIncr = 0
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment