gobot.io/x/gobot/v2@v2.1.0/examples/raspi_direct_pin.go (about)

     1  //go:build example
     2  // +build example
     3  
     4  //
     5  // Do not build by default.
     6  
     7  package main
     8  
     9  import (
    10  	"fmt"
    11  	"time"
    12  
    13  	"gobot.io/x/gobot/v2"
    14  	"gobot.io/x/gobot/v2/drivers/gpio"
    15  	"gobot.io/x/gobot/v2/platforms/adaptors"
    16  	"gobot.io/x/gobot/v2/platforms/raspi"
    17  )
    18  
    19  // Wiring
    20  // PWR  Raspi: 1 (+3.3V, VCC), 2(+5V), 6, 9, 14, 20 (GND)
    21  // GPIO Raspi: header pin 21 (GPIO9) is input, pin 24 (GPIO8) is normal output, pin 26 (GPIO7) is inverted output
    22  // Button: the input pin is wired with a button to GND, the internal pull up resistor is used
    23  // LED's: the output pins are wired to the cathode of a LED, the anode is wired with a resistor (70-130Ohm for 20mA) to VCC
    24  // Expected behavior: always one LED is on, the other in opposite state, if button is pressed for >2 seconds the state changes
    25  func main() {
    26  	const (
    27  		inPinNum          = "21"
    28  		outPinNum         = "24"
    29  		outPinInvertedNum = "26"
    30  	)
    31  	// note: WithGpiosOpenDrain() is optional, if using WithGpiosOpenSource() the LED's will not light up
    32  	board := raspi.NewAdaptor(adaptors.WithGpiosActiveLow(outPinInvertedNum),
    33  		adaptors.WithGpiosOpenDrain(outPinNum, outPinInvertedNum),
    34  		adaptors.WithGpiosPullUp(inPinNum),
    35  		adaptors.WithGpioDebounce(inPinNum, 2*time.Second))
    36  
    37  	inPin := gpio.NewDirectPinDriver(board, inPinNum)
    38  	outPin := gpio.NewDirectPinDriver(board, outPinNum)
    39  	outPinInverted := gpio.NewDirectPinDriver(board, outPinInvertedNum)
    40  
    41  	work := func() {
    42  		level := byte(1)
    43  
    44  		gobot.Every(500*time.Millisecond, func() {
    45  			read, err := inPin.DigitalRead()
    46  			fmt.Printf("pin %s state is %d\n", inPinNum, read)
    47  			if err != nil {
    48  				fmt.Println(err)
    49  			} else {
    50  				level = byte(read)
    51  			}
    52  
    53  			err = outPin.DigitalWrite(level)
    54  			fmt.Printf("pin %s is now %d\n", outPinNum, level)
    55  			if err != nil {
    56  				fmt.Println(err)
    57  			}
    58  
    59  			err = outPinInverted.DigitalWrite(level)
    60  			fmt.Printf("pin %s is now not %d\n", outPinInvertedNum, level)
    61  			if err != nil {
    62  				fmt.Println(err)
    63  			}
    64  
    65  			if level == 1 {
    66  				level = 0
    67  			} else {
    68  				level = 1
    69  			}
    70  		})
    71  	}
    72  
    73  	robot := gobot.NewRobot("pinBot",
    74  		[]gobot.Connection{board},
    75  		[]gobot.Device{inPin, outPin, outPinInverted},
    76  		work,
    77  	)
    78  
    79  	robot.Start()
    80  }