Help understand HEX and IF's

I've got a simple Bluetooth program that sends HEX from an android APP.

It either send;
1, 0 or 11 dependant on the button pushed.

I want the three commands to make an IF do something different each time.

In the code below the 0 and 1 options work but not the 11.

I am very new to this and I know this is a fundamental understanding thing but I cant find a simple tutorial to help.

The serial monitor reports the respective 0,1 or 11 with each different button push.

void setup() {
  Serial.begin(9600);
  Serial1.begin(9600);
  pinMode(3, OUTPUT);
}
int state;

void loop() 
{
  if(Serial1.available() > 0)
  {
    state= Serial1.read(); 
    Serial1.write ("Hello"); 
    Serial.println (state, HEX);
  }
    if(state == 0)
     {
       digitalWrite(3, LOW); 
     }
    if(state == 1)
     {
      digitalWrite(3, HIGH); 
     }
    if(state == 11)
     {
      digitalWrite(3, HIGH); 
      delay (1000);
      digitalWrite(3, LOW); 
      delay (1000);
     }
 }

Things work with normal decimal numbers unless you specifically say you’re using something different. Hex numbers are prefixed with 0x as in 0x11. Or you could use 17, the decimal equivalent of 0x11 though that might confuse you when you look at the code later.

Steve

Serial.read () is documented to return a single character. How is it ever going to hold "11" ?
In fact, unless the OP uses control characters, I do not understand how 0 or 1 works.

Steve

I knew it would be a dumb question. So the Int can be either HEX or DEC?

Now when I put the Hex equivalent in the IF it works perfectly!! and the serial monitor does report 0, 01 or 11.

Thanks again

Kev

kpg:
So the Int can be either HEX or DEC?

All values within the processor are binary. Binary, hex, decimal, octal, etc are simply different ways of representing a number. The number's value remains unchanged regardless of how it's represented.

One way to code the hex cases is as follows:

int state_h11 = 0x0011; // 16 bit integer contains 4 hex digits

So in your if statement, you can then just write

if(state == state_h11)

I was surprised that the compiler recognized the the hex symbolism "0x0011" since there are no hex functions in the library, but it does recognize it. :slight_smile:

My other thought is that I'm surprised the Bluetooth program is defining hex values 0, 1, and 11. That is wasting 6 bits. Am surprised they aren't setting bits. But, you got it to work so that must have been what they did.