cyberp/AT24Cx
Use Git or checkout with SVN using the web URL.
Work fast with our official CLI. Learn more.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
Library for using the Atmels EEPROM AT24C32/AT24C64/AT24C128/AT24C256/AT24C512 in Arduino projects. See https://oberguru.net/elektronik/eeprom/at24cx-at24c32-at24c64-at24c128-at24c256-at24c512.html for definitons and differences.
Written by Christian Paul, 2014 — 2015. This software is released under the terms of the MIT license. See the file LICENSE or LIZENZ for details, please.
You can use any of the eight possibles EEPROM devices on the I2C bus.
uses the device with index 0 and given page size. You can select a device with given index between 0 and 8 with constructor
Than, you can single write or read single bytes from the EEPROM with
or write and read an array of bytes with
For writing integers, long, float, double or sequences of chars you can use the comfort functions
Reading the values is done by using
Alternative you can use the individual classes with predefined page sizes:
or with different index than 0:
About
Library for using the Atmels EEPROM AT24C32/AT24C64/AT24C128/AT24C256/AT24C512 in Arduino projects.
Arduino.ru
Запись и чтение at24c32
- Войдите или зарегистрируйтесь, чтобы получить возможность отправлять комментарии
Добрый день. Arduino только начинаю осваивать. Помогите разобраться. Без проблем пишу и читаю по 1 байту.
Функция для записи:
void i2c_eeprom_write_byte( int deviceaddress, unsigned int eeaddress, byte data ) <
int rdata = data;
Wire.beginTransmission(deviceaddress);
Wire.write((int)(eeaddress >> 8)); // MSB
Wire.write((int)(eeaddress & 0xFF)); // LSB
Wire.write(rdata);
Wire.endTransmission();
>
Функция для чтения:
byte i2c_eeprom_read_byte( int deviceaddress, unsigned int eeaddress ) <
byte rdata = 0xFF;
Wire.beginTransmission(deviceaddress);
Wire.write((int)(eeaddress >> 8)); // MSB
Wire.write((int)(eeaddress & 0xFF)); // LSB
Wire.endTransmission();
Wire.requestFrom(deviceaddress,1);
if (Wire.available()) rdata = Wire.read();
return rdata;
>
//записываю единицу по адресу 4000
i2c_eeprom_write_byte( 0x50, 4000, 1 );
delay(10);
//считываю данные по адресу 4000
byte b = i2c_eeprom_read_byte(0x50, 4000);
Вопрос: как записать 2х байтовое число по адресу 4000? Я понимаю, что в 1 ячейку не поместится, тоесть нужно записывать по адресу 4000 и 4001. Как реализовать такую запись и чтение. Например, я хочу записать в по адресу 4000 значение 3000, а затем считать это значение 3000.
Видел функцию, которая возможно и может так делать, но не могу разобраться.
void i2c_eeprom_write_page( int deviceaddress, unsigned int eeaddresspage, byte* data, byte length ) <
Wire.beginTransmission(deviceaddress);
Wire.write((int)(eeaddresspage >> 8)); // MSB
Wire.write((int)(eeaddresspage & 0xFF)); // LSB
byte c;
for ( c = 0; c > 8)); // MSB
Wire.write((int)(eeaddress & 0xFF)); // LSB
Wire.endTransmission();
Wire.requestFrom(deviceaddress,length);
int c = 0;
for ( c = 0; c Войдите или зарегистрируйтесь, чтобы получить возможность отправлять комментарии
- Войдите или зарегистрируйтесь, чтобы получить возможность отправлять комментарии
- Войдите или зарегистрируйтесь, чтобы получить возможность отправлять комментарии
все ли ячейки памяти 24С32, установленную на часах модуле часов 3231, можно использовать для своих нужд, или что-то используют часы?
почитайте, пожалуйста, с адреса 0 до 25. какие значения там? 65-90?
пытался писать с 0-го адреса. значеня по адресам 1 и 2 сбиваются, на 66 и 67.
видимо 3231 туда пишет.
- Войдите или зарегистрируйтесь, чтобы получить возможность отправлять комментарии
Для начала в реализации zs-042 имеет на борту АТ24С32 начальный адрес которой 0x68. И действительно первые 16 байт заняты под часы. Таким образом доступная рамять начинается с 0x78
- Войдите или зарегистрируйтесь, чтобы получить возможность отправлять комментарии
Для начала в реализации zs-042 имеет на борту АТ24С32 начальный адрес которой 0x68. И действительно первые 16 байт заняты под часы. Таким образом доступная рамять начинается с 0x78
В моем случае не было задержки после записи байта. писался мусор. добавил, все ок, работает как часы, китайские :-)
откуда такая информация?
0х68 начальный адрес? то есть перемычками я меняю начальный адрес? есть сомнения. 68-адрес устройства на шине, а не памяти
- Войдите или зарегистрируйтесь, чтобы получить возможность отправлять комментарии
Разрешите побыть КО (капитаном).
Вот два модуля RTC 3231 с Ali, оба «сверху» и потом «снизу». На одном напаяна память 24С32 (4 кБ) и он справа, на другом такой памяти нет.
Разумеется, оба модуля работают как RTC часы DS3231 без вопросов (левый не имеет встроенной подтяжки I2C шины, правый имеет 4.7 кОм подтягивающие резисторы). Разумеется, «часы» писать сами по себе куда-либо вовне (например, в EEPROM на той же плате модуля) не могут и не умеют.
Разумеется на фото справа перемычки (A0, A1 и A2) относятся к EEPROM памяти, позволяют изменять ее адрес, в то время как I2C адрес DS3231 («часы») остается 0x68. Если что, то I2C адрес напаяной 24С32 EEPROM (на фото справа) по умолчанию 0x57 (перемычки не запаяны).
Как представляется разумным, добавление EEPROM к RTC есть калька с удачного проекта, когда к работе RTC добавляют _расписание_, по аналогии с расписанием школьных звонков по дням недели и, может быть, по классам (учащихся). «Регулярную» задачу для часов придумать несложно.
Ну и, разумеется, никакой мистики во всем этом не имеется. Просто часы, просто бесплатно еще и 4 кБ (I2C eeprom) памяти.
AT24C32 EEPROM and arduino
I recently bought a small I2C demo board for the DS1307 RTC from Maxim and the AT24C32 EEPROM for Atmel, these boards are available everywhere and it contains a small battery for the RTC on the underside of the board. As I had not used I2C before, I decided to use tutorials to learn about the DS1307 but after I had mastered that I decided to see if I could work the EEPROM by myself. These EEPROMs are available in both 32K and 64K versions, and 8 chips can be used on the same bus at once, giving a total capacity of 64kbs if 8x 64K chips are present.
AT24C32 device addressing
Unlike the RTC which has a hardwired address, the AT24C32 has 3 pins which allow the address to be set by the user, to allow multiple AT24C32/64’s be installed on the I2C bus. As there are 3 address inputs (A0, A1 and A2), which can take 2 states, either a High or a Low, there are therefore 8 (2^3) different combinations of the state inputs, so 8 different addresses can be used. Looking at the datasheet it shows that these 3 bits are placed at the end of the 7-bit device address, just before the Read/Write bit. Examining the schematic provided by the seller, I see that all 3 inputs are tied low. And so the 7-bit address becomes 1010000 (Binary) or 0x50 (Hexadecimal). To read or write to the device I would take a 1 or 0 to the end of the 7-bit address, but gladly the arduino takes care of this.
Reading and writing data
To write to the AT24C32, requires only selecting the address and sending a byte. The address is in two bytes (not all 16 bits are used, see 12 bit register addresses) as there are 4096 possible addresses which is more than what one byte (255) can hold. Converting a numerical value to these two bytes is a little difficult and I’ll explain it in the next example. For now, we will just write to the first possible address.
Sequential reading and semi-sequential writing
Both reading and writing to the EEPROM are sequential meaning that you can read bytes from the register without having to reset the address pointer, however writing is only sequential up to the limit of 32 bytes (called a page write), I discovered this to my peril when receiving illegal characters that I had apparently written from the following sketch. This writes the alphabet to the first 26 positions of the EEPROM. It took me about an hour to finally have the sense to check the datasheet for an answer!
Have a go at changing the value of ‘val’ at the beginning of the sketch, and you will see that you can only write 30 bytes into the chip (the other 2 bytes are addresses) without garbage (ÿ) being return when you read it.
12 bit register addresses
As there are 4096 memory locations, there are 12-bit addresses and you can not simply 1 byte as an address, but must send two, with the address split over the 4 Least Significant Bits of the 1st word address and all 8-bits of the 2nd word address. To avoid complications, I started only reading/writing to the first possible address (0) and any following ones through sequential reads/writes. I then got to the problem of converting an int address to a 12-bit number.
We have an address, any number between 0 and 4095 inclusive. In binary this number is (0000) abcd efgh ijkl. To get the 1st word address, we bit shift the whole number right 8 bits, so it becomes 0000 abcd. Then, bit shifting the number back 8 bits it becomes (0000) abcd 0000 0000. If we then subtract this derived number (which is just the 1st word address with 8 0’s tacked on) from the original address ((0000) abcd efgh ijkl), we can get the lower byte of the address, (oooo oooo) efgh ijkl. To make the whole thing easier to understand, I’ve made up another example sketch to show the functionality of this.
I made functions to simplify sketches needing to use these:
These can be easily integrated into the first sketch:
You can also further integrate these functions into other functions eg. AT24C32.Write/Read(address, location, data), but I’ll leave that to the reader to work out, it really shouldn’t be hard…
At24c32 arduino примеры
Arduino библиотека за управление на 24C32 / 24C32 Arduino Library
/kn34pc.com/справочник/ .
Atmel AT24C32 — Two-wire Serial EEPROM 32K (4096 x 8)
Features:
— Internally Organized 4096 x 8 (32K)
— Two-wire Serial Interface
— Bi-directional Data Transfer Protocol
— 100 kHz (2,7V) and 400 kHz (5V) Compatibility
— Write Protect Pin for Hardware Data Protection
— 8-byte Page (32K) Write Modes
— Partial Page Writes are Allowed
— Self-timed Write Cycle (5 ms max)
— Endurance: 1 Million Write Cycles
— Data Retention: 100 Years
I2C address = 0x50 или 0x51 или 0x52 или 0x53 или 0x54 или 0x55 или 0x56 или 0x57 в зависимост от лог. ниво на адресните изводи A2, A1, A0
EEPROM 24C32 — тестова схема
За тестовете не разполагах с отделна ИС — EEPROM 24C32, а с китайски модул, изпълнен с RT C (s erial Real-Time Clock) DS1307, EEPROM 24C32 и температурен сензор DS18B20.
China module RTC DS1307 + EEPROM 24C32 + temp. sensor DS18B20
DS1307, 24C32 и DS18B20 са свързани на една захранваща шина, а DS1307 и 24C32: на обща I2C шина. Акумулаторът/батерията BAT1 (CR2032 ) са необходими само за RTC DS1307 .
LZ2WSG: принципна ел . схема («свалена» от печатната платка) на модул RTC DS1307 + EEPROM 24C32 + DS18B20
(възможни са грешки и неточности!)
Arduino Nano и модул RTC DS1307 + EEPROM 24C32 + DS18B20
Библиотека за управление на EEPROM 24C32 под Arduino / EEPROM 24C32 Arduino Library:
at24c32_lib_v0.2.zip
Библиотеката записва данни САМО побитово (BYTE WRITE). Режим PAGE WRITE не е реализиран.
В тестовата схема с китайския модул към I2C шината са свързани вътрешните pull-up резистори на микроконтролера (Arduino TWI, 20..50 kΩ) и съответно двата резистора R2, R3 в паралел. При схема с ИС 24C32 външни pull-up резистори може да не се свързват, а да се разчита на вътрешните резистори в микроконтролера.
at24c32( uint8_t );
I2C address, в зависимост от лог. ниво на адресните изводи A2, A1, A0
Напр. при A2(GND), A1(GND), A0(GND) -> I2C address = 0x50 (при използвания китайски модул: на I2C адрес 0x68 отговаря DS1307).
EEPROM 24C32 и RTC DS1307: Arduino I2C Scanner
Публични функции и процедури:
void init();
инициализация на библиотеката
I2C шината може да работи на честота 100 kHz (по подразбиране) и на 400 kHz.
За работа на 400 kHz е необходимо след инициализацията да се добави стандартната Arduino функция за управление на TWI:
Wire.setClock(400000L);
uint8_t read( uint16_t m_addr);
чете съдържанието на клетка с адрес m_addr
void write( uint16_t m_addr, uint8_t m_data);
записва клетка на адрес m_addr с данни m_data
void update( uint16_t m_addr, uint8_t m_data);
чете клетка и записва върху нея данни само при разлика (виж EEPROM endurance)
След запис I2C шината трябва да остане в технологично време на покой преди началото на следващата операция. В документацията това време twr (Write Cycle Time, табл. 5, стр. 5 от [1]) варира от 5..10 ms в зависимост от конкретния производител.
В библиотеката съм добавил 5 ms, като досега не съм имал проблем с реакцията на ИС. За конкретни случаи (напр. при друг производител) twr може да се увеличи.
Пример 1: Четене, изтриване и запис (със случайни данни) на клетки в EEPROM 24C32
at24c32_rbx.zip
Пример-1 използвам за бърз тест на работоспособността на интегралната схема и контрол на съдържанието в паметта.
Функциите са достъпни през Arduino Serial Monitor. Скорост: 57 600 бода.
***
r — четене на данни от цялото адресно пространство
***
b — изтриване (запис с 0xFF) на клетките в EEPROM (и последващо автоматично четене за визуална проверка на състоянието). Процесът е сравнително бавен поради относително големия брой клетки за обработка.
***
x — запис на всички клетки в адресното пространство с псевдо-случайни данни (и последващо автоматично четене за визуална проверка на състоянието). Процесът е сравнително бавен поради относително големия брой клетки за обработка.
Забележка: Програмният код (или части от него) е за некомерсиалнно използване!
LZ2WSG, Силистра
31 октомври 2018 година