Skip to content

Commit

Permalink
examples: add example showing how to create a peripheral using the Ba…
Browse files Browse the repository at this point in the history
…ttery Service

Signed-off-by: deadprogram <[email protected]>
  • Loading branch information
deadprogram committed Jan 9, 2025
1 parent 4f8491d commit ab457cb
Showing 1 changed file with 64 additions and 0 deletions.
64 changes: 64 additions & 0 deletions examples/battery/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
// example that demonstrates how to create a BLE peripheral device with the Battery Service.
package main

import (
"math/rand"
"time"

"tinygo.org/x/bluetooth"
)

var adapter = bluetooth.DefaultAdapter

var (
localName = "TinyGo Battery"

batteryLevel uint8 = 75 // 75%
battery bluetooth.Characteristic
)

func main() {
println("starting")
must("enable BLE stack", adapter.Enable())
adv := adapter.DefaultAdvertisement()
must("config adv", adv.Configure(bluetooth.AdvertisementOptions{
LocalName: localName,
ServiceUUIDs: []bluetooth.UUID{bluetooth.ServiceUUIDBattery},
}))
must("start adv", adv.Start())

must("add service", adapter.AddService(&bluetooth.Service{
UUID: bluetooth.ServiceUUIDBattery,
Characteristics: []bluetooth.CharacteristicConfig{
{
Handle: &battery,
UUID: bluetooth.CharacteristicUUIDBatteryLevel,
Value: []byte{byte(batteryLevel)},
Flags: bluetooth.CharacteristicReadPermission | bluetooth.CharacteristicNotifyPermission,
},
},
}))

for {
println("tick", time.Now().Format("04:05.000"))

// random variation in batteryLevel
batteryLevel = randomInt(65, 85)

// and push the next notification
battery.Write([]byte{batteryLevel})

time.Sleep(time.Second)
}
}

func must(action string, err error) {
if err != nil {
panic("failed to " + action + ": " + err.Error())
}
}

// Returns an int >= min, < max
func randomInt(min, max int) uint8 {
return uint8(min + rand.Intn(max-min))
}

0 comments on commit ab457cb

Please sign in to comment.