lis3dh/i2c.c

79 lines
1.1 KiB
C
Raw Normal View History

2023-12-21 20:52:17 +00:00
/*
Example I2C use on linux/raspberry pi
*/
#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>
#include "i2c.h"
#define I2C_DEVICE "/dev/i2c-1"
#define I2C_LIS3DH_ADDRESS 0x18
static int fd;
int i2c_init(void) {
fd = open(I2C_DEVICE, O_RDWR);
if (fd < 0) {
fprintf(stderr, "could not open device: %s\n", I2C_DEVICE);
2023-12-21 23:29:22 +00:00
return 1;
2023-12-21 20:52:17 +00:00
}
if (ioctl(fd, I2C_SLAVE, I2C_LIS3DH_ADDRESS) < 0) {
fprintf(stderr, "failed to acquire bus/talk to slave\n");
close(fd);
2023-12-21 23:29:22 +00:00
return 1;
2023-12-21 20:52:17 +00:00
}
2023-12-21 23:29:22 +00:00
return 0;
2023-12-21 20:52:17 +00:00
}
int i2c_read(uint8_t reg, uint8_t *dst, uint32_t size) {
2023-12-23 15:37:33 +00:00
uint8_t cmd[2];
cmd[0] = reg;
cmd[1] = 0x00;
2023-12-21 20:52:17 +00:00
write(fd, cmd, 2);
if (read(fd, dst, size) != (ssize_t)size) {
fprintf(stderr, "error read()\n");
2023-12-21 23:29:22 +00:00
return 1;
2023-12-21 20:52:17 +00:00
}
2023-12-21 23:29:22 +00:00
return 0;
2023-12-21 20:52:17 +00:00
}
int i2c_write(uint8_t reg, uint8_t value) {
2023-12-23 15:37:33 +00:00
uint8_t cmd[2];
cmd[0] = reg;
cmd[1] = value;
2023-12-21 20:52:17 +00:00
if (write(fd, cmd, 2) != 2) {
fprintf(stderr, "error write()\n");
2023-12-21 23:29:22 +00:00
return 1;
2023-12-21 20:52:17 +00:00
}
2023-12-21 23:29:22 +00:00
return 0;
2023-12-21 20:52:17 +00:00
}
int i2c_deinit(void) {
if (fd) {
close(fd);
}
2023-12-21 23:29:22 +00:00
return 0;
2023-12-21 20:52:17 +00:00
}