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.
106 lines
1.6 KiB
106 lines
1.6 KiB
/*
|
|
* i2csensor.cc
|
|
*
|
|
* Created on: 18.12.2017
|
|
* Author: steffen
|
|
*/
|
|
|
|
#include <unistd.h>
|
|
#include <fcntl.h>
|
|
#include <sys/ioctl.h>
|
|
#include <linux/i2c-dev.h>
|
|
#include <stdlib.h>
|
|
#include <stdio.h>
|
|
#include <sys/types.h>
|
|
#include <sys/stat.h>
|
|
#include <errno.h>
|
|
#include <string.h>
|
|
|
|
#include "i2csensor.h"
|
|
|
|
|
|
#define LEN_FILENAME 255
|
|
#define LEN_BUFFER 32
|
|
|
|
I2C::I2C () {
|
|
i2cdev = 1;
|
|
};
|
|
|
|
I2C::~I2C () {
|
|
};
|
|
|
|
bool I2C::ReadByte(int addr, int reg, uint8_t *readval) {
|
|
int file;
|
|
char filename[LEN_FILENAME];
|
|
unsigned char buffer[LEN_BUFFER];
|
|
|
|
if (readval == NULL) return false;
|
|
// i2c device
|
|
snprintf(filename, 255, "/dev/i2c-%d", i2cdev);
|
|
file = open(filename, O_RDWR);
|
|
if (file < 0) {
|
|
return false;
|
|
}
|
|
|
|
// setup slave addresse
|
|
if (ioctl(file, I2C_SLAVE, addr) < 0) {
|
|
close (file);
|
|
return false;
|
|
}
|
|
|
|
usleep (10000);
|
|
|
|
// write register
|
|
buffer[0] = reg;
|
|
if (write(file, buffer, 1) != 1) {
|
|
close (file);
|
|
return false;
|
|
}
|
|
|
|
// read value
|
|
if (read(file, buffer, 1) != 1) {
|
|
close (file);
|
|
return false;
|
|
}
|
|
|
|
*readval = buffer[0];
|
|
close (file);
|
|
|
|
return true;
|
|
};
|
|
|
|
bool I2C::SendByte(int addr, int reg, uint8_t data) {
|
|
int file;
|
|
char filename[LEN_FILENAME];
|
|
unsigned char buffer[LEN_BUFFER];
|
|
|
|
// i2c device
|
|
snprintf(filename, 255, "/dev/i2c-%d", i2cdev);
|
|
file = open(filename, O_RDWR);
|
|
if (file < 0) {
|
|
return false;
|
|
}
|
|
|
|
// setup slave addresse
|
|
if (ioctl(file, I2C_SLAVE, addr) < 0) {
|
|
close (file);
|
|
return false;
|
|
}
|
|
|
|
usleep (10000);
|
|
|
|
// write register and value
|
|
buffer[0] = reg;
|
|
buffer[1] = data;
|
|
if (write(file, buffer, 2) != 2) {
|
|
close (file);
|
|
return false;
|
|
}
|
|
close (file);
|
|
|
|
return true;
|
|
};
|
|
|
|
|
|
|