forked from warthog618/go-gpiocdev
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mcp3208.go
90 lines (85 loc) · 2.35 KB
/
mcp3208.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
// SPDX-FileCopyrightText: 2019 Kent Gibson <warthog618@gmail.com>
//
// SPDX-License-Identifier: MIT
// An example of reading values from a MCP3208 using the bit-bashed SPI driver.
package main
import (
"fmt"
"os"
"github.com/warthog618/config"
"github.com/warthog618/config/blob"
"github.com/warthog618/config/blob/decoder/json"
"github.com/warthog618/config/dict"
"github.com/warthog618/config/env"
"github.com/warthog618/config/pflag"
"github.com/warthog618/gpiod"
"github.com/warthog618/gpiod/device/rpi"
"github.com/warthog618/gpiod/spi/mcp3w0c"
)
// This example reads both channels from an MCP3208 connected to the RPI by four
// data lines - CSZ, CLK, DI, and DO. The default pin assignments are defined in
// loadConfig, but can be altered via configuration (env, flag or config file).
// All pins other than DO are outputs so do not run this example on a board
// where those pins serve other purposes.
func main() {
cfg := loadConfig()
tclk := cfg.MustGet("tclk").Duration()
tset := cfg.MustGet("tset").Duration()
if tset < tclk {
tset = 0
} else {
tset -= tclk
}
chip := cfg.MustGet("gpiochip").String()
c, err := gpiod.NewChip(chip, gpiod.WithConsumer("mcp3208"))
if err != nil {
fmt.Fprintf(os.Stderr, "mcp3208: %s\n", err)
os.Exit(1)
}
adc, err := mcp3w0c.NewMCP3208(
c,
cfg.MustGet("clk").Int(),
cfg.MustGet("csz").Int(),
cfg.MustGet("di").Int(),
cfg.MustGet("do").Int(),
mcp3w0c.WithTclk(tclk),
mcp3w0c.WithTset(tset),
)
c.Close()
if err != nil {
fmt.Printf("mcp3208: %s\n", err)
os.Exit(1)
}
defer adc.Close()
for ch := 0; ch < 8; ch++ {
d, err := adc.Read(ch)
if err != nil {
fmt.Printf("error reading ch%d: %s\n", ch, err)
continue
}
fmt.Printf("ch%d=0x%04x\n", ch, d)
}
}
func loadConfig() *config.Config {
defaultConfig := map[string]interface{}{
"gpiochip": "gpiochip0",
"tclk": "500ns",
"tset": "750ns",
"clk": rpi.J8p36,
"csz": rpi.J8p37,
"di": rpi.J8p38,
"do": rpi.J8p40,
}
def := dict.New(dict.WithMap(defaultConfig))
flags := []pflag.Flag{
{Short: 'c', Name: "config-file"},
}
cfg := config.New(
pflag.New(pflag.WithFlags(flags)),
env.New(env.WithEnvPrefix("MCP3208_")),
config.WithDefault(def))
cfg.Append(
blob.NewConfigFile(cfg, "config.file", "mcp3208.json", json.NewDecoder()))
cfg = cfg.GetConfig("", config.WithMust())
return cfg
}