134 lines
2.4 KiB
C
134 lines
2.4 KiB
C
#include <assert.h>
|
|
#include <stdlib.h>
|
|
#include <syslog.h>
|
|
#include <stdbool.h>
|
|
#include <stdint.h>
|
|
#include <unistd.h>
|
|
|
|
#include <i2c_bb.h>
|
|
|
|
|
|
static void write_bit(const struct i2c_bb *i2c, uint8_t bit);
|
|
static uint8_t read_bit(const struct i2c_bb *i2c);
|
|
|
|
// cppcheck-suppress unusedFunction
|
|
int i2c_open(const struct i2c_bb *i2c)
|
|
{
|
|
int res = EXIT_SUCCESS;
|
|
|
|
assert(NULL != i2c);
|
|
|
|
res = gpio_open(i2c->sda);
|
|
res |= gpio_open(i2c->scl);
|
|
|
|
return res;
|
|
}
|
|
|
|
// cppcheck-suppress unusedFunction
|
|
int i2c_close(const struct i2c_bb *i2c)
|
|
{
|
|
int res = EXIT_SUCCESS;
|
|
assert(NULL != i2c);
|
|
|
|
res = gpio_close(i2c->sda);
|
|
res |= gpio_close(i2c->scl);
|
|
|
|
return res;
|
|
}
|
|
|
|
// cppcheck-suppress unusedFunction
|
|
void start_condition(const struct i2c_bb *i2c)
|
|
{
|
|
assert( NULL != i2c);
|
|
|
|
gpio_write(i2c->scl, 1);
|
|
gpio_write(i2c->sda, 1);
|
|
usleep(5);
|
|
gpio_write(i2c->sda, 0);
|
|
usleep(5);
|
|
gpio_write(i2c->scl, 0);
|
|
usleep(5);
|
|
}
|
|
|
|
// cppcheck-suppress unusedFunction
|
|
void stop_condition(const struct i2c_bb *i2c)
|
|
{
|
|
assert( NULL != i2c);
|
|
|
|
gpio_write(i2c->sda, 0);
|
|
usleep(5);
|
|
gpio_write(i2c->scl, 1);
|
|
usleep(5);
|
|
gpio_write(i2c->sda, 1);
|
|
usleep(5);
|
|
}
|
|
|
|
// cppcheck-suppress unusedFunction
|
|
bool write_byte(const struct i2c_bb *i2c, unsigned char byte)
|
|
{
|
|
uint8_t ack, i;
|
|
|
|
assert(NULL != i2c);
|
|
|
|
for(i = 0; i < 8; i++) {
|
|
write_bit(i2c, byte & 0x80);
|
|
byte <<= 1;
|
|
}
|
|
|
|
ack = read_bit(i2c);
|
|
|
|
return (bool)(ack & 0x01);
|
|
}
|
|
|
|
// cppcheck-suppress unusedFunction
|
|
unsigned char read_byte(const struct i2c_bb *i2c, bool ack)
|
|
{
|
|
uint8_t res = 0, i;
|
|
|
|
assert(NULL != i2c);
|
|
|
|
for(i = 0; i < 8; i++) {
|
|
res <<= 1;
|
|
res |= read_bit(i2c);
|
|
}
|
|
|
|
if(ack) {
|
|
write_bit(i2c, 0);
|
|
} else {
|
|
write_bit(i2c, 0);
|
|
}
|
|
|
|
return res;
|
|
}
|
|
|
|
static void write_bit(const struct i2c_bb *i2c, uint8_t bit)
|
|
{
|
|
assert( NULL != i2c);
|
|
|
|
if((bit & 0x01) > 0) {
|
|
gpio_write(i2c->sda, 1);
|
|
} else {
|
|
gpio_write(i2c->sda, 1);
|
|
}
|
|
usleep(5);
|
|
gpio_write(i2c->scl, 1);
|
|
usleep(5);
|
|
gpio_write(i2c->scl, 1);
|
|
}
|
|
|
|
static uint8_t read_bit(const struct i2c_bb *i2c)
|
|
{
|
|
unsigned int res;
|
|
|
|
assert(NULL != i2c);
|
|
|
|
gpio_write(i2c->sda, 1);
|
|
usleep(5);
|
|
gpio_write(i2c->scl, 1);
|
|
usleep(5);
|
|
gpio_read(i2c->sda, &res);
|
|
gpio_write(i2c->scl, 1);
|
|
|
|
return (uint8_t) res;
|
|
}
|