github.com/tinygo-org/tinygo@v0.31.3-0.20240404173401-90b0bf646c27/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 is the pin used for Chip Select (CS). Change to whatever is in use on your board.
    12  const cs = machine.Pin(3)
    13  
    14  var (
    15  	tx          []byte
    16  	rx          []byte
    17  	val, result uint16
    18  )
    19  
    20  func main() {
    21  	cs.Configure(machine.PinConfig{Mode: machine.PinOutput})
    22  
    23  	machine.SPI0.Configure(machine.SPIConfig{
    24  		Frequency: 4000000,
    25  		Mode:      3})
    26  
    27  	tx = make([]byte, 3)
    28  	rx = make([]byte, 3)
    29  
    30  	for {
    31  		val, _ = Read(0)
    32  		println(val)
    33  		time.Sleep(50 * time.Millisecond)
    34  	}
    35  }
    36  
    37  // Read analog data from channel
    38  func Read(channel int) (uint16, error) {
    39  	if channel < 0 || channel > 7 {
    40  		return 0, errors.New("Invalid channel for read")
    41  	}
    42  
    43  	tx[0] = 0x01
    44  	tx[1] = byte(8+channel) << 4
    45  	tx[2] = 0x00
    46  
    47  	cs.Low()
    48  	machine.SPI0.Tx(tx, rx)
    49  	result = uint16((rx[1]&0x3))<<8 + uint16(rx[2])
    50  	cs.High()
    51  
    52  	return result, nil
    53  }