#include <i2c.h>
#include <hardware.h>
#define SDA (1 << 0)
#define SCL (1 << 1)
void
_delay_ms(u8 ms);
void
i2c_start_condition(void)
{
port_a_data &= ~SDA;
_delay_ms(1);
port_a_data &= ~SCL;
_delay_ms(1);
}
void
i2c_restart_condition(void)
{
port_a_data |= SDA;
_delay_ms(1);
port_a_data |= SCL;
_delay_ms(1);
i2c_start_condition();
}
void
i2c_stop_condition(void)
{
port_a_data |= SCL;
_delay_ms(1);
port_a_data |= SDA;
_delay_ms(1);
}
void
i2c_send(u8 b)
{
u8 i;
for (i = 0; i < 8; ++i) {
if (b & 1)
port_a_data |= SDA;
else
port_a_data &= ~SDA;
port_a_data |= SCL;
_delay_ms(1);
port_a_data &= ~SCL;
_delay_ms(1);
b >>= 1;
}
port_a_ctrl = PIO_MODE_3;
port_a_ctrl = 0x7D;
// Read ack
port_a_data |= SCL;
_delay_ms(1);
port_a_data &= ~SCL;
_delay_ms(1);
port_a_ctrl = PIO_MODE_3;
port_a_ctrl = 0x7C;
}
u8
i2c_recv(u8 ack)
{
u8 i;
u8 b = 0;
port_a_ctrl = PIO_MODE_3;
port_a_ctrl = 0x7D;
for (i = 0; i < 8; ++i) {
port_a_data |= SCL;
_delay_ms(1);
if (port_a_data & 1)
b |= 1;
port_a_data &= ~SCL;
_delay_ms(1);
b <<= 1;
}
port_a_ctrl = PIO_MODE_3;
port_a_ctrl = 0x7C;
if (ack)
port_a_data |= SDA;
else
port_a_data &= ~SDA;
port_a_data |= SCL;
_delay_ms(1);
port_a_data &= ~SCL;
_delay_ms(1);
return b;
}