2024-08-19 13:17:39 +00:00
|
|
|
/* Raspberry Pi i2c */
|
2023-11-22 11:48:03 +00:00
|
|
|
|
2023-09-17 20:31:02 +00:00
|
|
|
#include <stdio.h>
|
|
|
|
#include <fcntl.h>
|
|
|
|
#include <linux/i2c.h>
|
|
|
|
#include <linux/i2c-dev.h>
|
|
|
|
#include <stdint.h>
|
|
|
|
#include <sys/ioctl.h>
|
|
|
|
#include <unistd.h>
|
|
|
|
#include <stdlib.h>
|
|
|
|
|
2023-11-04 20:37:39 +00:00
|
|
|
#include "i2c.h"
|
|
|
|
|
2023-11-05 23:43:43 +00:00
|
|
|
#define I2C_DEVICE "/dev/i2c-1"
|
|
|
|
#define I2C_BME680_ADDRESS 0x77
|
2023-09-17 20:31:02 +00:00
|
|
|
|
2023-11-05 23:43:43 +00:00
|
|
|
static int fd;
|
|
|
|
|
|
|
|
int i2c_init(void) {
|
|
|
|
fd = open(I2C_DEVICE, O_RDWR);
|
2023-09-17 20:31:02 +00:00
|
|
|
if (fd < 0) {
|
2023-11-05 23:43:43 +00:00
|
|
|
fprintf(stderr, "could not open device: %s\n", I2C_DEVICE);
|
2024-08-19 13:17:39 +00:00
|
|
|
return 1;
|
2023-09-17 20:31:02 +00:00
|
|
|
}
|
|
|
|
|
2023-11-05 23:43:43 +00:00
|
|
|
if (ioctl(fd, I2C_SLAVE, I2C_BME680_ADDRESS) < 0) {
|
2023-09-17 20:31:02 +00:00
|
|
|
fprintf(stderr, "failed to acquire bus/talk to slave\n");
|
|
|
|
close(fd);
|
2024-08-19 13:17:39 +00:00
|
|
|
return 1;
|
2023-09-17 20:31:02 +00:00
|
|
|
}
|
|
|
|
|
2024-08-19 13:17:39 +00:00
|
|
|
return 0;
|
2023-09-17 20:31:02 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
2023-11-05 23:43:43 +00:00
|
|
|
int i2c_read(uint8_t reg, uint8_t *dst, uint32_t size) {
|
2024-08-19 13:17:39 +00:00
|
|
|
uint8_t cmd[2];
|
|
|
|
cmd[0] = reg;
|
|
|
|
cmd[1] = 0x00;
|
|
|
|
|
2023-09-17 20:31:02 +00:00
|
|
|
write(fd, cmd, 2);
|
2023-11-04 20:37:39 +00:00
|
|
|
|
|
|
|
if (read(fd, dst, size) != (ssize_t)size) {
|
2023-09-17 20:31:02 +00:00
|
|
|
fprintf(stderr, "error read()\n");
|
2024-08-19 13:17:39 +00:00
|
|
|
return 1;
|
2023-11-04 20:37:39 +00:00
|
|
|
|
2023-09-17 20:31:02 +00:00
|
|
|
}
|
2023-11-07 16:24:40 +00:00
|
|
|
|
2024-08-19 13:17:39 +00:00
|
|
|
return 0;
|
2023-09-17 20:31:02 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
2023-11-05 23:43:43 +00:00
|
|
|
int i2c_write(uint8_t reg, uint8_t value) {
|
2024-08-19 13:17:39 +00:00
|
|
|
uint8_t cmd[2];
|
|
|
|
cmd[0] = reg;
|
|
|
|
cmd[1] = value;
|
2023-11-04 20:37:39 +00:00
|
|
|
|
2023-09-17 20:31:02 +00:00
|
|
|
if (write(fd, cmd, 2) != 2) {
|
|
|
|
fprintf(stderr, "error write()\n");
|
2024-08-19 13:17:39 +00:00
|
|
|
return 1;
|
2023-09-17 20:31:02 +00:00
|
|
|
}
|
2023-11-04 20:37:39 +00:00
|
|
|
|
2024-08-19 13:17:39 +00:00
|
|
|
return 0;
|
2023-09-17 20:31:02 +00:00
|
|
|
}
|
|
|
|
|
2023-11-05 23:43:43 +00:00
|
|
|
int i2c_deinit(void) {
|
|
|
|
if (fd) {
|
|
|
|
close(fd);
|
|
|
|
}
|
|
|
|
|
2024-08-19 13:17:39 +00:00
|
|
|
return 0;
|
2023-11-05 23:43:43 +00:00
|
|
|
}
|
2023-11-07 16:24:40 +00:00
|
|
|
|