banner



How To Read/write Eeprom Using I2c Linux

Introduction


EEPROM, or Eastwardlectrically Erasable Programmable Read-Only Grandemory, is a type of device that allows yous to shop small chunks of data and retrieve it later fifty-fifty if the device has been power cycled. A lot of modern microcontrollers – such as the ATmega328 – contain some congenital-in EEPROM, merely that doesn't mean that you can't add together more! Serial EEPROM devices like the Microchip 24-series EEPROM permit you lot to add more retention to any device that can speak I²C. Today nosotros're going to learn how to read and write serial EEPROM devices using Arduino.

Library Now Available: We've created an External EEPROM Library for Arduino that makes reading and writing an EEPROM easy. This tutorial is still very good knowledge and background to take. Please read then consider using the library.

Required Materials

To follow along with this tutorial, you lot will need the following materials. You may not need everything though depending on what you accept. Add it to your cart, read through the guide, and adapt the cart as necessary.

Suggested Reading

Before continuing with this guide, we recommend you be somewhat familiar with the concepts in the following tutorials:

How to Use a Breadboard

Welcome to the wonderful world of breadboards. Here we will learn what a breadboard is and how to use one to build your very kickoff circuit.

What is an Arduino?

What is this 'Arduino' thing anyway? This tutorials dives into what an Arduino is and forth with Arduino projects and widgets.

Integrated Circuits

An introduction to integrated circuits (ICs). Electronics' ubiquitous black chips. Includes a focus on the diversity of IC packages.

I2C

An introduction to I2C, one of the main embedded communications protocols in use today.

EEPROM Basics

Before we get into the hookup it's probably a good idea to familiarize ourselves with EEPROM and the history of ROM in general. That said, if yous don't nerd-out on calculator history it's probably rubber to skip that section.

What is ROM?

Read-Only Retentivity (ROM) is a type of figurer memory which, more often than not speaking, is merely programmed one time (or very occasionally) and then gets read from the residue of the fourth dimension. This is because it'due south very slow — or impossible — to write new data to ROM. The trade-off for very tedious write times — traditionally — is that it's also non-volatile pregnant that the data doesn't get away when ability is removed from the device. This makes information technology platonic for things like firmware which need to be "remembered" by the computer, but never really alter. The BIOS in your PC is stored on a form of ROM.

A Brief History of ROM

Early on "Stored-Program" type computers — such every bit desk calculators and keyboard interpreters — began using ROM in the form of Diode Matrix ROM. This was memory made upward of discrete semiconductor diodes placed on a particularly organized PCB. This gave mode to Mask ROM with the advent of integrated circuits. Mask ROM was a lot like Diode Matrix ROM only information technology was implemented on a much smaller scale. This meant, however, that you couldn't just move a couple of diodes around with a soldering iron and reprogram it. Mask ROM had to be programmed by the manufacturer and was thereafter not alterable.

Unfortunately, Mask ROM was expensive and took a long time to produce because each new programme required a brand new device to be manufactured past a foundry. In 1956, however, this problem was solved with the invention of PROM (Programmable ROM) which allowed developers to programme the chips themselves. That meant manufacturers could produce millions of the aforementioned unprogrammed device which made it cheaper and more than practical. PROM, still, could only be written to one time using a high-voltage programming device. Subsequently a PROM device was programmed, in that location was no mode to return the device to its unprogrammed state.

UV Erasable Microcontroller

A UV Erasable Microcontroller. The window gives it away.

This changed in 1971 with the invention of EPROM (Erasable Programmable ROM) which — likewise calculation another letter to the acronym — brought with information technology the ability to erase the device and return information technology to a "blank" state using a strong UV calorie-free source. That's right, yous had to shine a bright calorie-free on the IC to reprogram it, how cool is that? Well, information technology turns out it's pretty absurd unless you're a developer working on firmware in which case you'd really similar to be able to reprogram the device using electric signals. This finally became a reality in 1983 with the development of EEPROM (Electrically Erasable Programmable ROM) and with that, we arrive at the electric current day unwieldy acronym.

Quirks of EEPROM

At that place are ii major drawbacks to EEPROM as a method of information storage. In most applications the pros outweigh the cons, simply you should be aware of them earlier incorporating EEPROM into your next design.

First of all, the technology that makes EEPROM piece of work likewise limits the number of times that it tin can exist re-written. This has to do with electrons becoming trapped in the transistors that make up the ROM and building up until the charge difference between a "1" and a "0" is unrecognizable. But don't worry, most EEPROMs take a maximum re-write number of 1 million or more than. Equally long as you're not continuously writing to the EERPROM information technology's unlikely y'all'll hit this maximum.

Secondly, EEPROM volition not be erased if you lot remove power from it, but it won't hold onto your data indefinitely. Electrons can migrate out of the transistors and through the insulator, effectively erasing the EEPROM over time. That said, this usually occurs over the class of years (although information technology can exist accelerated past heat). Near manufacturers say that your data is safe on EEPROM for 10 years or more than at room temperature.

And at that place'southward one more thing you should keep in heed when selecting an EEPROM device for your project. EEPROM capacity is measured in bits and not bytes. A 256K EEPROM will hold 256Kbits of data, in other words, but 32KB.

Arduino Hardware Hookup

Okay, now that nosotros know what EEPROM is, let's hook one up and run across what it can do! In guild to go our device talking we'll need to connect power equally well equally I²C series lines. This device in particular runs at 5VDC so nosotros'll connect information technology to the 5V output of our Arduino UNO. Also, the I²C lines volition need pullup resistors for communication to happen correctly. The value of these resistors depends on the capacitance of the lines and frequency you want to communicate at, but a skilful dominion of pollex for non-critical applications is just keep it in the kΩ range. In this case, we'll use four.7kΩ pullup resistors.

At that place are 3 pins on this device to select the I²C accost, this fashion you can have more than one EEPROM on the passenger vehicle and accost them each differently. Y'all could only ground them all, but we'll be wiring them and then that nosotros tin drop in a higher-capacity device later in the tutorial.

We'll use a breadboard to connect everything together. The diagram beneath shows the correct hookup for most I²C EEPROM devices, including the Microchip 24-serial EEPROM that we sell.

drawing showing the correct way to wire an I2C EEPROM device to an Arduino UNO

That's it! Like most I²C devices, the hardware hookup is a cakewalk. Now nosotros can move on to the code.

Reading and Writing

Virtually of the fourth dimension when you're using an EEPROM in conjunction with a microcontroller you won't really demand to meet all of the contents of the memory at once. You'll merely read and write bytes here and there equally needed. In this example, however, we're going to write an entire file to EEPROM and then read all of it dorsum off so we tin can view it on our computer. This should get us comfy with the idea of using EEPROM and besides give u.s. a feeling for how much information can really fit on a minor device.

To send and receive files using the case Arduino sketches beneath, you'll demand a final program such equally TeraTerm. Once you have that downloaded and installed, we can get down to business organization.

Heads upward! If your EEPROM is larger than 512k (For Instance: If information technology's marked '24LC1025') you lot may want to skip directly to the section on college capacity EEPROMs.

Write Something

Our example sketch will only have any byte that comes in over the serial port and write it to the EEPROM, keeping runway along the way of how many bytes we've written to memory.

Writing a byte of memory to the EEPROM generally happens in iii steps:

  1. Send the Most Significant Byte of the retentiveness address that you desire to write to.
  2. Send the Least Meaning Byte of the memory address that you want to write to.
  3. Send the data byte that y'all would similar to store at this location.

At that place are probably a few key words in that location that bare explaining:

Retention Addresses

If you lot imagine all of the bytes in a 256 Kbit EEPROM standing in a line from 0 to 32000 — because at that place are viii $.25 to a byte and therefore yous tin can fit 32000 bytes on a 256 Kbit EEPROM — then a memory accost is the place in line where you would discover a item byte. We need to send that accost to the EEPROM so it knows where to put the byte that nosotros're sending.

Most Significant and Least Meaning Bytes

Because in that location are 32000 possible places in a 256 Kbit EEPROM — and because 255 is the largest number you can encode in 1 byte — we need to send this address in two bytes. First we send the Most Meaning Byte (MSB) — the first eight bits in this case. And so we send the Least Pregnant Byte (LSB) — the 2nd 8 bits. Why? Because this is how the device expects to receive them, that'southward all.

Page Writing

Writing 1 byte at a fourth dimension is fine, but well-nigh EEPROM devices have something called a "folio write buffer" which allows you to write multiple bytes at a time the same manner y'all would a unmarried byte. We'll exist taking advantage of this in our example sketch.

The EEPROM uses an internal counter that automatically increases the retention location with each post-obit data byte it receives. Once a memory accost has been sent nosotros can follow it with up to 64 bytes of information. The EEPROM assumes (rightly) that an address of 312 followed by 10 bytes will record byte 0 at address 312, byte 1 at address 313, byte 2 at address 314, and so on.

Arduino Sketch Example Write Something

Notation: This example assumes you are using the latest version of the Arduino IDE on your desktop. If this is your first fourth dimension using Arduino, please review our tutorial on installing the Arduino IDE.

Here'south an example sketch to write some data to the EEPROM. Walk through the comments in the code for an explanation well-nigh what's going on.

          language:c //Include the Wire I2C Library #include <Wire.h>  /*This address is determined by the fashion your address pins are wired. In the diagram from before, we continued A0 and A1 to Ground and  A2 to 5V. To become the address, nosotros start with the control code from  the datasheet (1010) and add the logic land for each address pin in the lodge A2, A1, A0 (100) which gives usa 0b1010100, or in  Hexadecimal, 0x54*/  #define EEPROM_ADR 0x54  /*Theoretically, the 24LC256 has a 64-byte page write buffer just  we'll write 16 at a time to be prophylactic*/   #ascertain MAX_I2C_WRITE sixteen   byte tempStore[MAX_I2C_WRITE];  void setup() {  //Start the I2C Library   Wire.begin();   Wire.setClock(400000);  //Beginning the series port   Series.begin(19200);  //Hither is where nosotros'll continue rails of where in the memory nosotros're writing   long currentSpot = 0;   long timerReset = 0;   byte counter = 0;    //Here we listen for bytes on the serial port and increment   //the counter as we shop them in our tempStore variable   while (1)   {     while (Series.available())     {       tempStore[counter++] = Serial.read(); //Read this byte into the array        if (counter == MAX_I2C_WRITE)       {       //Once we've nerveless a page worth, go alee and exercise        //a folio write functioning         writeEEPROMPage(currentSpot);         counter = 0; //Reset         currentSpot += MAX_I2C_WRITE;       }        timerReset = millis();     }      if (millis() - timerReset > 2000)     {       Series.println(currentSpot);       timerReset = millis();     }   }  }  void loop() {     // Don't exercise annihilation here }  /* This is the three step retentivity writing procedure that we talked about. First nosotros ship the MSB of the address.  And so we ship the LSB of the address. And so we send the  data that we want to store. */  void writeEEPROMPage(long eeAddress) {    Wire.beginTransmission(EEPROM_ADR);    Wire.write((int)(eeAddress >> viii)); // MSB   Wire.write((int)(eeAddress & 0xFF)); // LSB    //Write bytes to EEPROM   for (byte 10 = 0 ; x < MAX_I2C_WRITE ; x++)     Wire.write(tempStore[10]); //Write the information    Wire.endTransmission(); //Send stop condition }                  

Upload this code to your Arduino board and open the terminal program that you installed before. For the purposes of this tutorial, I'll presume you're using TeraTerm.

When yous open TeraTerm, it will ask yous to setup a new connexion:

TeraTerm window asking for connection information

Y'all'll need to select the serial port that your Arduino is connected to. Once you've pressed OK on that, go to Setup > Serial Port and set your Baud Rate to the one nosotros selected in the code higher up (19200) then printing OK.

TeraTerm serial port window with 19200 in the baud rate field

Now you should be seeing a bunch of zeros appearing in your terminal window. This is our sketch telling us how many bytes we've written. So far we've written nothing; allow'southward modify that! Go to File > Send File... and select a file to transport through the terminal. For testing purposes, I suggest using the complete text of the Ghostbusters theme as written and performed by Ray Parker Jr. You tin can get the text file below.

Select that file and exist sure to click on the "binary" button, so that the file is written byte-for-byte over the serial port.

file selection window in TeraTerm with ghostbusters.txt highlighted

When y'all printing "Open" y'all'll see a file transfer window for just a moment as the file is dumped to the concluding.

TeraTerm file transfer window transferring ghostbusters.txt at 80% with 0:00 elapsed time

Now the number in your terminal window should exist 1344, representing the retentivity location that nosotros're sitting at later on writing the complete text of the Ghostbusters theme equally written and performed by Ray Parker Jr. Y'all can get alee and close TeraTerm, it worked! Well... we don't really know if information technology worked until we read it back, then permit's read it dorsum!


Read Something

Reading from the EEPROM basically follows the same 3 pace process equally writing to the EEPROM:

  1. Send the Nearly Significant Byte of the retentivity address that you want to write to.
  2. Send the Least Significant Byte of the memory address that you lot desire to write to.
  3. Ask for the information byte at that location.

Arduino Sketch Example Read Something

Here's an instance sketch to write some data to the EEPROM. Walk through the comments in the lawmaking for an explanation about what's going on.

          linguistic communication:c //Include the Wire I2C Library #include <Wire.h>  /*This address is determined by the way your accost pins are wired. In the diagram from before, nosotros connected A0 and A1 to Basis and  A2 to 5V. To get the address, we showtime with the control lawmaking from  the datasheet (1010) and add the logic state for each address pin in the order A2, A1, A0 (100) which gives us 0b1010100, or in  Hexadecimal, 0x54*/  #define EEPROM_ADR 0x54  void setup() {  //Commencement the I2C Library   Wire.begin();   Wire.setClock(400000);   //First the serial port   Serial.begin(115200);    //Output raw bytes to final   //In this case we're going to read all of the bytes   //which is 32000, or in hex, 0x7D00   for (long x = 0 ; ten < 0x7D00 ; ten++) //Read all 131,071 bytes from EERPOM   {     byte val = readEEPROM(10);     Serial.write(val);   } }  void loop() {   //Naught to do, just hang out. }  /* This is the 3 step retentiveness reading procedure that we talked most. Commencement we send the MSB of the address.  Then we send the LSB of the address. Then nosotros enquire for the  number of bytes that we desire to receive. Hither, we're  going one byte at a time*/  byte readEEPROM(long eeaddress) {   Wire.beginTransmission(EEPROM_ADR);    Wire.write((int)(eeaddress >> 8)); // MSB   Wire.write((int)(eeaddress & 0xFF)); // LSB   Wire.endTransmission();    Wire.requestFrom(EEPROM_ADR, 1);    byte rdata = 0xFF;   if (Wire.bachelor()) rdata = Wire.read();   return rdata; }                  

Now load this sketch onto your Arduino and open TeraTerm again. Once again, you'll need to open the correct series port but earlier we set the correct baud rate and become things moving, allow's create a file to store all the memory that we're almost to read. Go to File > Log... and create a logfile. Make sure to uncheck the "Append" option and check the "Binary" option. This makes certain that the terminal will showtime a fresh logfile and write to information technology byte-for-byte what comes over the terminal.

Log File window in TeraTerm with binary option selected and append option unselected. teraterm.log in the filename field.

When y'all printing "Save" some other dialog window will appear but it may popular under the current window Go notice information technology, it volition come in handy in a 2nd. At present go to Setup > Serial Port and set your Baud Rate to the i nosotros selected in the code above (115200) so press OK. Check the logfile window and see how many bytes have been transferred.

TeraTerm logfile transfer window showing 32000 bytes transferred

One time we've transferred 32000 bytes, nosotros've got everything on the flake. Now shut everything and open upwardly that logfile in a text editor. You should now be face to face up with, you guessed it, the complete text of the Ghostbusters theme every bit written and performed past Ray Parker Jr. Oh aye, plus a agglomeration of junk that represents the unwritten space in memory.

Higher Capacity EEPROMs

So what if the thing that we desire to store is bigger than complete text of the Ghostbusters theme every bit written and performed by Ray Parker Jr? As it happens, y'all tin can become EEPROM devices with much larger storage. For example, the Microchip 24LC1025 tin can store up to 1025 Kbits! That's 128KB, enough infinite to take some real fun with!

Using the Microchip 24LC1025 is nigh exactly like using the smaller EEPROM devices but with 1 minor tweak. Considering the retentiveness space is so much larger, two bytes is no longer enough to correspond the retention accost that we desire to modify. To get around this problem, the 24LC1025 splits up the memory addresses into ii separate blocks. When you accost the fleck, you ship the block selector for the block that you want to manipulate in place of where y'all'd usually send the first bit of the chip address. Because of this, pin A2 on the EEPROM isn't used and needs to exist tied to 5V in lodge for the device to work. Y'all'll notice that we've already tied A2 to 5V in our previous example, so yous could use the aforementioned example excursion to hook it upwardly!

Arduino Sketch Instance Write Something in a Higher Chapters EEPROM

Forth with that change to our Arduino hookup, we'll likewise need to add to our code in order to switch the block select when we reach higher up a certain memory address. Here's what that operation looks like when we're writing:

          language:c void writeEEPROM(long eeAddress, byte data) {   if (eeAddress < 65536)   {     Wire.beginTransmission(EEPROM_ADR_LOW_BLOCK);     eeAddress &= 0xFFFF; //Erase the get-go xvi bits of the long variable   }   else   {     Wire.beginTransmission(EEPROM_ADR_HIGH_BLOCK);   }    Wire.write((int)(eeAddress >> 8)); // MSB   Wire.write((int)(eeAddress & 0xFF)); // LSB   Wire.write(data);   Wire.endTransmission(); }                  

Arduino Sketch Case Read Something in a College Capacity EEPROM

...and here it is when we're reading:

          language:c byte readEEPROM(long eeaddress) {   if (eeaddress < 65536)     Wire.beginTransmission(EEPROM_ADR_LOW_BLOCK);   else     Wire.beginTransmission(EEPROM_ADR_HIGH_BLOCK);    Wire.write((int)(eeaddress >> 8)); // MSB   Wire.write((int)(eeaddress & 0xFF)); // LSB   Wire.endTransmission();    if (eeaddress < 65536)     Wire.requestFrom(EEPROM_ADR_LOW_BLOCK, ane);   else     Wire.requestFrom(EEPROM_ADR_HIGH_BLOCK, one);    byte rdata = 0xFF;   if (Wire.bachelor()) rdata = Wire.read();   return rdata; }                  

It's just that easy! Y'all tin can get the complete Arduino example sketches here if y'all want to play with information technology yourself:

Heads up! If y'all accept an EEPROM device that already has data on it, running the "Write an EEPROM" code will write over the existing data and make it irretrievable. If you lot think there's interesting information on your device, try reading from it first!

  • Write an EEPROM
  • Read an EEPROM

Resources and Going Further

Now that y'all know how to read and write series EEPROMs, yous can have all kinds of fun with your Arduino! Why end at song lyrics? Why non store journals or bitmaps... or fifty-fifty sensor readings? Actually, to think of it, sensor readings are probably the most practical thing to use information technology for...

For more information on the Microchip 24-series EEPROM, check out the resources below:

  • Datasheet (PDF)
  • Ghostbusters (TXT)
  • Arduino Sketch Examples
    • Write an EEPROM
    • Read an EEPROM

But wait, if you're mad with power and want even more storage for your Arduino then you should check out this awesome tutorial on the MicroSD Card Breakout!

How To Read/write Eeprom Using I2c Linux,

Source: https://learn.sparkfun.com/tutorials/reading-and-writing-serial-eeproms/all

Posted by: hsuprots1996.blogspot.com

0 Response to "How To Read/write Eeprom Using I2c Linux"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel