61 lines
1.6 KiB
C++
61 lines
1.6 KiB
C++
// i2c_linux.c
|
|
#include "i2c_linux.h"
|
|
#include <stdio.h>
|
|
#include <string.h>
|
|
#include <fcntl.h>
|
|
#include <sys/ioctl.h>
|
|
#include <linux/i2c-dev.h>
|
|
|
|
/* Open the I2C bus node for read/write :contentReference[oaicite:0]{index=0} */
|
|
int i2c_open_bus(const char *bus)
|
|
{
|
|
int fd = open(bus, O_RDWR);
|
|
if (fd < 0) {
|
|
perror("I2C open failed");
|
|
}
|
|
return fd;
|
|
}
|
|
|
|
void i2c_close_bus(int fd)
|
|
{
|
|
close(fd);
|
|
}
|
|
|
|
/* Read: write register address, then read back data :contentReference[oaicite:1]{index=1} */
|
|
BME68X_INTF_RET_TYPE bme68x_i2c_read(uint8_t reg_addr,
|
|
uint8_t *reg_data,
|
|
uint32_t len,
|
|
void *intf_ptr)
|
|
{
|
|
int fd = *(int *)intf_ptr;
|
|
if (write(fd, ®_addr, 1) != 1) {
|
|
return BME68X_E_COM_FAIL;
|
|
}
|
|
if (read(fd, reg_data, len) != (ssize_t)len) {
|
|
return BME68X_E_COM_FAIL;
|
|
}
|
|
return BME68X_OK;
|
|
}
|
|
|
|
/* Write: prepend register address to payload */
|
|
BME68X_INTF_RET_TYPE bme68x_i2c_write(uint8_t reg_addr,
|
|
const uint8_t *reg_data,
|
|
uint32_t len,
|
|
void *intf_ptr)
|
|
{
|
|
int fd = *(int *)intf_ptr;
|
|
uint8_t buf[len + 1];
|
|
buf[0] = reg_addr;
|
|
memcpy(&buf[1], reg_data, len);
|
|
if (write(fd, buf, len + 1) != (ssize_t)(len + 1)) {
|
|
return BME68X_E_COM_FAIL;
|
|
}
|
|
return BME68X_OK;
|
|
}
|
|
|
|
void bme68x_delay_us(uint32_t period, void *intf_ptr)
|
|
{
|
|
(void)intf_ptr;
|
|
usleep(period);
|
|
}
|