Hotwheels-Cluster 1.2
Creation of Cluster APP for SEA:ME project.
 
Loading...
Searching...
No Matches
I2CController.cpp
Go to the documentation of this file.
1
18
19#include "I2CController.hpp"
20#include <array>
21#include <cstdio>
22#include <fcntl.h>
23#include <linux/i2c-dev.h>
24#include <sys/ioctl.h>
25#include <unistd.h>
26
36I2CController::I2CController(const char *i2c_device, int address)
37 : i2c_fd_(-1), i2c_addr_(address) {
38 // Open I2C device
39 i2c_fd_ = open(i2c_device, O_RDWR);
40 if (i2c_fd_ < 0) {
41 perror("Failed to open I2C device");
42 }
43
44 // Set I2C address
45 if (ioctl(i2c_fd_, I2C_SLAVE, i2c_addr_) < 0) {
46 perror("Failed to set I2C address");
47 }
48}
49
55 if (i2c_fd_ >= 0) {
56 close(i2c_fd_);
57 }
58}
59
66void I2CController::writeRegister(uint8_t reg, uint16_t value) {
67 std::array<uint8_t, 3> buffer = {reg, static_cast<uint8_t>(value >> 8),
68 static_cast<uint8_t>(value & 0xFF)};
69 if (write(i2c_fd_, buffer.data(), buffer.size()) != 3) {
70 perror("I2C write failed");
71 }
72}
73
81uint16_t I2CController::readRegister(uint8_t reg) {
82 if (write(i2c_fd_, &reg, 1) != 1) {
83 perror("I2C write failed");
84 }
85 std::array<uint8_t, 2> buffer;
86 if (read(i2c_fd_, buffer.data(), buffer.size()) != 2) {
87 perror("I2C read failed");
88 }
89 return (buffer[0] << 8) | buffer[1];
90}
Definition of the I2CController class.
uint16_t readRegister(uint8_t reg) override
Read a 16-bit value from a register.
void writeRegister(uint8_t reg, uint16_t value) override
Write a 16-bit value to a register.
~I2CController() override
Destroy the I2CController object.
I2CController(const char *i2c_device, int address)
Construct a new I2CController object.