-
Notifications
You must be signed in to change notification settings - Fork 83
/
I2CInterface.cpp
63 lines (53 loc) · 1.64 KB
/
I2CInterface.cpp
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
/*
* File: I2CInterface.cpp
* Author: Matthew
*
* Created on 21 October 2012, 10:38
*/
#include "I2CInterface.h"
I2CInterfaceClass I2CInterface;
I2CInterfaceClass::I2CInterfaceClass()
{
strcpy(filename_, "/dev/i2c-1");
openInterface();
}
I2CInterfaceClass::~I2CInterfaceClass()
{
close(file_);
}
void I2CInterfaceClass::openInterface()
{
pthread_mutex_lock (&I2Cmutex_);
if ((file_ = open(filename_, O_RDWR)) < 0)
{
std::cout << "Failed to open the i2c bus at path " << filename_ << std::endl;
}
pthread_mutex_unlock (&I2Cmutex_);
}
bool I2CInterfaceClass::writeRegister(unsigned char slaveAddress, unsigned char registerAddress, unsigned char* buf, unsigned char len)
{
pthread_mutex_lock (&I2Cmutex_);
setSlaveAddress_(slaveAddress);
if (i2c_smbus_write_i2c_block_data(file_, registerAddress, len, buf) < 0)
{
std::cout << "I2C write failed writing to " << std::hex << slaveAddress << std::endl;
}
pthread_mutex_unlock (&I2Cmutex_);
}
bool I2CInterfaceClass::readRegister(unsigned char slaveAddress, unsigned char registerAddress, unsigned char* buf, unsigned char len)
{
pthread_mutex_lock (&I2Cmutex_);
setSlaveAddress_(slaveAddress);
if (i2c_smbus_read_i2c_block_data(file_, registerAddress, len, buf) != len)
{
std::cout << "Incorrect number of bytes read" << std::endl;
}
pthread_mutex_unlock (&I2Cmutex_);
}
void I2CInterfaceClass::setSlaveAddress_(unsigned char address)
{
if (ioctl(file_, I2C_SLAVE, address) < 0)
{
std::cout << "Failed to set I2C slave address at file descriptor " << file_ << " errno " << errno << std::endl;
}
}