Dealing with Hex

Hello,

I am trying to write a code to control a motor controller using the CanOpen protocol.
For the motor command I am using a pot that is going to mapped like this:
0, 1023, -1000, 1000
Being -1000 full reverse and 1000 full forward.
Now I have to convert the command value into an hex value, if we take the example of the full reverse value (-1000) into hex it will be something like 0xFFFFFC71, so far so good, now I have to take that hex value and seperate it into byte values because it has to be sent like this:
0x71 0xFC 0xFF 0xFF (byte4, byte5, byte6, byte7)

If it is the full forward (0x3E8) it will be like this:
0xE8 0x03 0x00 0x00

How can I do it seperate the long hex value into seperate bytes?
Any example code I can use?

Thanks

Regards

Please supply a link to the motor controller.

Hi,

I don't see why would you want to have it, I have explained all I need, is just the way to deal with hex values...

But I am attaching a picture of the manual just in case

Btw, it is a roboteq motor controller, the CanOpen protocol can be found in any user manual of a compatible controller from RoboteQ

Cheers

Use a union.
Use shifts.
Use a byte array.

int32_t x = -1000;
Serial.write((uint8_t*)&x, sizeof(x));

Something like that?

Keep in mind that Arduino is Little Endian, so the least significant bytes will be sent first (which seems to be what you want.

Pieter

Here is how to do it with a union.

union ctrlUnion
{
  long ctrlLong;
  byte ctrlBytes[4];
};

ctrlUnion ctrl;

void setup() 
{
  ctrl.ctrlLong = 0xffeda976;
  Serial.begin(115200);
  Serial.print("long version ");
  Serial.println(ctrl.ctrlLong, HEX);
  for(int n = 0; n < 4; n++)
  {
    Serial.print("byte ");
    Serial.print(n);
    Serial.print(" = ");
    Serial.println(ctrl.ctrlBytes[n], HEX);
  }
}

void loop()
{
}

Then send the 4 bytes in the order required.

Thank you for your code groundfungus, it almost worked well until I tested with a shorter hex value like "0x3E8", it gave me this result:
long version 3E8
byte 0 = E8
byte 1 = 3
byte 2 = 0
byte 3 = 0

When I should have this:

long version 3E8
byte 0 = E8
byte 1 = 03
byte 2 = 00
byte 3 = 00

Any suggestion of what must be changed on the code to get the right values?

Thanks

There is no difference between 3 whether is is written as decimal (3), hex (0x3) or octal (03).

What is the problem?

Like AWOL said, there's no difference. What do you need the text representation for any way?

What is the point of converting into HEX values to begin with? HEX representation is for humans to read.

All numbers in a computer are binary.

You are all right about it... I am really new to this hex things and to arduino coding in general.

My problem is solved thanks to you all
Thanks a lot guys

Cheers