此篇是介紹Arduino外接EEPROM記憶體 繼上一篇讀取Arduino內部記憶體文章之後 https://tcweng.blogspot.com/2019/05/tcwengarduino-eeprom.html 要存取外部EEPROM記憶體 相對存取內部記憶體 程式就要麻煩了很多 內容包含了存取位置的相關問題 如要了解EEPROM請見 https://tcweng.blogspot.com/2019/05/eeprom.html 先解決接線的部分 VCC跟GND分別接上5V跟接地 如果是電是吃3.3的話就要接Arduino的3.3 SDA >> A4 SCL >> A5 程式的部分: #include <Wire.h> 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(); } 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 < length; c++) Wire.write(data[c]); 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; } // maybe let's not read more than 30 or 32 bytes at a time! void i2c_eeprom_read_buffer( int deviceaddress, unsigned int eeaddress, byte *buffer, int length ) { Wire.beginTransmission(deviceaddress); Wire.write((int)(eeaddress >> 8)); // MSB Wire.write((int)(eeaddress & 0xFF)); // LSB Wire.endTransmission(); Wire.requestFrom(deviceaddress,length); int c = 0; for ( c = 0; c < length; c++ ) if (Wire.available()) buffer[c] = Wire.read(); } void setup() { char somedata[] = "this is data from the eeprom"; Wire.begin(); Serial.begin(9600); i2c_eeprom_write_page(0x50, 0, (byte *)somedata, sizeof(somedata)); delay(100); Serial.println("Memory written"); } void loop() { int addr=0; //first address byte b = i2c_eeprom_read_byte(0x50, 0); // access the first address from the memory while (b!=0) { Serial.print((char)b); //print content to serial port addr++; //increase address b = i2c_eeprom_read_byte(0x50, addr); //access an address from the memory } Serial.println(" "); delay(2000); } |
沒有留言:
張貼留言