I wrote some haskell code to toggle a pin on the raspberry pi depending on an interrupt I get from another pin on the raspberry pi. I simply do not know how to toggle the state of the pin without knowing the previous toggle state. The program itself is very simple.
import Control.Concurrent
import Data.IORef
import HasberryPi
main = do wiringPiSetup
pinMode 0 output
pinMode 7 input
pullUpDnControl 7 pull_down
wiringPiISR 7 edge_both onoff
threadDelay (15*(10^6))
onoff s = do a <- readIORef s -- This is wrong
digitalWrite 0 (if b then pinhigh else pinlow) -- This is wrong
So basically what happens here is pin 7 is registered as an interrupt. The interrupt is triggered whenever pin 7 goes from high to low or low to high. And whenever the interrupt is triggered it calls the onoff
function that toggles the state of pin 0.
The main
function is correct. Its the onoff
function that is the problem. The wanted behavior of the onoff
function is to make pin 0 high when the pin it is low and toggle the pin low when it is high. But to do that I need to store the previous state of the pin in the previous call to onoff
.
I tried the state monad. But the problem is that the state monad passes state around based on an initial state value. But in subsequent calls to onoff
it seems impossible to change the initial state value. I thought about IORef and it seems no different. It just seems like it's doing what state is doing.. but only inside the IO.
I can clearly see that I am sorely missing the ability of storing state in a Global variable. And I'm happy that I'm not able to do it because I know there is some other idiomatic way of achieving the same goal.
Any help in the right direction is very much appreciated.
Cheers and Regards.