read serial - hex input

Hi,
I am trying to read serial which is to take a hex input ie. 0xFFFFFF but I seem to only recieve ints. I need the output to be identical to the input. (The 0x prefix is not required, but just assuming it is as declaring hex in the past required me to do that).

What i expect when I send F through serial is F output in hex or 1111 in Bin but instead i recieve a byte that i cant seem to make sense of in bin or dec as i seem to get a 2 digit number (I think this is the ascii code as int).
Or if I send FF i expect 11111111 in bin back and so on.
I have set the variable to hold the read as unsigned long and have also tried int too.

Right now i dont have any code to hand as i am sat in bed, woken up in middle of night and cant stop thinking about this. If someone could also give me a quick crash course on what is actually happening during the serial read too that would be great as it appears i see multiple bytes printed after input. Also I am basically using the example code from arduino guide for serial.read if that helps.

Thanks

My guess is that you're receiving either 70 or 102. The reason is because data from the Serial object is ASCII and 70 is the letter 'F' while 102 is 'f'. You need to convert the ASCII hex codes to numerics.

markyj:
I am trying to read serial which is to take a hex input ie. 0xFFFFFF but I seem to only recieve ints.

Bra, do you know the difference between a byte, char, int, double, float, long, or longlong? Do you know how many bits are in an int (as per Arduino architectures)?

markyj:
Hi,
i recieve a byte that i cant seem to make sense of in bin or dec as i seem to get a 2 digit number (I think this is the ascii code as int).

ASCII codes are always bytes, never ints.

markyj:
Right now i dont have any code to hand as i am sat in bed, woken up in middle of night and cant stop thinking about this.

Post your code and we can figure things out quicker. My guess is that you are using Serial.print() or Serial.println() when you should be using Serial.write(). Like so:

byte variable = 0xFF;
Serial.write(variable);

Hi guys,

Thanks for your input, I went a different option and used Serial.parseInt() which would essentially take in an int and then I can get it as hex later.

For anyone interested and future searches, this is the basic code I went with.

void setup() {
  Serial.begin(9600);   // Start Serial
  Serial.println("start"); // Debug message
}

void loop() {
 unsigned long serialIn; // Set and wipe variable
 
  while (Serial.available() > 0) {
    serialIn = Serial.parseInt(); // Takes in an int
    Serial.print("Serial read: "); // Debug message
    Serial.print(serialIn, HEX); // Print the result in HEX
    Serial.println(""); // Debug message
  }
}