packages feed

fuyu-gpio-0.1.0.0: examples/01-blink.hs

-- In this example we will learn the basic usage of libgpiod line configuration for output.
-- We check and initialize a GPIO chip, set a line direction to output mode, and blink an LED 10 times
-- using nested resource allocation brackets ('withChip', 'withSettings', 'withConfig', 'withRequest').
module Main where

-- High-level resource brackets & utility functions.
-- This import libgpiod Core API functions for chip and line (definitions, settings, configuration, request).
-- Also this module contains the miscellaneous functions for libgpiod ('isGPIOChip' & 'gpiodAPIVersion')
import Fuyu.GPIO

-- Base & third-party libraries.
-- Usually we are going to use these modules and their functions.
import Control.Concurrent (threadDelay)
import Control.Monad (replicateM_)

-- We could check if this file is a GPIO Chip with 'isGPIOChip' function.
myChipPath :: FilePath
myChipPath = "/dev/gpiochip0" 

-- In Orange Pi devices we could find this information with 'gpio readall' command (or in docs)
-- In this case the line offset 269 corresponds to physical pin 7 
ledOffset :: Offset 
ledOffset = Offset 269 


main :: IO ()
main = do
   isChip <- isGPIOChip myChipPath
   if isChip
     then do 
       putStrLn "Example started: LED blinking"
       runApp
     else putStrLn $ myChipPath ++ " does not correspond to a valid GPIO Chip"

runApp :: IO ()
runApp = do
   withChip myChipPath $ \chip -> do
      withSettings $ \settings -> do
         setDirection settings DirOutput
         withConfig $ \config -> do
            addSettings config [ledOffset] settings
            -- The use of Nothing instead of a 'RequestConfig' means that we are using a NULL request configuration object.
            -- (Do not confuse Fuyu.GPIO.RequestConfig with Fuyu.GPIO.Line.Config, the first one is used for kernel options
            -- and the second one is used for line config).  
            withRequest chip Nothing config $ \request -> do
               replicateM_ 10 $ do 
                 setLineValue request ledOffset Active
                 threadDelay 500000 -- 0.5 seconds pause   
                 setLineValue request ledOffset Inactive
                 threadDelay 500000 -- 0.5 seconds pause