What is EEPROM? Main features of EEPROM memory Eeprom erasing

  • 10.09.2021

Clearing EEPROM memory

The example loops through all memory cells and writes zeros to them.

// Connecting a library for working with EEPROM. #include "EEPROM.h" void setup () (// Go through all cells (bytes) and write zeros to them. for (int i = 0; i< EEPROM.length(); i++) EEPROM.update(i, 0); } void loop() { // Пустой цикл... }


Rollback to factory settings

If you want to return the memory to the factory settings, you must replace 0 with 255, i.e. write not zeros, but the number 255. Thus, in the future, using the isNaN () function, it is possible to check whether a write was made to the EEPROM memory or not.

// Connecting a library for working with EEPROM. #include "EEPROM.h" void setup () (// Iterate through all cells (bytes) and write 255 numbers in them. for (int i = 0; i< EEPROM.length(); i++) EEPROM.update(i, 255); } void loop() { // Пустой цикл... }

Tell us about us

Message

If you have experience in working with Arduino and actually have time for creativity, we invite everyone to become authors of articles published on our portal. These can be either lessons or stories about your experiments with Arduino. Description of various sensors and modules. Advice and guidance for beginners. Write and post your articles in

Electrically erasable programmable read-only memory (EEPROM) chips are metal oxide semiconductor computer chips that are used on a printed circuit board. This type of chip can be erased and reprogrammed using a strong electronic signal. Since this can be done without removing the chip from the device to which it is connected, EEPROM chips are used in many industries.
The EEPROM chip contains non-volatile memory, so its data is not lost if the power supply to the chip is interrupted. This type of microcircuit can be selectively programmed, which means that part of its memory can be changed by rewriting it without affecting the rest of the memory. The information stored inside an EEPROM chip is permanent until it is erased or reprogrammed, making it a valuable component in computers and other electronic devices.

EEPROMs are based on floating gate transistors. The EEPROM is programmed by forced programmable information in the form of electrons through the gate oxide. The floating gate then stores these electrons. A memory cell is considered programmed when it is charged with electrons, and this is represented by zero. If the memory cell is not charged, it is not programmed, and it is represented by one.

A wide variety of devices require memory, which is why EEPROM chips have many uses in consumer electronics. They are used in gaming systems, televisions and computer monitors. Hearing aids, digital cameras, Bluetooth technology, and gaming systems also use EEPROM chips. They are used in the telecommunications, medical and manufacturing industries. Personal and business computers contain EEPROMs.

The EEPROM chip also has a wide variety of applications in the automotive industry. It is used in anti-lock braking systems, airbags, electronic stability controls, transmissions and engine control units. EEPROM chips are also used in air conditioners, instrument panel displays, chassis control modules, and keyless entry systems. These chips help monitor fuel consumption and are also used in various diagnostic systems.

There is a limit on the number of repetitions that can be overwritten by the EEPROM chip. The layer inside the chip is gradually damaged by numerous rewrites. This is not a big problem because some EEPROM chips can be changed up to a million times. Further advances in technology are likely to have a positive impact on what memory chips can look to in the future.

At the dawn of the emergence of memory that retains data when the power is turned off (EPROM, Erasable Programmable ROM - "erasable / programmable ROM", or in Russian EPROM - "programmable ROM"), its main type was memory erasable by ultraviolet light: UV-EPROM (Ultra -Violet EPROM, UV-EPROM). Moreover, the UV prefix was often omitted, since it was clear to everyone that EPROM is erasable by ultraviolet light, and ROM (or ROM) is simply, without additions, one-time programmable OTP-ROM crystals. Microcontrollers with UV program memory have been around since the mid-1990s. In working samples of devices with UV memory, the quartz window through which the erasure was carried out was sealed with a piece of black adhesive tape, since the information in the UV-EPROM is slowly destroyed in sunlight.

Rice. 18.7. Unit cell device EPROM

In fig. 18.7 shows the structure of the EPROM unit cell, which underlies all modern types of flash memory. If we exclude from it what is indicated by the inscription "floating gate", we get the most ordinary field-effect transistor - exactly the same is included in the DRAM cell. If a positive voltage is applied to the control gate of such a transistor, then it will open, and current will flow through it (this is considered the state of a logical unit). In fig. 18.7 above shows a case when the floating gate has no effect on the operation of the cell - for example, this state is typical for pure flash memory, which has never been written to.

If, however, we somehow (we will talk separately) manage to place on the floating gate a certain amount of charges - free electrons, which are shown in Fig. 18.7 below in the form of dark circles with a minus sign, then they will screen the action of the control electrode, and such a transistor will stop conducting current altogether. This is a logical zero state. Since the floating gate is called so because it "floats" in the thickness of the insulator (silicon dioxide), then the charges once imparted to it at rest cannot go anywhere. And the information recorded in this way can be stored for decades (until recently, manufacturers usually gave a 10-year warranty, but in practice, under normal conditions, the storage time is much longer).

Marginal notes

Strictly speaking, in NAND chips (which will be discussed below), the logic must be reversed. If you cannot open the programmed cell in a normal EPROM by applying a reading voltage, then on the contrary there - it cannot be locked by removing the voltage. Therefore, in particular, pure NAND memory produces all zeros, and not ones, like EPROMs. But these are nuances that do not change the essence of the matter.

Octajiocb is nothing at all - to figure out how to place charges on a floating shutter isolated from all external influences. And not only to place - after all, sometimes memory has to be erased, therefore there must be a way to extract them from there. In UV-EPROM, the oxide layer between the floating gate and the substrate was quite thick (if 50 nanometers can be described by the word "thick", of course), and it all worked rather crudely. When recording, a sufficiently high positive voltage was applied to the control gate - sometimes up to 36-40 V, and a small positive voltage was applied to the drain of the transistor. In this case, the electrons that moved from the source to the drain were so accelerated by the field of the control electrode that they simply jumped over the barrier in the form of an insulator between the substrate and the floating gate. This process is also called "hot electron injection".

At the same time, the charge current reached a milliampere - you can imagine what the consumption of the entire circuit was if at least several thousand cells were simultaneously programmed in it. And although such a current was required for a fairly short time (however, from the point of view of the speed of the circuit, it is not so short - milliseconds), it was the biggest drawback of all old samples of EPROM memory. Another thing is even worse - both the insulator and the floating shutter itself could not withstand such mockery for a long time and gradually degraded, which is why the number of erase-write cycles was limited to several hundred, maximum thousands. Many more recent flash memory designs even had a special scheme for storing a map of "broken" cells - exactly as it is done for hard drives. Modern models with millions of cells also have such a card - however, the number of erase / write cycles has now increased to hundreds of thousands. How did you achieve this?

Rice. 18.8. Erasing process in an EPROM unit cell

First, let's see how the erasure was carried out in this scheme. In UV-EPROM, when irradiated with ultraviolet light, high-energy photons impart sufficient momentum to electrons on the floating gate to jump back onto the substrate on their own, without any electrical influences. The first samples of electrically erasable memory (EEPROM, Electrically Erasable Programmable ROM - "electrically erasable programmable ROM", EEPROM) were created at Intel in. late 1970s with the direct participation of future Atmel founder George Perlegos. He used the "Fowler-Nordheim quantum tunneling effect." Behind this incomprehensible name lies a rather simple in essence (but very complex from a physical point of view) phenomenon: with a sufficiently thin insulator film (its thickness had to be reduced from 50 to 10 nm) electrons, if they are slightly pushed by applying a not too high voltage in the right direction , can seep through the barrier without jumping over it. The process itself is shown in Fig. 18.8 above (note the voltage sign at the gate).

The old EEPROMs worked exactly like this: writing was done by "hot injection", and erasing was done by "quantum tunneling". That is why they were quite difficult to operate - experienced developers remember that the first EEPROM microcircuits required two or even three supply voltages, and it was required to supply them during writing and erasing in a certain sequence.

The transformation of EEPROM into flash took place in three different directions. First of all - in the direction of improving the design of the cell itself. To begin with, we got rid of the nastiest stage - "hot injection". Instead, they also began to use "quantum tunneling" when writing, as in erasing. rice. 18.8 below this process is shown - if, when the transistor is open, a sufficiently high (but much lower than with "hot injection") voltage is applied to the control gate, then part of the electrons moving through the open transistor from source to drain will "leak" through the insulator and turn out on a floating shutter. The current consumption during writing has decreased by several orders of magnitude. The insulator, however, had to be made even thinner, which caused rather great difficulties with the introduction of this technology into production.

The second direction - the cell was made a little more complicated by attaching a second transistor to it (ordinary, not two-gate), which divided the drain output and the readout bus of the entire microcircuit. Thanks to all this, it was possible to achieve a significant increase in durability - up to hundreds of thousands of write / erase cycles (millions of cycles typical for flash cards are obtained if you add error correction circuits). In addition, the high voltage generation circuits and the corresponding write / erase pulse generators were transferred inside the microcircuit, which made it incomparably more convenient to use these types of memory - they began to be powered from the same voltage (5, 3.3, or even 1.8 V).

And, finally, the third, perhaps the most important, improvement consisted in changing the organization of access to cells on a chip, as a result of which this type of memory earned the name - flash (that is, "lightning"), now known to every owner of a digital camera or pocket MP3 player. So in the mid-1980s they called a kind of EEPROM, in which erasing and writing were performed at once in whole blocks - pages. The procedure for reading from an arbitrary cell, however, for obvious reasons has slowed down - to speed it up, you have to place an intermediate (buffer) SRAM on the flash memory crystals. For flash drives, this does not really matter, since there all the same, data is read and written in large arrays at once, but for use in microcontrollers this may turn out to be inconvenient. Moreover, in MK it is inconvenient to use the fastest version of flash-technology - the so-called. memory of the NAND type (from the name of the logical function "AND-NOT"), where in principle it is possible to read and write memory only in blocks of 512 bytes (this is the usual size of a sector on a hard disk, also read and written entirely at a time - from here you can understand the main NAND assignment).

In MK, traditional (like NOR) flash-memory of programs is usually used, in which pages are relatively small in size - about 64-256 bytes. However, if the user himself does not undertake the creation of a programmer for such a microcircuit, he may not even guess about the paged nature of the memory. And for user data, an EEPROM is used either with the ability to read an arbitrary byte, or partitioned, but into very small blocks - for example, 4 bytes each. In this case, for the user, access still remains byte byte. A characteristic feature of such memory is a rather slow (on the order of milliseconds) write procedure, while reading proceeds no slower than any other operations in the MC.

The development of flash memory technologies has been of great importance for the reduction in the cost and availability of microcontrollers. In the future, we will deal with nonvolatile memory not only in the form of programs and data built into the microcontroller, but also with individual microcircuits that allow recording rather large amounts of information.

All microcontrollers of the Mega family include non-volatile memory ( EEPROM memory). The amount of this memory ranges from 512 bytes in the ATmega8x models to 4 KB in the older models. EEPROM memory is located in its address space and, like RAM, is organized linearly. To work with EEPROM memory uses three I / O registers: an address register, a data register, and a control register.

Address register

Address register EEPROM memory EEAR (EEPROM Address Register) physically located in two RVB EEARH: EEARL located along
addresses $ 1F ($ 3F) and $ 1E ($ 3E), respectively. The address of the cell to be accessed is loaded into this register. The address register is available for both writing and reading. Moreover, in the register EEARH only the least significant bits are used (the number of involved bits depends on the volume EEPROM memory). Unused register bits EEARH are read-only and contain "0".

Data register

Data register EEPROM memory EEDR (EEPROM Data Register) located at $ 1D ($ 3D). When writing to this register, data is loaded that should be placed in EEPROM, and when reading, this register is filled with data read from EEPROM.

Control register

Control register EEPROM memory EECR (EEPROM Control Register) located at $ 1C ($ 3C). This register is used for
access control to EEPROM memory. Its description is shown in the table below:

Discharge Name Description
7..4 - not used, read as "0"
3 EERIE EEPROM interrupt enable. This bit controls the generation of an interrupt that occurs at the end of the write cycle to the EEPROM. If this bit is set to "1", interrupts are enabled (if the register I flag
SREG is also set to "1"). When the EEWE discharge is cleared (see further in
table) interrupt is generated constantly
2 EEMWE EEPROM write permission control. The state of this bit determines the operation of the EEWE write enable flag. If this bit is set to "1", then when writing to the EEWE bit "1", the data is written to the EEPROM. Otherwise, setting EEWE to “1” has no effect. After software installation, the EEMWE bit is reset by hardware after
4 machine cycles
1 EEWE Permission to write to EEPROM. When this bit is set to "1", data is written to the EEPROM (if EEMWE is "1")
0 EERE Permission to read from EEPROM. After setting this bit to "1", data is read from the EEPROM. At the end of reading, this bit is cleared by hardware.

To write one byte to the EEPROM, you must:

1. Wait until the EEPROM is ready to write data (wait until the EEWE flag of the EECR register is cleared).

2. Wait until the completion of writing to the FLASH program memory (wait until the SPMEN flag of the SPMCR register is cleared).

3. Load the data byte into the EEDR register, and the required address into the EEAR register (if necessary).

4. Set the EEMWE flag of the EECR register to "1".

5. Write to the EEWE bit of the register EECR log. "1" for 4 machine cycles. After setting this bit, the processor
skips 2 machine cycles before executing the next instruction.

To read one byte from the EEPROM, you must:

1. Check the state of the EEWE flag. The fact is that while the operation is being written to the EEPROM memory (the EEWE flag is set), you can neither read the EEPROM memory, nor change the address register.

2. Load the required address into the EEAR register.

3. Set the EERE bit of the EECR register to "1".

When the requested data is placed in the data register EEDR, a hardware reset of this bit will occur. However, you do not need to monitor the state of the EERE bit to determine when the read operation is complete, since the read operation from the EEPROM is always performed in one machine cycle. In addition, after setting the EERE bit to "1", the processor skips 4 machine cycles before starting the next instruction.

The AVR Studio GCC environment has a standard library for working with EEPROM, which is included by connecting a file ... The main functions are eeprom_read_byte (), eeprom_write_byte (), eeprom_read_word (), eeprom_write_word (). For example, let's write a program for a mini-counter from 0 to 9, where when you press one button, a value will be added, and the other button will store this value in memory. The Atmega8 microcontroller is powered by an internal 8MHz clock generator. A single-digit seven-segment indicator with a common anode through current-limiting resistors R1-R7 is connected to port B, the common anode is connected to the positive power supply. The diagram is shown below:

First, we connect the libraries necessary for the work, including the EEPROM. We define variables. The variable "s" stores the value to be displayed on the indicator, when the SB1 button is pressed, this value is increased by one, but not more than 10. The eeprom_var variable will interact with the EEPROM. When the power is turned on, the EEPROM is read, the read data is assigned to the "s" variable, based on this, a certain digit is displayed on the indicator. When you press SB2, data from the "s" variable is written to the EEPROM, and the indicator will blink once.

#include #include #include #define d0 ~ (0x3F) // 0 #define d1 ~ (0x06) // 1 #define d2 ~ (0x5B) // 2 #define d3 ~ (0x4F) // 3 #define d4 ~ (0x66) // 4 #define d5 ~ (0x6D) // 5 #define d6 ~ (0x7D) // 6 #define d7 ~ (0x07) // 7 #define d8 ~ (0x7F) // 8 #define d9 ~ (0x6F) // 9 unsigned char s; unsigned char eeprom_var EEMEM; // define a variable in EEPROM int main (void) (DDRB = 0xFF; // Port B to output PORTB = 0xFF; DDRD = 0x00; // Port D to input PORTD = 0xFF; // Turn on pulling resistors s = eeprom_read_byte (& eeprom_var ); // read a byte from EEPROM and put it in "s" while (1) (if ((PIND & (1<< PD0)) == 0) // если кнопка SB1 нажата { while((PIND&(1 << PD0)) == 0){} // ждем отпускания кнопки s++; // увеличиваем "s" на единицу _delay_ms(200); } if(s == 10) // Когда дойдет до 10 обнуляем "s" { s = 0; } if((PIND&(1 << PD1)) == 0) // если кнопка SB2 нажата { while((PIND&(1 << PD1)) == 0){} // ждем отпускания кнопки DDRB = 0xFF; // мигаем индикатором _delay_ms(200); DDRB = 0x00; _delay_ms(200); DDRB = 0xFF; eeprom_write_byte(&eeprom_var, s); // записываем "s" в EEPROM _delay_ms(200); } if(s==0) // Выводим цифры на индикатор PORTB = d0; if(s==1) PORTB = d1; if(s==2) PORTB = d2; if(s==3) PORTB = d3; if(s==4) PORTB = d4; if(s==5) PORTB = d5; if(s==6) PORTB = d6; if(s==7) PORTB = d7; if(s==8) PORTB = d8; if(s==9) PORTB = d9; } }

Comments (1)

0 AntonChip 05/02/2013 22:15

Quoting Max:

Maybe I'm confusing something, but if you have an indicator with OA, then one resistor on the 5V line is enough. Why put current-limiting resistors after the element that they should protect from a large current ??


Just imagine what will happen if one segment of the indicator closes with this and with a different resistor connection scheme.

0 AntonChip 05/15/2013 11:16

I quote gydok:

How to write a two-dimensional array to eeprom?


Code:
#include // Connect the library

EEMEM unsigned char colors = ((1, 2, 3), // Declare array in EEPROM
{4, 5, 6}};

eeprom_write_byte (& colors, 1); // Writing array elements to EEPROM
eeprom_write_byte (& colors, 2);
eeprom_write_byte (& colors, 3);
eeprom_write_byte (& colors, 4);
eeprom_write_byte (& colors, 5);
eeprom_write_byte (& colors, 6);

unsigned char temp;
temp = eeprom_read_byte (& colors); // Extract an array element from EEPROM, row 2 (), column 1 (), i.e. number 4

Arduino is a whole family of different devices for creating electronic projects. Microcontrollers are very easy to use, even a beginner can learn. Each microcontroller consists of a board, software for work, memory. This article will take a look at the non-volatile memory used in the Arduino.

EEPROM memory description

Arduino provides its users with three types of built-in device memory: stationary RAM (random access memory or SRAM) - it is necessary for recording and storing data during use; flash cards - to save already recorded schemes; - for storage and subsequent use of data.

All data on RAM is erased as soon as the device is rebooted or the power is turned off. The second two save all the information before overwriting and allow you to retrieve it when necessary. Flash drives are quite common nowadays. It is worth considering the EEPROM memory in more detail.

The abbreviation stands for Electrically Erasable Programmable Read-Only Memory and in translation into Russian literally means - electrically erasable programmable read-only memory. The manufacturer guarantees the safety of information for several decades in advance after the last power outage (usually a period of 20 years is given, depending on the rate of decrease of the device's charge).

In this case, you need to know that the ability to overwrite the device is limited and is no more than 100,000 times. Therefore, it is recommended to be careful and attentive to the entered data and not to overwrite it again.

The amount of memory, in comparison with modern media, is very small and different for different microcontrollers. For example, for:

  • ATmega328 - 1kB
  • ATmega168 and ATmega8 - 512 bytes,
  • and ATmega1280 - 4KB.

This is because each microcontroller is designed for a certain amount of tasks, has a different number of pins for connection, respectively, a different amount of memory is required. Moreover, this amount is sufficient for usually created projects.

It takes a significant amount of time to write to the EEPROM - about 3 ms... If the power is turned off while recording, the data is not saved at all or it may be written by mistake. It is always required to additionally check the entered information in order to avoid failures during operation. Data reading is much faster, the memory resource is not reduced from this.

Library

Working with EEPROM memory is carried out using a library that was specially created for Arduino. The main ones are the ability to write and read data. activated by command #include EEPROM.h.

  • for records- EEPROM.write (address, data);
  • for reading- EEPROM.read (address).

In these sketches: address - the argument with the cell data, where the data of the second data argument is entered; reads use one argument, address, which indicates where to read the information from.

Function Appointment
read (address) reads 1 byte from EEPROM; address - the address where the data is read from (cell starting from 0);
write (address, value) writes to memory the value value (1 byte, a number from 0 to 255) at the address address;
update (address, value) replaces the value value at address if its old content differs from the new one;
get (address, data) reads data of the specified type from memory at address;
put (address, data) writes data of the specified type to memory at address;
EEPROM allows you to use the identifier "EEPROM" as an array to write data to and read from memory.

Writing integers

Writing integers to the non-volatile EEPROM is fairly straightforward. Entering numbers occurs with the launch of the function EEPROM.write ()... The required data is indicated in brackets. In this case, numbers from 0 to 255 and numbers over 255 are written in different ways. The first ones are entered simply - their size is 1 byte, that is, one cell. To write the second, you must use the operators highByte () high byte and lowByte () low byte.

The number is divided into bytes and written separately in cells. For example, the number 789 will be written in two cells: the first will be multiplier 3, and the second - the missing value. As a result, the required value is obtained:

3 * 256 + 21 = 789

For « reuniting "large integer, the word () function is applied: int val = word (hi, low)... You should read that the maximum integer to write is 65536 (that is, 2 to the 16th power). In cells that have not yet had any other entries, the monitor will have numbers 255 in each.

Writing floating point numbers and strings

Floating point and string numbers are a form of notation for real numbers, where they are represented from the mantissa and exponent. Such numbers are written to the non-volatile EEPROM memory with the activation of the function EEPROM.put (), reading, respectively, - EEPROM.get ().

When programming, floating point numeric values ​​are denoted as float, it is worth noting that this is not a command, but a number. Char type (character type) - used to denote strings. The process of writing numbers to the monitor is started with setup (), reading with loop ().

In the process, the monitor screen may display the values ​​ovf, which means "overflowed", and nan, which means "there is no numerical value". This means that the information written to the cell cannot be reproduced as a floating point number. Such a situation will not arise if it is reliably known in which cell which type of information is recorded.

Examples of projects and sketches

Example # 1

The sketch will write up to 16 characters from the serial port and loop out 16 characters from the EEPROM. Thanks to the data is written to the EEPROM and the contents of the non-volatile memory are monitored.

// check if EEPROM is working #include int i, d; void setup () (Serial.begin (9600); // initialize the port, speed 9600) void loop () (// read EEPROM and output 16 data to the serial port Serial.println (); Serial.print ("EEPROM =" ); i = 0; while (i< 16) { Serial.print((char)EEPROM.read(i)); i++; } // проверка есть ли данные для записи if (Serial.available() != 0) { delay(50); // ожидание окончания приема данных // запись в EEPROM i= 0; while(i < 20) { d= Serial.read(); if (d == -1) d= " "; // если символы закончились, заполнение пробелами EEPROM.write(i, (byte)d); // запись EEPROM i++; } } delay(500); }

Example No. 2

For a better understanding, we can create a small sketch that will help in understanding how to work with non-volatile memory. We count all the cells of this memory. If the cell is not empty, output to the serial port. Then fill in the cells with spaces. Then we enter the text through the serial monitor. We write it to the EEPROM, and read it on the next turn on.

#include int address = 0; // eeprom address int read_value = 0; // data read from eeprom char serial_in_data; // serial port data int led = 6; // line 6 for LED int i; void setup () (pinMode (led, OUTPUT); // line 6 is configured for the output Serial.begin (9600); // baud rate on the serial port 9600 Serial.println (); Serial.println ("PREVIOUS TEXT IN EEPROM: - "); for (address = 0; address< 1024; address ++) // считываем всю память EEPROM { read_value = EEPROM.read(address); Serial.write(read_value); } Serial.println(); Serial.println("WRITE THE NEW TEXT: "); for(address = 0; address < 1024; address ++) // заполняем всю память EEPROM пробелами EEPROM.write(address, " "); for(address = 0; address < 1024;) // записываем пришедшие с последовательного порта данные в память EEPROM { if(Serial.available()) { serial_in_data = Serial.read(); Serial.write(serial_in_data); EEPROM.write(address, serial_in_data); address ++; digitalWrite(led, HIGH); delay(100); digitalWrite(led, LOW); } } } void loop() { //---- мигаем светодиодом каждую секунду -----// digitalWrite(led, HIGH); delay(1000); digitalWrite(led, LOW); delay(1000); }

Example No. 3

Writing two integers to memory, reading them from the EEPROM and outputting them to the serial port. Numbers from 0 to 255 occupy 1 byte of memory, using the function EEPROM.write () are written to the desired cell. For numbers greater than 255, divide them by bytes using highByte () and lowByte () and write each byte to its own cell. The maximum number in this case is 65536 (or 2 16).

#include // connect the EEPROM library void setup () (int smallNum = 123; // integer from 0 to 255 EEPROM.write (0, smallNum); // write the number to the cell 0 int bigNum = 789; // the number> 255 we split by 2 bytes (max. 65536) byte hi = highByte (bigNum); // high byte byte low = lowByte (bigNum); // low byte EEPROM.write (1, hi); // write high byte of EEPROM to cell 1 .write (2, low); // write the low byte into cell 2 Serial.begin (9600); // initialize the serial port) void loop () (for (int addr = 0; addr<1024; addr++) { // для всех ячеек памяти (для Arduino UNO 1024) byte val = EEPROM.read(addr); // считываем 1 байт по адресу ячейки Serial.print(addr); // выводим адрес в послед. порт Serial.print("\t"); // табуляция Serial.println(val); // выводим значение в послед. порт } delay(60000); // задержка 1 мин }

Example No. 4

Writing Floating Point Numbers and Strings - Method EEPROM.put ()... Reading - EEPROM.get ().

#include // connect the library void setup () (int addr = 0; // float address f = 3.1415926f; // floating point number (float type) EEPROM.put (addr, f); // wrote the number f at addr addr + = sizeof (float); // calculate the next free memory location char name = "Hello, SolTau.ru!"; // create an array of characters EEPROM.put (addr, name); // write the array to EEPROM Serial.begin (9600); // initialize serial port) void loop () (for (int addr = 0; addr<1024; addr++) { // для всех ячеек памяти (1024Б=1кБ) Serial.print(addr); // выводим адрес в послед. порт Serial.print("\t"); // табуляция float f; // переменная для хранения значений типа float EEPROM.get(addr, f); // получаем значение типа float по адресу addr Serial.print(f, 5); // выводим с точностью 5 знаков после запятой Serial.print("\t"); // табуляция char c; // переменная для хранения массива из 20 символов EEPROM.get(addr, c); // считываем массив символов по адресу addr Serial.println(c); // выводим массив в порт } delay(60000); // ждём 1 минуту }

Example No. 5

Using EEPROM as an array.

#include void setup () (EEPROM = 11; // write the 1st EEPROM cell = 121; // write the 2nd EEPROM cell = 141; // write the 3rd EEPROM cell = 236; // write the 4th cell Serial .begin (9600);) void loop () (for (int addr = 0; addr<1024; addr++) { Serial.print(addr); Serial.print("\t"); int n = EEPROM; // считываем ячейку по адресу addr Serial.println(n); // выводим в порт } delay(60000); }

Working with EEPROM

As mentioned earlier, the EEPROM memory resource is limited. To extend the lifespan of nonvolatile memory, instead of using the write () function, it is better to use the update function. In this case, rewriting is carried out only for those cells where the value differs from the newly recorded one.

Another useful function of the considered microcontroller memory is the ability to use byte storage cells as parts of an integral EEPROM array. With any format of use, it is necessary to constantly monitor the integrity of the recorded data.

Such memory on Arduino stores the most important things for the operation of the controller and the device as standard. For example, if a temperature controller is created on such a basis and the initial data turn out to be erroneous, the device will work “inadequately” to the existing conditions - greatly underestimate or overestimate the temperature.

There are several situations where the EEPROM contains incorrect data:

  1. Upon initial activation, there were no entries yet.
  2. At the moment of uncontrolled power failure, some or all of the data will not be recorded or will be written incorrectly.
  3. After the completion of possible data rewriting cycles.

To avoid unpleasant consequences, the device can be programmed for several options: apply the emergency code data, turn off the system completely, signal a malfunction, use a previously created copy, or others.

To control the integrity of information, the system control code is used. It is created on the basis of the original data recording and, when checked, it re-calculates the data. If the result is different, it is an error. The most common option for such a check is a checksum - an ordinary mathematical operation is performed to add all the cell values.

Experienced programmers add an additional "exclusive OR" to this code, for example, E5h. If all values ​​are equal to zero, and the system mistakenly zeroed out the original data, such a trick will reveal an error.

These are the basic principles of working with non-volatile EEPROM memory for Arduino microcontrollers. For certain projects it is worth using only this type of memory. It has both its pros and cons. To master the methods of writing and reading, it is best to start with simple tasks.