Follow+Star Public Number, Don’t Miss Wonderful Content
Author | strongerHuang
WeChat Public Account | strongerHuang
1Basic Principles of I²C Read/Write EEPROM
Most EEPROMs on the market that use I2C communication have similar control timing and read/write processes.
You can refer to the articles I shared:
2EEPROM Low-Level Driver
Those who have actually worked on projects know that a good low-level driver can greatly facilitate upper-level application development, saves development time, and reduces the occurrence of bugs.
However, most beginners or recent graduates engaged in related development rarely consider issues like portability, reusability, or fault tolerance.
Below, I will briefly list a few common operations for EEPROM that I use in projects.
1. Write, Read, and Verify Successful Write
This method is easy to understand: after writing, read the data again and match it one by one to verify if it is consistent with the written data.
Generally, I will repeat the operation 3 times, meaning: write, read, if it fails more than 3 times, I will give up writing, considering it a write failure or chip anomaly.
This method can simply solve the issue of write failure due to anomalies.
2. Add Check Information
Based on the above read verification, for some parameters I generally also: add similar “and check” or “CRC check” at the end of the parameters.
If you continuously store a 10-byte parameter (data structure) and if one byte is modified due to an anomaly, reading it for verification will reveal the discrepancy, thus deeming the parameter invalid.
The purpose of adding this check is clear from my example above, which is to resolve the issue of a byte being maliciously modified within a multi-byte parameter, rendering that parameter invalid.
3. Add Mutex Lock for EEPROM in Multitasking
Friends who have used operating systems know that when multiple threads access a resource, there is generally a mutual exclusion relationship. In simple terms: a resource can only be operated on by one thread at a time.
For example, if Thread A is writing 10 bytes of data to EEPROM and has completed 6 bytes, while Thread B attempts to preempt and write data to EEPROM, should Thread A relinquish the I2C bus for Thread B to write?
The answer is definitely no, hence the concept of a mutex lock. This means that the thread occupying the I2C bus must complete its operation before releasing the bus for other threads to operate.
These three points are what I commonly use. There are other related fault tolerance mechanisms available online; if interested, feel free to search.
I won’t post the code here, as the code varies due to different chip models and applications. However, our goal is to consider code portability, reusability, and fault tolerance while ensuring it meets application needs.
3Hardware or Software for I²C?
Should we use hardware I2C in our code? Or software simulated I2C?
Click “Read Original” to see more shares.