You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
67 lines
1.5 KiB
67 lines
1.5 KiB
#include "i2c_driver.h"
|
|
#include "systemCall.h"
|
|
|
|
#include <cstdio>
|
|
#include <ostream>
|
|
#include <iostream>
|
|
#include <linux/i2c-dev.h>
|
|
#include <fcntl.h>
|
|
#include <unistd.h>
|
|
#include <sys/ioctl.h>
|
|
#include <sys/types.h>
|
|
#include <sys/stat.h>
|
|
|
|
|
|
#define PORT_I2C "/dev/i2c-1"
|
|
|
|
|
|
I2C_Driver::I2C_Driver(const uint8_t& channel, const uint8_t& mode)
|
|
{
|
|
char filename[20];
|
|
snprintf(filename, 19, "/dev/i2c-%d", channel);
|
|
|
|
deviceDescriptor = open(filename, O_RDWR);
|
|
if (deviceDescriptor < 0) {
|
|
std::cout << "unable to open : "<< deviceDescriptor << " ! quiting" << std::endl;
|
|
exit(1);
|
|
}
|
|
std::cout << "I2C initialized sucsessfully" << std::endl;
|
|
}
|
|
|
|
uint8_t I2C_Driver::writeByte(const uint8_t& address, const uint8_t& data) // retuns 0 when a sucsessful transation ocures
|
|
{
|
|
if (ioctl(deviceDescriptor, I2C_SLAVE, address) < 0)
|
|
{
|
|
std::cout << "Unable to reach device : "<< address << " ! quiting" << std::endl;
|
|
exit(1);
|
|
}
|
|
|
|
send_buffer[0] = data;
|
|
|
|
if ((write(deviceDescriptor, send_buffer, 1)) != 1)
|
|
{
|
|
std::cout << "Unable to write quiting" << std::endl;
|
|
exit(0);
|
|
}
|
|
return 1;
|
|
}
|
|
|
|
uint8_t I2C_Driver::readByte(const uint8_t& address, const uint8_t& reg)
|
|
{
|
|
if (ioctl(deviceDescriptor, I2C_SLAVE, address) < 0)
|
|
{
|
|
std::cout << "Unable to reach device : "<< address << " ! quiting" << std::endl;
|
|
exit(1);
|
|
}
|
|
|
|
if(writeByte(address,reg))
|
|
{
|
|
if (read(deviceDescriptor, recieve_buffer, 1) != 1)
|
|
{
|
|
std::cout << "Unable to read quiting" << std::endl;
|
|
exit(1); // ERROR HANDLING: i2c transaction failed
|
|
}
|
|
}
|
|
return recieve_buffer[0] ;
|
|
}
|