Hi Guys,
I'm having some trouble converting unsigned ints to signed ones.
In my system I am sending serial data to an arduino from a computer. I send a 4 byte command
which is
[ 0 ] 'p' or 's' for position or speed
[ 1 ] pos/speed high byte
[ 2 ] pos/speed low byte
[ 3 ] flag for +ve or -ve
my receiving code on the arduino is:
uint8_t writeval = 1;
uint8_t dir = 0;
uint8_t inputArray[5];
int targetPos = 0;
void loop()
{
int n =0;
if(Serial.available())
{
delayMicroseconds(5000);
while (Serial.available()) {
inputArray[n] = Serial.read();
n++;
delayMicroseconds(500);
}
targetPos = 0;
dir = inputArray[3];
if((dir&0x01))
{
targetPos=static_cast<int>(((uint16_t)inputArray[2])+((uint16_t)(inputArray[1]<<8)))*1;
}
if(!(dir&0x01))
{
targetPos=static_cast<int>(((uint16_t)inputArray[2])+((uint16_t)(inputArray[1]<<8)))*-1;
}
Serial.println(targetPos);
Serial.println(static_cast<int>((uint16_t)(inputArray[1]<<8)));
Serial.println(enc.read());
Serial.println("");
}
Sending:
70 255 253 00
as in position -65533
Gives:
-3
-256
0
Sending:
70 255 253 01
as in position 65533
Gives:
3
-256
0
So it looks like its using the unisgned ints as signed ints in twos compliment. Any pointers?
Thanks