Serial Data Conversion and Calculation

Morning Guys,

I am sure this is simple, as i am sure i am having some kind of mental block about this :slight_smile:

I am sending characters (programmed in HEX) via Serial, and expecting a long string of characters as a response from a device.

I know i am getting the response, and if i Serial.write(DataLine[21]) into a terminal program that displays as HEX i get 8B. I need to convert 8B to a dec, which would be 139, then divide it by 10 to give a float 13.9. Thats the goal, and i intend to parse the whole string by position in a similar fashion (although math will vary a little)

The issue i am having is no matter what I use, "atoi", "int" i get zeros?? what am i missing. I am attaching the code so that you guys can review and tell me what on earth i am doing wrong...

Really appreciate any help - this is driving me crazy!

char DataLine [185];
char Convert[2];
static unsigned int input_pos = 0;
String inData;



void setup() {

  Serial2.begin(9600, SERIAL_8E1);
  Serial.begin(9600);

  Serial2.write(0xb8);
  Serial2.write(0x31);
  Serial2.write(0xf7);
  Serial2.write(0x02);
  Serial2.write(0x21);
  Serial2.write(0x01);
  Serial2.write(0x5C);
 
}

void loop() { 
 
  if (Serial2.available()) {
    const char recieved = Serial2.read();
    DataLine [input_pos] = recieved;

      if (input_pos == 21)
      {
      Convert[1] = recieved;
      Convert[2] = '/0';
      Serial.println(DataLine[21],HEX);
      Serial.write(Convert);
      Serial.println();
      int number = atoi(Convert);
      Serial.println();
      Serial.print(number);

      }
   input_pos = input_pos + 1;
  }

  
}

Terminating nul character is '\0', not '/0'.

atoi() will not accept A..F; you can use strtol or strtoul.

Note:
read the full number 0x8B into the array, next convert.

Have a look at the examples in Serial Input Basics - simple reliable ways to receive data. There is also a parse example.

...R

Serial.print(DataLine[21], HEX);

If your device already sends 0x8B, you don't have to do anything except for the division.

byte x = 0x8B;
float fl = x / 10.0;

PS
I might have misinterpreted your question earlier; you have now two solutions for slightly different problems :wink:

Actually, on re-reading the original supplied code, I would have written that as

float number = DataLine[21] / 10.0;
Serial.print("Your number is ");
Serial.println(number, 1);

Although that is a pretty stupid name for a variable. If you know what it is for then you should use that description instead of "number".