24C02 is now basically the standard configuration of development boards, and it is indeed the best choice for applications that require power-down storage. At present, the single-chip microcomputer generally supports the power-off storage of data because of the internal integrated Flash memory. However, compared with the EEPROM such as 24C02, there are some problems that need to be paid attention to when using the internal Flash of the single-chip microcomputer:
a. Before writing data in Flash, an erase operation needs to be performed, and the erase operation is performed in units of sectors.
b. Flash read and write times are much less than EEPROM.
c. It is easy to misuse and erase the code inside the Flash.
d. Affects the response time of the interrupt.
24C02 has 256 bytes of data, which is generally enough. Its address can be configured through pins, so that multiple 24C02s can be connected to one I2C bus. as follows:
We ground A2, A1, A0, so the address is A0. Then the SCL and SDA pins are connected to PB8 and PB9 of the MCU. Need to pay attention to SCL, and SDA need to add pull-up resistors.
Next, we modify the code on an I2C routine to realize the read and write of 24C02. You can see the benefits of using library functions. Basically, you don’t need to read the STM32F030 manual, and you can quickly implement the functions we want to achieve. We use Keil to open the following project:
Step 1, Change the I2C address to be consistent with our hardware:
Step 2, configure according to the actual I2C module and pins used:
Step 3, change the address mode to 7BIT:
Step 4, operate EEPROM, we do not use HAL_I2C_Master_Transmit and HAL_I2C_Master_Receive in the example, these two functions are suitable for data transfer between two I2C devices. We use the following two functions here:
Here we use the Page Write command of 24C02 to write data, write 8 bytes of data each time, and then add 8 to the memory write address. It should be noted that after each write command is executed, there needs to be a delay, and the write can be continued after the EEPROM has processed the command internally. Check the manual for this delay. Different manufacturers may have different values. Data can be read out continuously without waiting.
Below is the waveform of write data, 0xA0 is the device address, 0x28 is the 24C02 internal memory address, followed by 8 bytes of data.
The waveform of the read data:
Deadlock problems are sometimes encountered when using hardware I2C operations. In this case, the SCL and SDA pins can be initialized as GPIO, such as PB8, PB9 in this example, and then continuously flip the SCL pin to send 9 clock pulses, which can reset the I2C from the deadlock state. Then re-initialize the I2C module to enter normal I2C operation.
Reviewing Editor: Liu Qing