| // Copyright 2015 The Android Open Source Project |
| // |
| // Licensed under the Apache License, Version 2.0 (the "License"); |
| // you may not use this file except in compliance with the License. |
| // You may obtain a copy of the License at |
| // |
| // http://www.apache.org/licenses/LICENSE-2.0 |
| // |
| // Unless required by applicable law or agreed to in writing, software |
| // distributed under the License is distributed on an "AS IS" BASIS, |
| // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| // See the License for the specific language governing permissions and |
| // limitations under the License. |
| |
| // Defines a single i2c device at an address for a named i2c bus. |
| // |
| // Can be used to read and write i2c registers, or send arbitrary streams of |
| // messages. |
| |
| |
| #include <fcntl.h> |
| #include <linux/i2c.h> |
| #include <linux/i2c-dev.h> |
| #include <android-base/logging.h> |
| |
| |
| class I2CDevice { |
| |
| public: |
| // Creates an I2CDevice for a given filename and address. |
| // |
| // For example: I2CDevice my_device("/dev/i2c-0", 0x20); |
| // |
| // Note: this constructor does not actually open the device, Begin() must be |
| // called at the appropriate time. |
| I2CDevice(const char* device_filename, |
| const uint8_t device_address); |
| // Opens the device for reading and writing. Returns 0 on success, or the |
| // error code from the open/ioctl operations. |
| int Begin(); |
| // Closes the device. Returns 0 on success or the error code from the close |
| // operation. |
| int End(); |
| // Sends a sequence of I2C messages. This is used for write operations AND |
| // read operations, since reads are just an empty outbound message. Returns 0 |
| // on success or the error code from the ioctl operation. |
| int Send(struct i2c_msg messages[], |
| const size_t count); |
| // Sets a register at a given address to a given value. Returns 0 on success |
| // or the error code from the ioctl operation. |
| int SetRegister(const uint8_t register_address, |
| const uint8_t value); |
| // Reads a register into a passed value. Returns 0 on success or the error |
| // code from the ioctl operation. |
| int GetRegister(const uint8_t register_address, |
| uint8_t& value); |
| |
| private: |
| // Demonstrates opening a device. |
| int open_i2c(); |
| // Demonstrates sending the I2C_SLAVE ioctl. |
| int enslave_i2c(); |
| |
| // Stores the device address. |
| const uint8_t address_; |
| // Stores the device filename. |
| const char* filename_; |
| // Stores the open file descriptor for the device. |
| int fd_; |
| }; |