Some sort of state monitoring?
Oldbitcollector (Jeff)
Posts: 8,091
I've got a programming challenge that I haven't been able to get my head around..
I'm reading a switch that is either on all the time or off all the time, however I need to activate a command only once when the state of the switch changes.
Anyone have an elegant method for this?
Thanks
OBC
I'm reading a switch that is either on all the time or off all the time, however I need to activate a command only once when the state of the switch changes.
Anyone have an elegant method for this?
Thanks
OBC
Comments
Andy
In software, you can do the same sort of thing using a single memory bit to save the most recent state of the switch. Each time through the loop, you compare the bit to the state of the switch. If they're different, you execute your command. In all cases, you copy the state of the switch as it was when you tested it to the bit, wash, rinse, and repeat.
I have used the waitpeq/pne for syncing to the ADC sample clock to the csel in the ADC/DAC fun objects. The one unknown in this equation is by state change does Jeff anticipate always one way or the other with brief excursions to the opposite state, or once switched does it stay permanently there (mostly). If it is not a permanent transition, all three of the solutions presented here have a good probability of failure if the transition is narrow enough to be missed by a cog watching for this transition not being in a tight enough loop time-wise.
If it is a short transition then consider using the counter feature of the prop cog wherein the init routine looks at the state of the monitored pin and uses a movi to set the counter for pos or neg edge transition detection to capture the transient depending on the initial state recorded.
Otherwise, you are not looking for a transition, rather a level change. In that case, I would probably use the waitpeq/pne and again at init, see what the initial state is and set the peq/pne instruction looking for one or zero using the movi as done for the transition detect above.
Frank
if newstate <> oldstate
That's what I wasn't thinking of!
Thanks Ariba!
OBC
Aribas code can easily be added to a loop which is doing some real work.
If he is looking to create a safety ckt or a watch dog function, then he may want a dedicated cog. Hate to waste a cog unless you have to, but cheaper than external circuitry if you have a cog to spare.
Frank
OBC