[SOLVED] Convert random number to HEX command

Hello, I’m struggling with this for a while now and hoping you all can shed some light on what I’m missing. I’m trying to send a command to my catalex MP3 player like this:

sendCommand(CMD_PLAY_FOLDER, 0x040B);// This plays track 11

The last two characters of the command (‘0B’ in this case) are to be a random number. So I need to append the random number to ‘0x04’ and send the command in HEX to the player. This is what I’ve tried:

void setup()
{
 randomNumber=11;  //I've eliminated the random function for testing purposes
hextoPlay = strtoul(randomNumber,NULL,16);  //convert random number to Hex
 sprintf(toPlay, "04%i", randomNumber);  //append the command to the random number, output is a string
 Serial.println(toPlay);  //This outputs '0411'
 sendCommand(CMD_PLAY_FOLDER, hexPlay);  //This is what I would like to send 
  delay(5000);
}

void sendCommand(int8_t command, int16_t dat)
{
  delay(20);
  Send_buf[0] = 0x7e; //starting byte
  Send_buf[1] = 0xff; //version
  Send_buf[2] = 0x06; //the number of bytes of the command without starting byte and ending byte
  Send_buf[3] = command; //
  Send_buf[4] = 0x00;//0x00 = no feedback, 0x01 = feedback
  Send_buf[5] = (int8_t)(dat >> 8);//datah
  Send_buf[6] = (int8_t)(dat); //datal
  Send_buf[7] = 0xef; //ending byte
  Serial.print("Sending: ");
  for(uint8_t i=0; i<8; i++)//
  {
    mySerial.write(Send_buf[i]) ;
    Serial.print(sbyte2hex(Send_buf[i]));
  }
  Serial.println();
}

Can anyone suggest how to do this?

So I need to append the random number to '0x04' and send the command in HEX to the player.

No, you don't want to do that, because the compiler converts 0x040B to a binary value, which is then communicated to the function.

Hint:

int track=11;
sendCommand(CMD_PLAY_FOLDER, 1024+track);// This plays track 11

If you want to format a random track number in ASCII hex representation as a C-string, then the following should work:

sprintf(toPlay,"0x04%02X",randomNumber);//where randomNumber is a byte

Or avoid loading the large package sprintf() as follows (untested):

char tmp1[10]="0x04",tmp2[10]={0};
itoa(randomNumber,tmp2,16); //randomNumber is a byte
strcat(tmp1,tmp2);
Serial.println(tmp1);

Here is a hint. 0x040B is exactly the same as 0x0400 + 11.

Don't worry about the fact that it was written in hexadecimal. It's just a number and it has the same value no matter how you choose to write it and it will be seen as binary by the processor no matter how you choose to write it.

jremington and Delta_G,thank you for your quick reply! This is exactly what I was stuck on:

No, you don't want to do that, because the compiler converts 0x040B to a binary value, which is then communicated to the function.

Thanks for clarifying, I'm now using this

int track=11;
sendCommand(CMD_PLAY_FOLDER, 1024+track);// This plays track 11