Since handling these indices by hand for every call seems really unsafe to me, I’d suggest giving the approaches in the topic rdeits linked a try! Like a functor for each pin you want:
julia> struct Edgedetector
pinnumber::Int
state::Ref{Bool}
Edgedetector(pin, initialstate = false) = new(pin, Ref(initialstate))
end
julia> function (e::Edgedetector)()
newstate = getgpio(e.pinnumber)
if newstate
if !e.state[] println("Pin $(e.pinnumber): Button pressed!") end
else
if e.state[] println("Pin $(e.pinnumber): Button released!") end
end
e.state[] = newstate
return newstate
end
julia> getgpio(_) = rand(Bool); # mocked up
julia> p1 = Edgedetector(1)
Edgedetector(1, Base.RefValue{Bool}(false))
julia> p1()
false
julia> p1()
Pin 1: Button pressed!
true
julia> p1()
Pin 1: Button released!
false
julia> p1()
Pin 1: Button pressed!
true
Or if you don’t feel like carrying around an object per pin:
julia> let pinstates = Dict{Int,Bool}()
global detectedge
function detectedge(pinnumber::Int)
newstate = getgpio(pinnumber)
if haskey(pinstates, pinnumber)
if newstate
if !pinstates[pinnumber] println("Pin $(pinnumber): Button pressed!") end
else
if pinstates[pinnumber] println("Pin $(pinnumber): Button released!") end
end
end
pinstates[pinnumber] = newstate
return newstate
end
end
detectedge (generic function with 1 method)
julia> getgpio(_) = rand(Bool)
julia> detectedge(1)
true
julia> detectedge(1)
Pin 1: Button released!
false
julia> detectedge(1)
false
julia> detectedge(1)
false
julia> detectedge(1)
Pin 1: Button pressed!
true
julia> detectedge(2)
false
julia> detectedge(2)
Pin 2: Button pressed!
true