int I2C_Master_Receiver(void) {
uint32_t timeout;
int error = 0;
// 1. 发送起始条件 + 从机地址(读模式)
I2C_TargetAddressConfig(HTCFG_I2C_MASTER_PORT, I2C_SLAVE_ADDRESS, I2C_MASTER_READ);
// 2. 等待起始条件完成
timeout = 10000;
while (!I2C_CheckStatus(HTCFG_I2C_MASTER_PORT, I2C_MASTER_SEND_START) && timeout--);
if (timeout == 0) return ERROR_START_TIMEOUT;
// 3. 等待地址发送完成
timeout = 10000;
while (!I2C_CheckStatus(HTCFG_I2C_MASTER_PORT, I2C_MASTER_RECEIVER_MODE) && timeout--);
if (timeout == 0) return ERROR_ADDR_TIMEOUT;
// 4. 启用ACK
I2C_AckCmd(HTCFG_I2C_MASTER_PORT, ENABLE);
// 5. 接收数据
for (aaa = 0; aaa < BufferSize; aaa++) {
// 等待数据就绪
timeout = 10000;
while (!I2C_CheckStatus(HTCFG_I2C_MASTER_PORT, I2C_MASTER_RX_NOT_EMPTY) && timeout--);
if (timeout == 0) {
error = ERROR_RX_TIMEOUT;
break;
}
// 读取数据
s_receivedData = I2C_ReceiveData(HTCFG_I2C_MASTER_PORT);
I2C_Master_Buffer_Rx[aaa] = s_receivedData;
// 转发到USART0
rxd_scomm0.buffer[rxd_scomm0.write_pt] = s_receivedData;
rxd_scomm0.write_pt = (rxd_scomm0.write_pt + 1) % USART0_BUF_SIZE;
rxd_scomm0.cnt++;
USART_SendData(HT_USART0, s_receivedData);
// 倒数第二个字节发送NACK
if (aaa == BufferSize - 2) {
I2C_AckCmd(HTCFG_I2C_MASTER_PORT, DISABLE);
}
}
// 6. 发送停止条件
I2C_GenerateSTOP(HTCFG_I2C_MASTER_PORT);
// 7. 等待总线释放
timeout = 10000;
while (I2C_ReadRegister(HTCFG_I2C_MASTER_PORT, I2C_REGISTER_SR) & 0x80000 && timeout--);
if (timeout == 0) error = ERROR_BUS_BUSY;
// 重置变量
aaaa = 0;
aaa = 0;
return error;
} |