您好!
我从事 MSP430FR2673工作、我想使用 I2C 从外部 EEPROM 24LC64检测数据并读取数据。 我编写了一个代码、但它不起作用。 我不知道为什么? 请重播。
谢谢!
阿图利亚
#include <msp430.h>
#define EEPROM_ADDRESS 0xA0 // EEPROM I2C address
#define EEPROM_SIZE 256 // EEPROM size in bytes
void initI2C() {
WDTCTL = WDTPW | WDTHOLD;
// Configure GPIO
P1OUT &= ~BIT0; // Clear P1.0 output latch
P1DIR |= BIT0; // For LED
P3SEL0 |= BIT2 | BIT6; // I2C pins
// Disable the GPIO power-on default high-impedance mode to activate
// previously configured port settings
PM5CTL0 &= ~LOCKLPM5;
// Configure USCI_B0 for I2C mode
UCB1CTLW0 |= UCSWRST; // Software reset enabled
UCB1CTLW0 |= UCMODE_3 | UCMST | UCSYNC; // I2C mode, Master mode, sync
UCB1CTLW1 |= UCASTP_2; // Automatic stop generated
// after UCB0TBCNT is reached
UCB1BRW = 0x78; // baudrate = SMCLK / 8
UCB1TBCNT = 0x0002; // number of bytes to be received
UCB1I2CSA = 0x00A0; // Slave address
UCB1CTL1 &= ~UCSWRST;
UCB1IE |= UCRXIE | UCNACKIE | UCBCNTIE;
}
void writeByteToEEPROM(unsigned char data, unsigned int address) {
while (UCB1STATW & UCBBUSY); // Wait for I2C bus to be idle
// Set EEPROM write address
UCB1I2CSA = EEPROM_ADDRESS;
// Set write mode
UCB1CTLW0 |= UCTR;
// Set memory address to write to
UCB1CTLW0 |= UCTXSTT; // Send start condition
while (!(UCB1IFG & UCTXIFG1)); // Wait for start condition to be sent
// Send memory address (MSB then LSB)
UCB1TXBUF = (address >> 8) & 0xFF; // MSB
while (!(UCB1IFG & UCTXIFG1)); // Wait for address to be sent
UCB1TXBUF = address & 0xFF; // LSB
while (!(UCB1IFG & UCTXIFG1)); // Wait for address to be sent
// Send data byte
UCB1TXBUF = data;
while (!(UCB1IFG & UCTXIFG1)); // Wait for data to be sent
// Send stop condition
UCB1CTLW0 |= UCTXSTP;
}
unsigned char readByteFromEEPROM(unsigned int address) {
unsigned char data;
while (UCB1STATW & UCBBUSY); // Wait for I2C bus to be idle
// Set EEPROM write address
UCB1I2CSA = EEPROM_ADDRESS;
// Set write mode
UCB1CTLW0 |= UCTR;
// Set memory address to read from
UCB1CTLW0 |= UCTXSTT; // Send start condition
while (!(UCB1IFG & UCTXIFG1)); // Wait for start condition to be sent
// Send memory address (MSB then LSB)
UCB1TXBUF = (address >> 8) & 0xFF; // MSB
while (!(UCB1IFG & UCTXIFG1)); // Wait for address to be sent
UCB1TXBUF = address & 0xFF; // LSB
while (!(UCB1IFG & UCTXIFG1)); // Wait for address to be sent
// Set read mode
UCB1CTLW0 &= ~UCTR;
// Send repeated start condition
UCB1CTLW0 |= UCTXSTT;
while (UCB1CTLW0 & UCTXSTT); // Wait for repeated start to be sent
// Receive data byte
data = UCB1RXBUF;
// Send stop condition
UCB1CTLW0 |= UCTXSTP;
return data;
}
int main(void) {
WDTCTL = WDTPW | WDTHOLD; // Stop watchdog timer
initI2C();
// Example usage: Write data to EEPROM
unsigned int address = 0;
unsigned char data_to_write = 0x55;
writeByteToEEPROM(data_to_write, address);
// Example usage: Read data from EEPROM
unsigned char data_read = readByteFromEEPROM(address);
while (1) {
// Do something with the data
}
return 0;
}