forked from periph/devices
-
Notifications
You must be signed in to change notification settings - Fork 0
/
piblaster.go
66 lines (58 loc) · 1.66 KB
/
piblaster.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
// Copyright 2016 The Periph Authors. All rights reserved.
// Use of this source code is governed under the Apache License, Version 2.0
// that can be found in the LICENSE file.
// Package piblaster implements interfacing code is piblaster.
//
// See https://github.com/sarfata/pi-blaster for more details. This package
// relies on pi-blaster being installed and enabled.
//
// TODO(maruel): "dtoverlay=pwm" or "dtoverlay=pwm-2chan" works without having
// to install anything, albeit with less pins supported.
//
// Warning
//
// piblaster doesn't report what pins is controls so it is easy to misuse this
// library.
package piblaster
import (
"fmt"
"io"
"os"
"periph.io/x/conn/v3/gpio"
)
// SetPWM enables and sets the PWM duty on a GPIO output pin via piblaster.
//
// duty must be [0, 1].
func SetPWM(p gpio.PinIO, duty float32) error {
if duty < 0 || duty > 1 {
return fmt.Errorf("piblaster: duty %f is invalid for blaster", duty)
}
err := openPiblaster()
if err == nil {
_, err = io.WriteString(piblasterHandle, fmt.Sprintf("%d=%f\n", p.Number(), duty))
}
return err
}
// ReleasePWM releases a GPIO output and leave it floating.
//
// This function must be called on process exit for each activated pin
// otherwise the pin will stay in the state.
func ReleasePWM(p gpio.PinIO) error {
err := openPiblaster()
if err == nil {
_, err = io.WriteString(piblasterHandle, fmt.Sprintf("release %d\n", p.Number()))
}
return err
}
//
var piblasterHandle io.WriteCloser
func openPiblaster() error {
if piblasterHandle == nil {
f, err := os.OpenFile("/dev/pi-blaster", os.O_WRONLY|os.O_APPEND, 0644)
if err != nil {
return err
}
piblasterHandle = f
}
return nil
}