本文主要是介绍Golang实现控制树莓派 - 按键如何点灯,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
引脚
LED : 负极 -> GND
正极 -> GPIO17
Button: GPIO27\GND
实现
package mainimport ("fmt""github.com/stianeikeland/go-rpio/v4""os""time"
)var (buttonPin = rpio.Pin(27)ledPin = rpio.Pin(17)gpioChangedChan = make(chan rpio.State)
)func ledInit() {ledPin.Output()ledPin.Low()
}func buttonInit() {buttonPin.PullUp() // 设置为上拉buttonPin.Input() // 设置为输入
}func gpioInit() {ledInit()buttonInit()
}func main() {// Open and map memory to access gpio, check for errorsif err := rpio.Open(); err != nil {fmt.Println(err)os.Exit(1)}// Unmap gpio memory when donedefer rpio.Close()gpioInit()go func() {var (status = rpio.Hightemp = rpio.High)/* 100ms扫描一次引脚 */for {temp = buttonPin.Read()if temp != status {status = tempgpioChangedChan <- status}time.Sleep(time.Millisecond * 100)}}()for {select {case currGPIOStatus := <-gpioChangedChan:if currGPIOStatus == rpio.Low {fmt.Println("Key Pressed!")ledPin.High()} else {fmt.Println("Key Released!")ledPin.Low()}}}}
这篇关于Golang实现控制树莓派 - 按键如何点灯的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!