1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Raspberrypi+GobotとタクトスイッチボタンでLチカ

Posted at

前回の記事に続き、GoBotをつかってLチカをやってみたので備忘録。前回の記事は下記掲載。

準備

  • Raspberrypi3 model b+

今回やったこと

ボタンを押したらLEDが点灯するという、Raspberrypi初心者にあるあるな例をGobotでやってみます。

配線図

raspberrypiとLEDとボタンの配線図です。

内容 接続先
タクトスイッチ上の足 1番ピン(3.3v)
タクトスイッチの下の足 抵抗を経由して14番ピン(GND)、12番ピン(Port18)
LEDのカソード(マイナス) 34番(GND)
LEDのアノード(プラス) 抵抗を経由して40番ピン(Port21)

layout_raspi_button.png

ソースコード

main.goを以下のように変更します。

参考:https://gobot.io/documentation/examples/raspi_button/

package main

import (
	"fmt"

	"gobot.io/x/gobot"
	"gobot.io/x/gobot/drivers/gpio"
	"gobot.io/x/gobot/platforms/raspi"
)

func main() {
	adaptor := raspi.NewAdaptor()
	button := gpio.NewButtonDriver(adaptor, "12")
	led := gpio.NewLedDriver(adaptor, "40")

	work := func() {
		button.On(gpio.ButtonPush, func(data interface{}) {
			fmt.Println("Button Pressed")
			led.On()
		})

		button.On(gpio.ButtonRelease, func(data interface{}) {
			fmt.Println("Button Released")
			led.Off()
		})
	}

	robot := gobot.NewRobot("ButtonBot",
		[]gobot.Connection{adaptor},
		[]gobot.Device{button, led},
		work,
	)

	robot.Start()
}

動作

それでは、Lチカさせてみましょう。

$ go run main.go
>>>2023/04/30 00:12:13 Initializing connections...
>>>2023/04/30 00:12:13 Initializing connection RaspberryPi-6ACB3C4D ...
>>>2023/04/30 00:12:13 Initializing devices...
>>>2023/04/30 00:12:13 Initializing device Button-70F89516 ...
>>>2023/04/30 00:12:13 Initializing device LED-2EA9178A ...
>>>2023/04/30 00:12:13 Robot ButtonBot initialized.
>>>2023/04/30 00:12:13 Starting Robot ButtonBot ...
>>>2023/04/30 00:12:13 Starting connections...
>>>2023/04/30 00:12:13 Starting connection RaspberryPi-6ACB3C4D...
>>>2023/04/30 00:12:13 Starting devices...
>>>2023/04/30 00:12:13 Starting device Button-70F89516 on pin 12...
>>>2023/04/30 00:12:13 Starting device LED-2EA9178A on pin 40...
>>>2023/04/30 00:12:13 Starting work...
>>>Button Pressed
>>>Button Released
>>>Button Pressed
>>>Button Released
>>>...

タクトスイッチを押すとLEDが点滅し、コンソールにはボタンを押すと、Button Pressedと表示され、ボタンを話すとButton Releasedが表示されます。

おわりに

引き続き、Gobotを使って楽しいラズパイライフを送ろうと思います。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?