github.com/aykevl/tinygo@v0.5.0/src/examples/mcp3008/mcp3008.go (about)

     1  // Connects to an MCP3008 ADC via SPI.
     2  // Datasheet: https://www.microchip.com/wwwproducts/en/en010530
     3  package main
     4  
     5  import (
     6  	"errors"
     7  	"machine"
     8  	"time"
     9  )
    10  
    11  // CS_PIN is the pin used for Chip Select (CS). Change to whatever is in use on your board.
    12  const CS_PIN = 3
    13  
    14  var (
    15  	tx          []byte
    16  	rx          []byte
    17  	val, result uint16
    18  	cs          machine.GPIO
    19  )
    20  
    21  func main() {
    22  	cs = machine.GPIO{CS_PIN}
    23  	cs.Configure(machine.GPIOConfig{Mode: machine.GPIO_OUTPUT})
    24  
    25  	machine.SPI0.Configure(machine.SPIConfig{
    26  		Frequency: 4000000,
    27  		Mode:      3})
    28  
    29  	tx = make([]byte, 3)
    30  	rx = make([]byte, 3)
    31  
    32  	for {
    33  		val, _ = Read(0)
    34  		println(val)
    35  		time.Sleep(50 * time.Millisecond)
    36  	}
    37  }
    38  
    39  // Read analog data from channel
    40  func Read(channel int) (uint16, error) {
    41  	if channel < 0 || channel > 7 {
    42  		return 0, errors.New("Invalid channel for read")
    43  	}
    44  
    45  	tx[0] = 0x01
    46  	tx[1] = byte(8+channel) << 4
    47  	tx[2] = 0x00
    48  
    49  	cs.Low()
    50  	machine.SPI0.Tx(tx, rx)
    51  	result = uint16((rx[1]&0x3))<<8 + uint16(rx[2])
    52  	cs.High()
    53  
    54  	return result, nil
    55  }