我解决了寻找如何接线PiI2C(https://github.com/WiringPi/WiringPi/blob/master/wiringPi/wiringPiI2C.c https://github.com/WiringPi/WiringPi/blob/master/wiringPi/wiringPiI2C.c)做了并修改了我的代码上的一些点。
TEST_F(I2CTest, TestReadAndWriteI2C) {
// ------- LOAD i2c_stub KERNEL MODULE -------
char *params;
int fd;
size_t image_size;
struct stat st;
void *image;
// command: sudo insmod /root/i2c-tests/i2c-stub.ko chip_addr=0x20
params = "chip_addr=0x20";
fd = open("/root/i2c-tests/i2c-stub.ko", O_RDONLY);
fstat(fd, &st);
image_size = st.st_size;
image = malloc(image_size);
read(fd, image, image_size);
close(fd);
if (init_module(image, image_size, params) != 0) {
perror("init_module");
std::cout
<< "Please make sure that the following commands were executed " <<
"on the directory [/root/i2c-tests/] before to run the unit test TestAddKernelModule " <<
"and the file [/root/i2c-tests/i2c-stub.ko] exists." << std::endl;
std::cout << "sudo rmmod i2c_stub" << std::endl;
std::cout << "sudo make -C /lib/modules/$(uname -r)/build M=$(pwd) clean" << std::endl;
std::cout << "sudo make -C /lib/modules/$(uname -r)/build M=$(pwd) modules" << std::endl;
std::cout << "sudo make -C /lib/modules/$(uname -r)/build M=$(pwd) modules_install" << std::endl;
GTEST_FAIL();
}
free(image);
GTEST_SUCCESS_("Kernel module loaded.");
// This initialises the I2C system with your given device identifier.
int i2cFileDescriptor;
if ((i2cFileDescriptor = open("/dev/i2c-3", O_RDWR)) < 0) {
GTEST_FAIL();
}
if (ioctl(i2cFileDescriptor, I2C_SLAVE, 0x20) < 0) {
GTEST_FAIL();
}
// Write bytes on I2C bus
union i2c_smbus_data data;
data.byte = 5;
i2c_smbus_access(i2cFileDescriptor, I2C_SMBUS_WRITE, 0x00, I2C_SMBUS_BYTE_DATA, &data);
// Read bytes from I2C bus
union i2c_smbus_data dataRead;
if (i2c_smbus_access(i2cFileDescriptor, I2C_SMBUS_READ, 0x00, I2C_SMBUS_BYTE_DATA, &dataRead)) {
GTEST_FAIL();
} else {
ASSERT_EQ(data.byte, dataRead.byte);
std::cout << "Read: " << std::hex << static_cast<int>(dataRead.byte ) << std::endl;
std::cout << "Read: " << (int) dataRead.byte << std::endl;
GTEST_SUCCESS_("Read bytes from I2C bus.");
}
// Write word on I2C bus
data.word = 556;
i2c_smbus_access(i2cFileDescriptor, I2C_SMBUS_WRITE, 0x00, I2C_SMBUS_WORD_DATA, &data);
// Read word from I2C bus
union i2c_smbus_data wordRead;
if (i2c_smbus_access(fd, I2C_SMBUS_READ, 0x00, I2C_SMBUS_WORD_DATA, &wordRead)) {
GTEST_FAIL();
} else {
ASSERT_EQ(data.word, wordRead.word);
std::cout << "Read: " << std::hex << static_cast<int>(wordRead.word ) << std::endl;
std::cout << "Read: " << (int) wordRead.word << std::endl;
std::cout << "Read: " << wordRead.word << std::endl;
GTEST_SUCCESS_("Read word from I2C bus.");
}
// return data.word & 0xFFFF ;
}