gobot.io/x/gobot@v1.16.0/examples/raspi_adafruit_servo.go (about)

     1  // +build example
     2  //
     3  // Do not build by default.
     4  
     5  package main
     6  
     7  import (
     8  	"log"
     9  	"time"
    10  
    11  	"gobot.io/x/gobot"
    12  	"gobot.io/x/gobot/drivers/i2c"
    13  	"gobot.io/x/gobot/platforms/raspi"
    14  )
    15  
    16  var (
    17  	// Min pulse length out of 4096
    18  	servoMin = 150
    19  	// Max pulse length out of 4096
    20  	servoMax = 700
    21  	// Limiting the max this servo can rotate (in deg)
    22  	maxDegree = 180
    23  	// Number of degrees to increase per call
    24  	degIncrease = 10
    25  	yawDeg      = 90
    26  )
    27  
    28  func degree2pulse(deg int) int32 {
    29  	pulse := servoMin
    30  	pulse += ((servoMax - servoMin) / maxDegree) * deg
    31  	return int32(pulse)
    32  }
    33  
    34  func adafruitServoMotorRunner(a *i2c.AdafruitMotorHatDriver) (err error) {
    35  	log.Printf("Servo Motor Run Loop...\n")
    36  	// Changing from the default 0x40 address because this configuration involves
    37  	// a Servo HAT stacked on top of a DC/Stepper Motor HAT on top of the Pi.
    38  	stackedHatAddr := 0x41
    39  	var channel byte = 1
    40  	deg := 90
    41  
    42  	// update the I2C address state
    43  	a.SetServoHatAddress(stackedHatAddr)
    44  
    45  	// Do not need to set this every run loop
    46  	freq := 60.0
    47  	if err = a.SetServoMotorFreq(freq); err != nil {
    48  		log.Printf("%s", err.Error())
    49  		return
    50  	}
    51  	// start in the middle of the 180-deg range
    52  	pulse := degree2pulse(deg)
    53  	if err = a.SetServoMotorPulse(channel, 0, pulse); err != nil {
    54  		log.Printf(err.Error())
    55  		return
    56  	}
    57  	// INCR
    58  	pulse = degree2pulse(deg + degIncrease)
    59  	if err = a.SetServoMotorPulse(channel, 0, pulse); err != nil {
    60  		log.Printf(err.Error())
    61  		return
    62  	}
    63  	time.Sleep(2000 * time.Millisecond)
    64  	// DECR
    65  	pulse = degree2pulse(deg - degIncrease)
    66  	if err = a.SetServoMotorPulse(channel, 0, pulse); err != nil {
    67  		log.Printf(err.Error())
    68  		return
    69  	}
    70  	return
    71  }
    72  
    73  func main() {
    74  	r := raspi.NewAdaptor()
    75  	adaFruit := i2c.NewAdafruitMotorHatDriver(r)
    76  
    77  	work := func() {
    78  		gobot.Every(5*time.Second, func() {
    79  			adafruitServoMotorRunner(adaFruit)
    80  		})
    81  	}
    82  
    83  	robot := gobot.NewRobot("adaFruitBot",
    84  		[]gobot.Connection{r},
    85  		[]gobot.Device{adaFruit},
    86  		work,
    87  	)
    88  
    89  	robot.Start()
    90  }