gobot.io/x/gobot/v2@v2.1.0/examples/raspi_direct_pin_event.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/platforms/raspi" 15 "gobot.io/x/gobot/v2/system" 16 ) 17 18 const ( 19 inPinNum = "21" 20 outPinNum = "24" 21 outPinInvertedNum = "26" 22 debounceTime = 2 * time.Second 23 ) 24 25 var ( 26 outPin gobot.DigitalPinner 27 outPinInverted gobot.DigitalPinner 28 ) 29 30 // Wiring 31 // PWR Raspi: 1 (+3.3V, VCC), 2(+5V), 6, 9, 14, 20 (GND) 32 // GPIO Raspi: header pin 21 (GPIO9) is input, pin 24 (GPIO8) is normal output, pin 26 (GPIO7) is inverted output 33 // Button: the input pin is wired with a button to GND, the internal pull up resistor is used 34 // 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 35 // Expected behavior: always one LED is on, the other in opposite state, if button is pressed for >2 seconds the state changes 36 func main() { 37 38 board := raspi.NewAdaptor() 39 40 work := func() { 41 inPin, err := board.DigitalPin(inPinNum) 42 if err != nil { 43 fmt.Println(err) 44 } 45 if err := inPin.ApplyOptions(system.WithPinDirectionInput(), system.WithPinPullUp(), 46 system.WithPinDebounce(debounceTime), system.WithPinEventOnBothEdges(buttonEventHandler)); err != nil { 47 fmt.Println(err) 48 } 49 50 // note: WithPinOpenDrain() is optional, if using WithPinOpenSource() the LED's will not light up 51 outPin, err = board.DigitalPin(outPinNum) 52 if err != nil { 53 fmt.Println(err) 54 } 55 if err := outPin.ApplyOptions(system.WithPinDirectionOutput(1), system.WithPinOpenDrain()); err != nil { 56 fmt.Println(err) 57 } 58 59 outPinInverted, err = board.DigitalPin(outPinInvertedNum) 60 if err != nil { 61 fmt.Println(err) 62 } 63 if err := outPinInverted.ApplyOptions(system.WithPinActiveLow(), system.WithPinDirectionOutput(1), 64 system.WithPinOpenDrain()); err != nil { 65 fmt.Println(err) 66 } 67 68 fmt.Printf("\nPlease press and hold the button for at least %s\n", debounceTime) 69 } 70 71 robot := gobot.NewRobot("pinEdgeBot", 72 []gobot.Connection{board}, 73 []gobot.Device{}, 74 work, 75 ) 76 77 robot.Start() 78 } 79 80 func buttonEventHandler(offset int, t time.Duration, et string, sn uint32, lsn uint32) { 81 fmt.Printf("%s: %s detected on line %d with total sequence %d and line sequence %d\n", t, et, offset, sn, lsn) 82 level := 1 83 84 if et == "falling edge" { 85 level = 0 86 } 87 88 err := outPin.Write(level) 89 fmt.Printf("pin %s is now %d\n", outPinNum, level) 90 if err != nil { 91 fmt.Println(err) 92 } 93 94 err = outPinInverted.Write(level) 95 fmt.Printf("pin %s is now not %d\n", outPinInvertedNum, level) 96 if err != nil { 97 fmt.Println(err) 98 } 99 }