1
0
Fork 0
mirror of https://github.com/RobotechLille/cdf2018-principal synced 2024-05-17 04:26:00 +02:00
cdf2018-principal/chef/src/i2c.c

78 lines
1.5 KiB
C
Raw Normal View History

2018-04-29 21:57:29 +02:00
#include <pthread.h>
2018-05-11 15:58:18 +02:00
#include <stdbool.h>
2018-04-29 21:57:29 +02:00
#include <stdio.h>
#include <stdlib.h>
2018-05-11 05:34:06 +02:00
#include <unistd.h>
2018-04-29 21:57:29 +02:00
#include <wiringPiI2C.h>
#include "i2c.h"
pthread_mutex_t sI2C;
2018-05-11 05:34:06 +02:00
bool i2cInited = false;
2018-04-29 21:57:29 +02:00
void initI2C()
{
2018-05-11 05:34:06 +02:00
if (!i2cInited) {
pthread_mutex_init(&sI2C, NULL);
i2cInited = true;
}
2018-04-29 21:57:29 +02:00
}
2018-05-11 05:34:06 +02:00
int openI2C(uint8_t address)
2018-04-29 21:57:29 +02:00
{
lockI2C();
int fd = wiringPiI2CSetup(address);
unlockI2C();
if (fd < 0) {
perror("wiringPiI2CSetup");
exit(EXIT_FAILURE);
}
return fd;
}
2018-05-11 05:34:06 +02:00
uint8_t readI2C(int fd, uint8_t reg)
2018-04-29 21:57:29 +02:00
{
lockI2C();
2018-05-11 15:58:18 +02:00
int res;
int delay = 1;
static char errBuffer[1024];
for (int i = 0; i < I2C_DRIVEN_HIGH_RETRIES; i++) {
while ((res = wiringPiI2CReadReg8(fd, reg)) < 0) {
snprintf(errBuffer, 1024, "wiringPiI2CReadReg8 @%3d %2x %9d", fd, reg, delay);
perror(errBuffer);
usleep(delay);
delay *= 2;
}
if (res != 0xFF) {
break;
}
}
2018-04-29 21:57:29 +02:00
unlockI2C();
return res;
}
2018-05-11 05:34:06 +02:00
void writeI2C(int fd, uint8_t reg, uint8_t data)
2018-04-29 21:57:29 +02:00
{
lockI2C();
2018-05-11 05:34:06 +02:00
int delay = 1;
2018-05-11 15:58:18 +02:00
static char errBuffer[1024];
2018-05-11 05:34:06 +02:00
while (wiringPiI2CWriteReg8(fd, reg, data) < 0) {
2018-05-11 15:58:18 +02:00
snprintf(errBuffer, 1024, "wiringPiI2CWriteReg8 @%3d %2x←%2x %9d", fd, reg, data, delay);
perror(errBuffer);
2018-05-11 05:34:06 +02:00
usleep(delay);
delay *= 2;
2018-04-29 21:57:29 +02:00
}
2018-05-11 05:34:06 +02:00
unlockI2C();
2018-04-29 21:57:29 +02:00
}
void lockI2C()
{
pthread_mutex_lock(&sI2C);
}
void unlockI2C()
{
pthread_mutex_unlock(&sI2C);
}