|
| 1 | +// Package pcf8591 implements a driver for the PCF8591 Analog to Digital/Digital to Analog Converter. |
| 2 | +// |
| 3 | +// Datasheet: https://www.nxp.com/docs/en/data-sheet/PCF8591.pdf |
| 4 | +package pcf8591 // import "tinygo.org/x/drivers/pcf8591" |
| 5 | + |
| 6 | +import ( |
| 7 | + "machine" |
| 8 | + |
| 9 | + "errors" |
| 10 | + |
| 11 | + "tinygo.org/x/drivers" |
| 12 | +) |
| 13 | + |
| 14 | +// Device wraps PCF8591 ADC functions. |
| 15 | +type Device struct { |
| 16 | + bus drivers.I2C |
| 17 | + Address uint16 |
| 18 | + CH0 ADCPin |
| 19 | + CH1 ADCPin |
| 20 | + CH2 ADCPin |
| 21 | + CH3 ADCPin |
| 22 | +} |
| 23 | + |
| 24 | +// ADCPin is the implementation of the ADConverter interface. |
| 25 | +type ADCPin struct { |
| 26 | + machine.Pin |
| 27 | + d *Device |
| 28 | +} |
| 29 | + |
| 30 | +// New returns a new PCF8591 driver. Pass in a fully configured I2C bus. |
| 31 | +func New(b drivers.I2C) *Device { |
| 32 | + d := &Device{ |
| 33 | + bus: b, |
| 34 | + Address: defaultAddress, |
| 35 | + } |
| 36 | + |
| 37 | + // setup all channels |
| 38 | + d.CH0 = d.GetADC(0) |
| 39 | + d.CH1 = d.GetADC(1) |
| 40 | + d.CH2 = d.GetADC(2) |
| 41 | + d.CH3 = d.GetADC(3) |
| 42 | + |
| 43 | + return d |
| 44 | +} |
| 45 | + |
| 46 | +// Configure here just for interface compatibility. |
| 47 | +func (d *Device) Configure() { |
| 48 | +} |
| 49 | + |
| 50 | +// Read analog data from channel |
| 51 | +func (d *Device) Read(ch int) (uint16, error) { |
| 52 | + if ch < 0 || ch > 3 { |
| 53 | + return 0, errors.New("invalid channel for pcf8591 Read") |
| 54 | + } |
| 55 | + |
| 56 | + return d.GetADC(ch).Get(), nil |
| 57 | +} |
| 58 | + |
| 59 | +// GetADC returns an ADC for a specific channel. |
| 60 | +func (d *Device) GetADC(ch int) ADCPin { |
| 61 | + return ADCPin{machine.Pin(ch), d} |
| 62 | +} |
| 63 | + |
| 64 | +// Get the current reading for a specific ADCPin. |
| 65 | +func (p ADCPin) Get() uint16 { |
| 66 | + // TODO: also implement DAC |
| 67 | + tx := make([]byte, 2) |
| 68 | + tx[0] = byte(p.Pin) |
| 69 | + |
| 70 | + rx := make([]byte, 2) |
| 71 | + |
| 72 | + // The result from the measurement triggered by the first write, |
| 73 | + // however, the second write is required to get the result. |
| 74 | + // See section 8.4 "A/D Conversion" in the datasheet for more info |
| 75 | + p.d.bus.Tx(p.d.Address, tx, rx) |
| 76 | + p.d.bus.Tx(p.d.Address, tx, rx) |
| 77 | + |
| 78 | + // scale result to 16bit value like other ADCs |
| 79 | + return uint16(rx[1] << 8) |
| 80 | +} |
| 81 | + |
| 82 | +// Configure here just for interface compatibility. |
| 83 | +func (p ADCPin) Configure() { |
| 84 | +} |
0 commit comments