27,373
社区成员
发帖
与我相关
我的任务
分享
Uint16 I2CA_WriteData(struct I2CMSG *msg)
{
Uint16 i;
// Wait until the STP bit is cleared from any previous master communication.
// Clearing of this bit by the module is delayed until after the SCD bit is
// set. If this bit is not checked prior to initiating a new message, the
// I2C could get confused.
if (I2caRegs.I2CMDR.bit.STP == 1)
{
return I2C_STP_NOT_READY_ERROR;
}
// Setup slave address
I2caRegs.I2CSAR = msg->SlaveAddress;
// Check if bus busy
if (I2caRegs.I2CSTR.bit.BB == 1)
{
return I2C_BUS_BUSY_ERROR;
}
// Setup number of bytes to send
// MsgBuffer + Address
I2caRegs.I2CCNT = msg->NumOfBytes+2;
// Setup data to send
I2caRegs.I2CDXR = msg->MemoryHighAddr;
I2caRegs.I2CDXR = msg->MemoryLowAddr;
// for (i=0; i<msg->NumOfBytes-2; i++)
for (i=0; i<msg->NumOfBytes2; i++)
{
I2caRegs.I2CDXR = *(msg->MsgBuffer+i);
}
// Send start as master transmitter
I2caRegs.I2CMDR.all = 0x6E20;
return I2C_SUCCESS;
}
//first clear the STP
I2caRegs.I2CMDR.bit.STP = 0;
wait_1us();
while(I2caRegs.I2CSTR.bit.BB == 1)
{
I2caRegs.I2CSTR.bit.BB = 0;
wait_1us();
}
// Check the outgoing message to see if it should be sent.
// In this example it is initialized to send with a stop bit.
if(I2cMsgOut1.MsgStatus == I2C_MSGSTAT_SEND_WITHSTOP)
{
Error = I2CA_WriteData(&I2cMsgOut1);
// If communication is correctly initiated, set msg status to busy
// and update CurrentMsgPtr for the interrupt service routine.
// Otherwise, do nothing and try again next loop. Once message is
// initiated, the I2C interrupts will handle the rest. Search for
// ICINTR1A_ISR in the i2c_eeprom_isr.c file.
if (Error == I2C_SUCCESS)
{
CurrentMsgPtr = &I2cMsgOut1;
I2cMsgOut1.MsgStatus = I2C_MSGSTAT_WRITE_BUSY;
}
} // end
I2caRegs.I2CMDR.bit.STP = 1;
while(I2caRegs.I2CSTR.bit.BB == 0)
{
I2caRegs.I2CSTR.bit.BB = 1;
wait_1us();
}
//I2c init
void I2CA_Init(void)
{
// Initialize I2C
// I2caRegs.I2CSAR = 0x0050; // Slave address - EEPROM control code
I2caRegs.I2CSAR = 0x0010; // Slave address - EEPROM control code for LTC2635
// I2CCLK = SYSCLK/(I2CPSC+1)
#if (CPU_FRQ_40MHZ||CPU_FRQ_50MHZ)
I2caRegs.I2CPSC.all = 4; // Prescaler - need 7-12 Mhz on module clk
#endif
#if (CPU_FRQ_60MHZ)
I2caRegs.I2CPSC.all = 6; // Prescaler - need 7-12 Mhz on module clk
#endif
I2caRegs.I2CCLKL = 10; // NOTE: must be non zero
I2caRegs.I2CCLKH = 5; // NOTE: must be non zero
// I2caRegs.I2CIER.all = 0x24; // Enable SCD & ARDY interrupts
I2caRegs.I2CIER.all = 0; // Disable SCD & ARDY interrupts
I2caRegs.I2CMDR.all = 0x0020; // Take I2C out of reset
// Stop I2C when suspended
I2caRegs.I2CFFTX.all = 0x6000; // Enable FIFO mode and TXFIFO
I2caRegs.I2CFFRX.all = 0x2040; // Enable RXFIFO, clear RXFFINT,
return;
}