Serial read to byte converstion to store in EEPROM

Hi

i am hoping someone can help me, im basically working with speed Thresholds i wanted to write a value from the serial monitor example 15,26,30 etc... to my eeprom 24LC256. this is my code to upload

byte data_in = 0;

 //data = (int)data_to_convert;

  while(Serial.available() == 0); { 
  data_in = Serial.read();  
 }

Wire.beginTransmission(eeprom);
  Wire.write((int)(0 >> 8));   // MSB
  Wire.write((int)(0 & 0xFF)); // LSB
  Wire.write(data_in);
  Wire.endTransmission();
  delay(5);

  Serial.println("OK");

this doesnt seem to work however if i hard code the value like this it works

byte data_in = 32;
Wire.beginTransmission(eeprom);
  Wire.write((int)(0 >> 8));   // MSB
  Wire.write((int)(0 & 0xFF)); // LSB
  Wire.write(data_in);
  Wire.endTransmission();
  delay(5);

  Serial.println("OK");

So just confused in what i am doing wrong

Thank you

weird...
is the Serial baud rate correct?

Don't post snippets (Snippets R Us!)

PS: code would look better written this way

if (Serial.available() != 0) { 
  byte data_in = Serial.read();
  Wire.beginTransmission(eeprom);
  Wire.write((int)(0 & 0xFF)); // LSB
  Wire.write(data_in);
  Wire.endTransmission();
  Serial.println("OK");
  delay(5);
}

this way you don't block the loop() - if it's in the loop - waiting for data entry.

Note as well that if your serial monitor is sending CR and or LF then whatever comes last will be written

Hi
yeah i am sure the braud rate is correct and i have set the serial monitor to No line ending

Check the topic "Serial basics". Reading a numerical value or reading a byte is done in different ways.

If it makes more sense i am using an Arduino Mega so not sure if thats the problem thats being caused

if you don't share the full code or a minimum example we can't be sure for what's going on.

check with a known library if you got everything wired and working correctly, try this:

#include <I2C_eeprom.h>  // https://github.com/RobTillaart/I2C_EEPROM/blob/master/I2C_eeprom.cpp
I2C_eeprom memory(0x50, I2C_DEVICESIZE_24LC256); // AT24C256 en 0x50

void setup() {
  Serial.begin(115200);
  if (! memory.isConnected()) {
    Serial.println(F("can't find EEPROM"));
    while (true) yield();
  }
}

void loop() {
  if (Serial.available() != 0) {
    byte data_in = Serial.read();
    Serial.print(F("Writing at @0 --W byte 0x")); Serial.println(data_in, HEX);
    memory.updateByte(0, data_in);

    Serial.print(F("Reading at @0 --> 0x")); Serial.println(memory.readByte(0), HEX);
  }
}

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.