while (UCB0STAT & UCBUSY); // wait until I2C module has finished all operations.
I2CWriteInit();
_DINT();
UCB0CTL1 |= UCTXSTT;
__bis_SR_register(CPUOFF + GIE); // Waiting for Sending.
UCB0CTL1 |= UCTXSTP; // I2C stop condition
while (UCB0CTL1 & UCTXSTP); // Ensure stop condition got sent
}
uchar I2C_Read(uchar address)
{
while (UCB0STAT & UCBUSY); // wait until I2C module has finished all operations
//Change to Write Mode.
I2CSendBuffer[0] = address;
I2CSendPtr = 0;
I2CWriteInit();
_DINT();
UCB0CTL1 |= UCTXSTT; // start condition generation
// => I2C communication is started
__bis_SR_register(CPUOFF + GIE); // Enter LPM0 w/ interrupts
//Change to Read Mode.
I2CReadInit();
UCB0CTL1 |= UCTXSTT; // I2C start condition
while (UCB0CTL1 & UCTXSTT); // Start condition sent?
UCB0CTL1 |= UCTXSTP; // I2C stop condition
__bis_SR_register(LPM0_bits + GIE); // Enter LPM0 w/ interrupts
while (UCB0CTL1 & UCTXSTP); // Ensure stop condition got sent
return I2CRecvBuffer;
}
/*----------------------------------------------------------------------------*/
// Description:
// Acknowledge Polling. The EEPROM will not acknowledge if a write cycle is
// in progress. It can be used to determine when a write cycle is completed.
/*----------------------------------------------------------------------------*/
void I2C_AckPolling(void)
{
while (UCB0STAT & UCBUSY); // wait until I2C module has
// finished all operations
do
{
UCB0STAT = 0x00; // clear I2C interrupt flags
UCB0CTL1 |= UCTR; // I2CTRX=1 => Transmit Mode (R/W bit = 0)
UCB0CTL1 &= ~UCTXSTT;
UCB0CTL1 |= UCTXSTT; // start condition is generated
while (UCB0CTL1 & UCTXSTT)
{
if (!(UCNACKIFG & UCB0STAT))
{
break;
}
}
UCB0CTL1 |= UCTXSTP; // stop condition is generated after
// slave address was sent => I2C communication is started
while (UCB0CTL1 & UCTXSTP); // wait till stop bit is reset
__delay_cycles(500); // Software delay
}
while (UCNACKIFG & UCB0STAT);
}
// USCI_B0 Data ISR
// Notice : UCSIAB0RX_ISR should be handle with UCSIAB0TX_ISR
#pragma vector = USCIAB0TX_VECTOR
__interrupt void USCIAB0TX_ISR(void)
{
if (UCB0TXIFG & IFG2) // TX
{
UCB0TXBUF = I2CSendBuffer[I2CSendPtr]; // Load TX buffer
I2CSendPtr--; // Decrement TX byte counter
if (I2CSendPtr < 0)
{
while (!(IFG2 & UCB0TXIFG)); // wait for tx complete
IE2 &= ~UCB0TXIE; // disable interrupts.
IFG2 &= ~UCB0TXIFG; // Clear USCI_B0 TX int flag
__bic_SR_register_on_exit(LPM0_bits); // Exit LPM0
}
}
else if (UCB0RXIFG & IFG2) // RX
{
I2CRecvBuffer = UCB0RXBUF; // store received data in buffer
__bic_SR_register_on_exit(LPM0_bits); // Exit LPM0
}
}