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

     1  package main
     2  
     3  import (
     4  	"machine"
     5  	"machine/usb/hid/mouse"
     6  	"math"
     7  	"time"
     8  
     9  	"tinygo.org/x/drivers/as560x"
    10  )
    11  
    12  func main() {
    13  	// Let's use the AS5600 to make the world's most useless mouse with just a single X-axis & no buttons (!)
    14  	machine.I2C0.Configure(machine.I2CConfig{
    15  		Frequency: machine.TWI_FREQ_400KHZ,
    16  		SDA:       machine.GPIO4,
    17  		SCL:       machine.GPIO5,
    18  	})
    19  	as5600 := as560x.NewAS5600(machine.I2C0)
    20  	as5600.Configure(as560x.Config{})
    21  	mouse := mouse.New()
    22  
    23  	lastAngle := -1
    24  	for {
    25  		time.Sleep(time.Millisecond * 10)
    26  		// Get the magnet status of the AS5600
    27  		magnetDetected, magnetStrength, err := as5600.MagnetStatus()
    28  		if err != nil {
    29  			continue
    30  		}
    31  		// Get the raw angle from the AS5600
    32  		angle, _, err := as5600.RawAngle(as560x.ANGLE_NATIVE)
    33  		if err != nil {
    34  			continue
    35  		}
    36  		str := ""
    37  		if !magnetDetected {
    38  			str += "NOT "
    39  		}
    40  		str += "detected. Strength is "
    41  		switch magnetStrength {
    42  		case as560x.MagnetTooWeak:
    43  			str += "too weak"
    44  		case as560x.MagnetTooStrong:
    45  			str += "too strong"
    46  		default:
    47  			str += "ok"
    48  		}
    49  		println("Raw angle:", angle, "Magnet was", str)
    50  		if lastAngle != -1 {
    51  			diff := int(angle) - lastAngle
    52  			// correct the zero crossover glitch
    53  			if diff < -0xc00 {
    54  				diff += 0xfff
    55  			} else if diff > 0xc00 {
    56  				diff -= 0xfff
    57  			}
    58  			// debounce the noise (could use the sensor's filters/hysteresis instead?)
    59  			if math.Abs(float64(diff)) > 2 {
    60  				// move the mouse x-axis in response to the AS5600
    61  				mouse.Move(diff, 0)
    62  			}
    63  		}
    64  		lastAngle = int(angle)
    65  	}
    66  }