| 1 | // Copyright 2016 The Go Authors. All rights reserved. |
| 2 | // Use of this source code is governed by a BSD-style |
| 3 | // license that can be found in the LICENSE file. |
| 4 | |
| 5 | // Package i2c allows users to read from and write to a slave I2C device. |
| 6 | // |
| 7 | // # Deprecated |
| 8 | // |
| 9 | // This package is not maintained anymore. An actively supported cross-platform |
| 10 | // alternative is https://periph.io/. |
| 11 | package i2c // import "golang.org/x/exp/io/i2c" |
| 12 | |
| 13 | import ( |
| 14 | "golang.org/x/exp/io/i2c/driver" |
| 15 | ) |
| 16 | |
| 17 | const tenbitMask = 1 << 12 |
| 18 | |
| 19 | // Device represents an I2C device. Devices must be closed once |
| 20 | // they are no longer in use. |
| 21 | type Device struct { |
| 22 | conn driver.Conn |
| 23 | } |
| 24 | |
| 25 | // TenBit marks an I2C address as a 10-bit address. |
| 26 | func TenBit(addr int) int { |
| 27 | return addr | tenbitMask |
| 28 | } |
| 29 | |
| 30 | // Read reads len(buf) bytes from the device. |
| 31 | func (d *Device) Read(buf []byte) error { |
| 32 | return d.conn.Tx(nil, buf) |
| 33 | } |
| 34 | |
| 35 | // ReadReg is similar to Read but it reads from a register. |
| 36 | func (d *Device) ReadReg(reg byte, buf []byte) error { |
| 37 | return d.conn.Tx([]byte{reg}, buf) |
| 38 | } |
| 39 | |
| 40 | // Write writes the buffer to the device. If it is required to write to a |
| 41 | // specific register, the register should be passed as the first byte in the |
| 42 | // given buffer. |
| 43 | func (d *Device) Write(buf []byte) (err error) { |
| 44 | return d.conn.Tx(buf, nil) |
| 45 | } |
| 46 | |
| 47 | // WriteReg is similar to Write but writes to a register. |
| 48 | func (d *Device) WriteReg(reg byte, buf []byte) (err error) { |
| 49 | // TODO(jbd): Do not allocate, not optimal. |
| 50 | return d.conn.Tx(append([]byte{reg}, buf...), nil) |
| 51 | } |
| 52 | |
| 53 | // Close closes the device and releases the underlying sources. |
| 54 | func (d *Device) Close() error { |
| 55 | return d.conn.Close() |
| 56 | } |
| 57 | |
| 58 | // Open opens a connection to an I2C device. |
| 59 | // All devices must be closed once they are no longer in use. |
| 60 | // For devices that use 10-bit I2C addresses, addr can be marked |
| 61 | // as a 10-bit address with TenBit. |
| 62 | func Open(o driver.Opener, addr int) (*Device, error) { |
| 63 | unmasked, tenbit := resolveAddr(addr) |
| 64 | conn, err := o.Open(unmasked, tenbit) |
| 65 | if err != nil { |
| 66 | return nil, err |
| 67 | } |
| 68 | return &Device{conn: conn}, nil |
| 69 | } |
| 70 | |
| 71 | // resolveAddr returns whether the addr is 10-bit masked or not. |
| 72 | // It also returns the unmasked address. |
| 73 | func resolveAddr(addr int) (unmasked int, tenbit bool) { |
| 74 | return addr & (tenbitMask - 1), addr&tenbitMask == tenbitMask |
| 75 | } |