各位,新年好!祝大家新年工作愉快!
谁能给我个硬件I2C操作AT24C02的程序?
我老是卡住,有时通有时不通,谁能帮帮忙啊,郁闷了很久!
下面是我的程序,哪位有空帮看下:
void I2CInit(unsigned char SA)
{ P3SEL |= 0x06; // Assign I2C pins to USCI_B0 UCB0CTL1 |= UCSWRST; // Enable SW reset UCB0CTL0 = UCMST + UCMODE_3 + UCSYNC; // I2C Master, synchronous mode UCB0CTL1 = UCSSEL_2 + UCSWRST; // Use SMCLK, keep SW reset UCB0BR0 = 80; // fSCL = SMCLK/80 = ~100kHz UCB0BR1 = 0; UCB0I2CSA = SA; // Slave Address is 2ch UCB0CTL1 &= ~UCSWRST; // Clear SW reset, resume operation
}
uint16 NVMRead(uint16 addr)
{ unsigned char data; I2CInit(0x50); while (UCB0CTL1 & UCTXSTP); // Ensure stop condition got sent UCB0CTL1 |= UCTR + UCTXSTT; // I2C TX, start condition while((IFG2 & UCB0TXIFG)==0); UCB0TXBUF = (unsigned char) (addr&0x00ff);////eeprom low addr while((IFG2 & UCB0TXIFG)==0); //老是卡在这个位置,而且断电重来都不行.但是有时候通,只要不通了断电也没用。 IFG2 &= ~UCB0TXIFG;
UCB0CTL1 &= ~UCTR; // I2C RX, while (UCB0CTL1 & UCTXSTP); // 判断总线是否被释放 UCB0CTL1 |= UCTXSTT; // Start condition while((UCB0CTL1&UCTXSTT)==1); while((IFG2&UCB0RXIFG)==0); data = UCB0RXBUF; delay100us(); UCB0CTL1 |= UCTXSTP + UCTXNACK; while((UCB0CTL1 & UCTXSTP)==1); return data;
}
uint8 NVMWrite(uint16 addr, uint8 data)
{ I2CInit(0x50); while (UCB0CTL1 & UCTXSTP); // Ensure stop condition got sent UCB0CTL1 |= UCTR + UCTXSTT; // I2C TX, start condition while((IFG2 & UCB0TXIFG)==0); UCB0TXBUF = (unsigned char) (addr&0x00ff); while((IFG2 & UCB0TXIFG)==0); UCB0TXBUF = data; while((IFG2 & UCB0TXIFG)==0); UCB0CTL1 |= UCTXSTP + UCTXNACK; // I2C stop condition while((UCB0CTL1 & UCTXSTP)==1); delayms(10); return 1;
}
void main(void)
{ WDTCTL = WDTPW + WDTHOLD; // Stop WDT BCSCTL1=CALBC1_16MHZ; DCOCTL=CALDCO_16MHZ; //DCOCLK设置16M BCSCTL2 = DIVM0 | DIVS0; //16M DCOCLK经2分频得到8M MCLK和8M SMCLK NVMRead(0);
} |