[SOLVED] EEPROM i2c - use negative values

Post here first, or if you can't find a relevant section!
Post Reply
pokemon99
Posts: 50
Joined: Wed Jun 07, 2017 9:09 am

[SOLVED] EEPROM i2c - use negative values

Post by pokemon99 » Fri Dec 08, 2017 9:06 am

Good afternoon.
Tell me by using External I2C EEPROM,
An example took this one.
https://playground.arduino.cc/Code/I2CEEPROM24LC512
Everything works, but I would like to record negative values.

stevestrong
Posts: 1936
Joined: Mon Oct 19, 2015 12:06 am
Location: Munich, Germany
Contact:

Re: EEPROM i2c

Post by stevestrong » Fri Dec 08, 2017 9:41 am

Change uint8_t to int8_t.

pokemon99
Posts: 50
Joined: Wed Jun 07, 2017 9:09 am

Re: EEPROM i2c

Post by pokemon99 » Fri Dec 08, 2017 12:43 pm

Code: Select all

void writeEEPROM(int deviceaddress, unsigned int eeaddress, int data)
{  
  Wire.beginTransmission(deviceaddress);
  Wire.write((int)(eeaddress >> 8));   // MSB
  Wire.write((int)(eeaddress & 0xFF)); // LSB
  Wire.write(data);
  Wire.endTransmission();
  delay(2);  //no puede ser 0, ya que la velocidad de acceso al EEPROM es muy alta
}
int readEEPROM(int deviceaddress, unsigned int eeaddress)
{
  int rdata = 0;
  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;
}

int EEPROM_int_read(int addr) {
  byte raw[2];
  for (byte i = 0; i < 2; i++) raw[i] =
      readEEPROM(disk1, addr + i);
  int &num = (int&)raw;
  return num;
}

void EEPROM_int_write(int addr, int num) {
  byte raw[2];
  (int&)raw = num;
  for (byte i = 0; i < 2; i++)
    writeEEPROM(disk1, addr + i, raw[i]);
}

  EEPROM_int_write(200, -2555);
  delay(100);
  val = -65536 + EEPROM_int_read(200);

stevestrong
Posts: 1936
Joined: Mon Oct 19, 2015 12:06 am
Location: Munich, Germany
Contact:

Re: EEPROM i2c

Post by stevestrong » Fri Dec 08, 2017 12:46 pm

Do you know how many bits wide is the variable of type "int" for STM32 ?
Hint: is not identical with that for AVR chips.

I recommend to always use the typedefs int8_t, uint8_t, int16_t, uint16_t, int32_t, uint32_t in your code, in this way you know how many bytes/bits are you working with.

dannyf
Posts: 197
Joined: Wed May 11, 2016 4:29 pm

Re: EEPROM i2c

Post by dannyf » Fri Dec 08, 2017 1:06 pm

I would like to record negative values.
negative values are the same as positive (unsigned) values. the code is written to be able to handle both.

pokemon99
Posts: 50
Joined: Wed Jun 07, 2017 9:09 am

Re: EEPROM i2c

Post by pokemon99 » Fri Dec 08, 2017 1:11 pm

Thank you. I replaced int with int16_t, everything is fine.
EEPROM_int_write(200, -2555);
delay(100);
val = EEPROM_int_read(200);

Post Reply