gobot.io/x/gobot/v2@v2.1.0/examples/tinkerboard_mfcrc522spi.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/spi"
    15  	"gobot.io/x/gobot/v2/platforms/tinkerboard"
    16  )
    17  
    18  // Wiring
    19  // PWR  Tinkerboard: 1 (+3.3V, VCC), 2(+5V), 6, 9, 14, 20 (GND)
    20  // SPI0 Tinkerboard (not working with armbian): 11 (CLK), 13 (TXD), 15 (RXD), 29 (CSN0), 31 (CSN1, n.c.)
    21  // SPI2 Tinkerboard: 23 (CLK), 19 (TXD), 21 (RXD), 24 (CSN0), 26 (CSN1, n.c.)
    22  // MFRC522 plate: VCC, GND, SCK (CLK), MOSI (->TXD), MISO (->RXD), NSS/SDA (CSN0/CSN1?)
    23  func main() {
    24  	a := tinkerboard.NewAdaptor()
    25  	d := spi.NewMFRC522Driver(a, spi.WithBusNumber(2))
    26  
    27  	wasCardDetected := false
    28  	const textToCard = "Hello RFID user!\nThis text was written to card."
    29  
    30  	work := func() {
    31  		if err := d.PrintReaderVersion(); err != nil {
    32  			fmt.Println("get version err:", err)
    33  		}
    34  
    35  		gobot.Every(2*time.Second, func() {
    36  			if !wasCardDetected {
    37  				fmt.Println("\n+++ poll for card +++")
    38  				if err := d.IsCardPresent(); err != nil {
    39  					fmt.Println("no card found")
    40  				} else {
    41  					fmt.Println("\n+++ write card +++")
    42  					err := d.WriteText(textToCard)
    43  					if err != nil {
    44  						fmt.Println("write err:", err)
    45  					}
    46  					wasCardDetected = true
    47  				}
    48  			} else {
    49  				fmt.Println("\n+++ read card +++")
    50  				text, err := d.ReadText()
    51  				if err != nil {
    52  					fmt.Println("read err:", err)
    53  					wasCardDetected = false
    54  				} else {
    55  					fmt.Printf("-- start text --\n%s\n-- end  text --\n", text)
    56  				}
    57  			}
    58  		})
    59  	}
    60  
    61  	robot := gobot.NewRobot("spiBot",
    62  		[]gobot.Connection{a},
    63  		[]gobot.Device{d},
    64  		work,
    65  	)
    66  
    67  	robot.Start()
    68  }