tinygo.org/x/drivers@v0.27.1-0.20240509133757-7dbca2a54349/examples/bma42x/main.go (about)

     1  package main
     2  
     3  // Smoke test for the BMA421/BMA425 sensors.
     4  // Warning: this code has _not been tested_. It's only here as a smoke test.
     5  
     6  import (
     7  	"fmt"
     8  	"machine"
     9  	"time"
    10  
    11  	"tinygo.org/x/drivers"
    12  	"tinygo.org/x/drivers/bma42x"
    13  )
    14  
    15  func main() {
    16  	time.Sleep(5 * time.Second)
    17  
    18  	i2cBus := machine.I2C1
    19  	i2cBus.Configure(machine.I2CConfig{
    20  		Frequency: 400 * machine.KHz,
    21  		SDA:       machine.SDA_PIN,
    22  		SCL:       machine.SCL_PIN,
    23  	})
    24  
    25  	sensor := bma42x.NewI2C(i2cBus, bma42x.Address)
    26  	err := sensor.Configure(bma42x.Config{
    27  		Device:   bma42x.DeviceBMA421 | bma42x.DeviceBMA425,
    28  		Features: bma42x.FeatureStepCounting,
    29  	})
    30  	if err != nil {
    31  		println("could not configure BMA421/BMA425:", err)
    32  		return
    33  	}
    34  
    35  	if !sensor.Connected() {
    36  		println("BMA42x not connected")
    37  		return
    38  	}
    39  
    40  	for {
    41  		time.Sleep(time.Second)
    42  
    43  		err := sensor.Update(drivers.Acceleration | drivers.Temperature)
    44  		if err != nil {
    45  			println("Error reading sensor", err)
    46  			continue
    47  		}
    48  
    49  		fmt.Printf("Temperature: %.2f °C\n", float32(sensor.Temperature())/1000)
    50  
    51  		accelX, accelY, accelZ := sensor.Acceleration()
    52  		fmt.Printf("Acceleration: %.2fg %.2fg %.2fg\n", float32(accelX)/1e6, float32(accelY)/1e6, float32(accelZ)/1e6)
    53  	}
    54  }