Last active
October 6, 2016 17:18
-
-
Save DavidEGrayson/8e84e69a24b58f65b6771593ad88a10c to your computer and use it in GitHub Desktop.
Better I2CBus.cpp. I want to integrate this into minimu9-ahrs.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "I2CBus.h" | |
#include <cerrno> | |
#include <cstring> | |
#include <system_error> | |
#include <string> | |
#include <unistd.h> | |
#include <fcntl.h> | |
#include <linux/i2c-dev.h> | |
static inline std::system_error posix_error(const std::string & what) | |
{ | |
return std::system_error(errno, std::system_category(), what); | |
} | |
I2CBus::I2CBus(const char * deviceName) | |
{ | |
fd = open(deviceName, O_RDWR); | |
if (fd == -1) | |
{ | |
throw posix_error(std::string("Failed to open I2C device ") + deviceName); | |
} | |
} | |
I2CBus::~I2CBus() | |
{ | |
close(fd); | |
} | |
void I2CBus::writeByteAndRead(uint8_t deviceAddress, uint8_t command, uint8_t size, uint8_t * data) | |
{ | |
i2c_msg messages[2] = { | |
{ deviceAddress, 0, 1, (typeof(i2c_msg().buf)) &command }, | |
{ deviceAddress, I2C_M_RD, size, (typeof(i2c_msg().buf)) data }, | |
}; | |
i2c_rdwr_ioctl_data ioctl_data = { messages, 2 }; | |
int result = ioctl(fd, I2C_RDWR, &ioctl_data); | |
if (result != 2) | |
{ | |
throw posix_error("Failed to read from I2C"); | |
} | |
} | |
void I2CBus::write(uint8_t deviceAddress, uint8_t size, const uint8_t * data) | |
{ | |
i2c_msg message = { deviceAddress, 0, size, (typeof(i2c_msg().buf)) data }; | |
i2c_rdwr_ioctl_data ioctl_data = { &message, 1 }; | |
int result = ioctl(fd, I2C_RDWR, &ioctl_data); | |
if (result != 1) | |
{ | |
throw posix_error("Failed to write to I2C"); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#pragma once | |
#include <stdint.h> | |
class I2CBus | |
{ | |
public: | |
I2CBus(const char * deviceName); | |
~I2CBus(); | |
void writeByteAndRead(uint8_t deviceAddress, uint8_t byte, | |
uint8_t size, uint8_t * data); | |
void write(uint8_t deviceAddress, uint8_t size, const uint8_t * data); | |
void writeTwoBytes(uint8_t deviceAddress, uint8_t byte1, uint8_t byte2) | |
{ | |
uint8_t buffer[] = { byte1, byte2 }; | |
write(deviceAddress, 2, buffer); | |
} | |
uint8_t writeByteAndReadByte(uint8_t deviceAddress, uint8_t byte1) | |
{ | |
uint8_t byte2; | |
writeByteAndRead(deviceAddress, byte1, 1, &byte2); | |
return byte2; | |
} | |
// TODO: | |
//int tryWriteByteAndReadByte(uint8_t deviceAddress, uint8_t byte1); | |
private: | |
int fd; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment