在实际项目中stm32作为从机只需要读取数据,故目前只实现读函数
GPIO操作函数
void SDA_H(int id)
void SDA_L(int id)
int SDA_READ(int id)
SCL_READ(int id)
IIC_SDA_OUTPUT(int id)
void IIC_SDA_INPUT(int id)
void IIC_SDA_INT_ENABLA(void)
用到的宏定义
#define RECEIVE_DATA 0x00
#define START_SIGNAL 0x01
#define STOP_SIGNAL 0x02
#define IDLE_SINGAL 0x03
#define INT_SINGAL 0x04
#define MASTER_WRITE 0x00
#define MASTER_READ 0x01
#define ADDR_NOMATH 0x02
#define SLAVE_ADDR 0xAC
起始信号通过SDA IO中断判断
int wait_iic_start(int id)
{
if (g_get_sda_int )
{
IIC_SDA_INPUT(id);
IIC_INT_DISABLE(id);
while (!SCL_READ(id));
while (SDA_READ(id));
iic_status.step = START_SIGNAL;
g_get_sda_int = 0;
}
}
void iic_slave_send_ack(int id)
{
while(SCL_READ(id));
IIC_SDA_OUTPUT(id);
SDA_L(id);
while(!SCL_READ(id));
while(SCL_READ(id));
SDA_H(id);
IIC_SDA_INPUT(id);
}
uint8_t iic_revc_addr(int id)
{
uint8_t cnt = 0;
uint8_t recvaddr = 0;
uint8_t iic_master_rw = 0;
wait_iic_start(id);
if (iic_status.step == START_SIGNAL)
{
for (cnt = 0; cnt < 8; cnt++)
{
while(SCL_READ(id));
while(!SCL_READ(id));
recvaddr<<=1;
if(SDA_READ(id))
{
recvaddr |=0x01;
}
}
iic_master_rw = MASTER_WRITE;
if (SLAVE_ADDR == recvaddr)
{
iic_slave_send_ack(id);
iic_status.step = RECEIVE_DATA;
g_step = 1;
}
else
{
g_step = 2;
while(SCL_READ(id));
while(!SCL_READ(id));
iic_status.step = IDLE_SINGAL;
IIC_SDA_INT_ENABLA();
return ADDR_NOMATH;
}
g_step = 3;
return iic_master_rw;
}
}
uint8_t iic_recv_data(int id)
{
uint8_t rw = 0;
uint8_t recvData = 0;
uint8_t bitcount = 0;
uint8_t r0,r1;
uint8_t data;
int len;
if (iic_status.step == IDLE_SINGAL)
rw = iic_revc_addr(ID1_IIC);
if (iic_status.step == RECEIVE_DATA)
{
g_step =4;
while(!recvData)
{
for (bitcount = 0;bitcount < 8;bitcount++)
{
while(SCL_READ(id));
while(!SCL_READ(id));
r0 = SDA_READ(id);
while(SCL_READ(id))
{
r1 = SDA_READ(id);
if (r0!=r1)
{
iic_status.step = STOP_SIGNAL;
IIC_SDA_INT_ENABLA();
recvData= 1;
return len;
}
}
data<<=1;
if(r0)
{
data |=1;
}
}
iic_slave_send_ack(id);
iic_status.iicrxbuf[iic_status.rxnum] = data;
iic_status.rxnum++;
}
}
}
|