Skip to content

Instantly share code, notes, and snippets.

@deadprogram
Created December 1, 2018 12:02
Show Gist options
  • Save deadprogram/4af8f3d203779c264bb28d9efcf4443b to your computer and use it in GitHub Desktop.
Save deadprogram/4af8f3d203779c264bb28d9efcf4443b to your computer and use it in GitHub Desktop.
// Connects to an MCP3008 ADC via SPI.
package main
import (
"errors"
"machine"
"time"
)
var (
tx []byte
rx []byte
val, result uint16
cs machine.GPIO
)
func main() {
cs = machine.GPIO{3}
cs.Configure(machine.GPIOConfig{Mode: machine.GPIO_OUTPUT})
machine.SPI0.Configure(machine.SPIConfig{
Frequency: 4000000,
Mode: 3,
SCK: machine.SPI0_SCK_PIN,
MOSI: machine.SPI0_MOSI_PIN,
MISO: machine.SPI0_MISO_PIN})
tx = make([]byte, 3)
rx = make([]byte, 3)
for {
val, _ = Read(0)
println(val)
time.Sleep(50 * time.Millisecond)
}
}
// Read analog data from channel
func Read(channel int) (uint16, error) {
if channel < 0 || channel > 7 {
return 0, errors.New("Invalid channel for read")
}
tx[0] = 0x01
tx[1] = byte(8+channel) << 4
tx[2] = 0x00
cs.Low()
machine.SPI0.Tx(tx, rx)
result = uint16((rx[1]&0x3))<<8 + uint16(rx[2])
cs.High()
return result, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment