gobot.io/x/gobot/v2@v2.1.0/examples/digispark_driver.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  	"strconv"
    12  	"time"
    13  
    14  	"gobot.io/x/gobot/v2"
    15  	"gobot.io/x/gobot/v2/drivers/i2c"
    16  	"gobot.io/x/gobot/v2/platforms/digispark"
    17  )
    18  
    19  // This is an example for using the generic I2C driver to write and read values
    20  // to an i2c device. It is suitable for simple devices, e.g. EEPROM.
    21  // The example was tested with the EEPROM part of PCA9501.
    22  //
    23  // Procedure:
    24  // * write value to register (EEPROM address)
    25  // * read value back from register (EEPROM address) and check for differences
    26  func main() {
    27  	const (
    28  		defaultAddress = 0x7F
    29  		myAddress      = 0x44 // needs to be adjusted for your configuration
    30  	)
    31  	board := digispark.NewAdaptor()
    32  	drv := i2c.NewDriver(board, "PCA9501-EEPROM", defaultAddress, i2c.WithAddress(myAddress))
    33  	var eepromAddr uint8 = 0x00
    34  	var register string
    35  	var valWr uint8 = 0xFF
    36  	var valRd int
    37  	var err error
    38  
    39  	work := func() {
    40  		gobot.Every(50*time.Millisecond, func() {
    41  			// write a value 0-255 to EEPROM address 255-0
    42  			eepromAddr--
    43  			valWr++
    44  			register = strconv.Itoa(int(eepromAddr))
    45  			err = drv.Write(register, int(valWr))
    46  			if err != nil {
    47  				fmt.Println("err write:", err)
    48  			}
    49  
    50  			// write process needs some time, so wait at least 5ms before read a value
    51  			// when decreasing to much, the check below will fail
    52  			time.Sleep(5 * time.Millisecond)
    53  
    54  			// read value back and check for unexpected differences
    55  			valRd, err = drv.Read(register)
    56  			if err != nil {
    57  				fmt.Println("err read:", err)
    58  			}
    59  			if int(valWr) != valRd {
    60  				fmt.Printf("addr: %d wr: %d differ rd: %d\n", eepromAddr, valWr, valRd)
    61  			}
    62  
    63  			if eepromAddr%10 == 0 {
    64  				fmt.Printf("addr: %d, wr: %d rd: %d\n", eepromAddr, valWr, valRd)
    65  			}
    66  		})
    67  	}
    68  
    69  	robot := gobot.NewRobot("simpleDriverI2c",
    70  		[]gobot.Connection{board},
    71  		[]gobot.Device{drv},
    72  		work,
    73  	)
    74  
    75  	err = robot.Start()
    76  	if err != nil {
    77  		fmt.Println(err)
    78  	}
    79  }