1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
|
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <cstdint>
#include <unistd.h>
#include <string.h>
#include <linux/i2c-dev.h>
#include "I2cController.hpp"
namespace communications
{
namespace i2c
{
I2cController::I2cController()
{
}
I2cController::~I2cController()
{
}
void I2cController::initializeI2c(uint16_t& fd, const uint8_t& devAddr)
{
fd = open("/dev/i2c-1", O_RDWR);
if(fd < 0)
{
//LOG_ERROR("I2cController :: readBytes() Failed to open device");
return;
}
if (ioctl(fd, I2C_SLAVE, devAddr) < 0)
{
//LOG_ERROR("I2cController :: readBytes() Failed to select device");
close(fd);
return;
}
}
int8_t readBytes(uint16_t& fd, const uint8_t& regAddr, const uint8_t& length, uint8_t* data)
{
int8_t count = 0;
if (write(fd, ®Addr, 1) != 1)
{
//LOG_ERROR("I2cController :: readBytes() Failed to write reg");
close(fd);
return(-1);
}
count = read(fd, data, length);
if (count < 0)
{
//LOG_ERROR("I2cController :: readBytes() Failed to read device");
close(fd);
return(-1);
} else if (count != length)
{
//LOG_ERROR("I2cController :: readBytes() Short read from device");
close(fd);
return(-1);
}
}
int8_t writeBytes(uint16_t& fd, const uint8_t& regAddr, const uint8_t& length, uint8_t* data)
{
int8_t count = 0;
uint8_t buf[128];
buf[0] = regAddr;
memcpy(buf+1,data,length);
count = write(fd, buf, length+1);
if (count < 0) {
//LOG_ERROR("I2cController :: writeBytes() Failed to write device");
close(fd);
return(-1);
} else if (count != length+1) {
//LOG_ERROR("I2cController :: writeBytes() Short write to device");
close(fd);
return(-1);
}
}
void I2cController::closeI2c(uint16_t& fd)
{
close(fd);
}
}
} |
Partager