[已解决]用共用体读写EEPROM乱码
本帖最后由 陈野猪 于 2014-6-20 22:19 编辑买了个DUE,但是没有内置的EEPROM,只好用AT24C32,参考坛子里用共用体写了一个读写程序,但是写进去后读出来结果不一样。后来用mega2560测试也不行,各位大大帮我指点一下吧~~
#include <Wire.h> //I2C library
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();
}
// WARNING: address is a page address, 6-bit end will wrap around
// also, data can be maximum of about 30 bytes, because the Wire library has a buffer of 32 bytes
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);
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 = Wire.read();
}
union floatType
{
float a;
byte b;
};
floatType num1;
union intType
{
int a;
byte b;
};
intType int1;
void setup()
{
int1.a=0;
num1.a=987.65;
// num1.a=781.03;
int addr=0,i;
Wire.begin(); // initialise the connection
Serial.begin(9600);
Serial.println("Write:");
// for(int i=0;i<2;i++)
// {
// byte temp=num1.b;
// i2c_eeprom_write_byte(0x57, addr++,int1.b);
// }
for(int i=0;i<4;i++)
{
i2c_eeprom_write_byte(0x57, addr++,num1.b);
}
Serial.print('\n');
}
void loop()
{
int i,b;
float num2;
int int2;
intType int1;
floatType temp;
int addr=0; //first address
Serial.println("Read:");
for(i=0;i<4;i++)
{
temp.b = i2c_eeprom_read_byte(0x57, i); //access an address from the memory
}
num2=temp.a;
Serial.println(num2);
Serial.print('\n');
delay(2000);
} 问题已经解决 在写入时加入延时就可以了 陈野猪 发表于 2014-6-20 22:19 static/image/common/back.gif
问题已经解决 在写入时加入延时就可以了
你好,我copy你的代码,读写都添加延时调试时,串口只循环返回
Read:
nan
何解? 加饭 发表于 2014-8-29 16:31 static/image/common/back.gif
你好,我copy你的代码,读写都添加延时调试时,串口只循环返回
Read:
nan
用的什么板子呢?
UNO和mega都试过,结果都一样
页:
[1]