module System.Hardware.Arduino.SamplePrograms.NumGuess where
import System.Hardware.Arduino
import System.Hardware.Arduino.Parts.LCD
osepp :: LCDController
osepp = Hitachi44780 { lcdRS = digital 8
, lcdEN = digital 9
, lcdD4 = digital 4
, lcdD5 = digital 5
, lcdD6 = digital 6
, lcdD7 = digital 7
, lcdRows = 2
, lcdCols = 16
, dotMode5x10 = False
}
data Key = KeyRight
| KeyLeft
| KeyUp
| KeyDown
| KeySelect
initOSepp :: Arduino (LCD, Bool -> Arduino (), Arduino (Maybe Key))
initOSepp = do lcd <- lcdRegister osepp
let button = analog 0
light = digital 10
setPinMode button ANALOG
setPinMode light OUTPUT
let threshHolds = [ (KeyRight, 30)
, (KeyUp, 150)
, (KeyDown, 360)
, (KeyLeft, 535)
, (KeySelect, 760)
]
backLight = digitalWrite light
readButton = do val <- analogRead button
let walk [] = Nothing
walk ((k, t):keys)
| val < t = Just k
| True = walk keys
return $ walk threshHolds
return (lcd, backLight, readButton)
numGuess :: LCD -> (Bool -> Arduino ()) -> Arduino (Maybe Key) -> Arduino ()
numGuess lcd light readKey = game
where home = lcdHome lcd
write = lcdWrite lcd
clear = lcdClear lcd
go = lcdSetCursor lcd
at (r, c) s = go (c, r) >> write s
getKey = do mbK <- readKey
case mbK of
Nothing -> getKey
Just k -> do delay 500
return k
game = do clear
home
light True
at (0, 4) "HArduino!"
at (1, 0) "# Guessing game"
delay 2000
guess 1 0 1000
newGame = getKey >> game
guess :: Int -> Int -> Int -> Arduino ()
guess rnd l h
| h == l = do clear
at (0, 0) $ "It must be: " ++ show h
at (1, 0) $ "Guess no: " ++ show rnd
newGame
| h < l = do clear
at (0, 0) "You lied!"
newGame
| True = do clear
let g = (l+h) `div` 2
at (0, 0) $ "(" ++ show rnd ++ ") Is it " ++ show g ++ "?"
k <- getKey
case k of
KeyUp -> guess (rnd+1) (g+1) h
KeyDown -> guess (rnd+1) l (g1)
KeySelect -> do at (1, 0) $ "Got it in " ++ show rnd ++ "!"
newGame
_ -> do at (1, 0) "Use up/down/select only.."
delay 1000
guess rnd l h
guessGame :: IO ()
guessGame = withArduino False "/dev/cu.usbmodemfd131" $ do
(lcd, light, readButton) <- initOSepp
numGuess lcd light readButton