0

I'm trying to display values received from serial but Matlab doesn't accept decimal numbers results. I would like to receive A=0.123 from a device, the values is multiplied by 1000 and then sent via serial to matlab.

The matlab script receives 123 but when that number is divided in order to get the original value, matlab shows 0.

consRollKpTemp = typecast([uint8(mess(typei + 1)), uint8(mess(typei + 2)),uint8(mess(typei + 3)), uint8(mess(typei + 4))], 'int32');
disp(consRollKpTemp);
consRollKp = consRollKpTemp/1000;
disp(consRollKp);

Which returns

consRollKpTemp:
         123    
consRollKp:
           0

I thought the problem was the typecast(X,type) function which

converts a numeric value in X to the data type specified by type.

and I changed it to:

consRollKpTemp = typecast([uint8(mess(typei + 1)), uint8(mess(typei + 2)),uint8(mess(typei + 3)), uint8(mess(typei + 4))], 'single');

But nothing changed. I've tried the suggestions in this question and here but they didnt' work.

Community
  • 1
  • 1
UserK
  • 884
  • 3
  • 17
  • 40

1 Answers1

3

The problem is that you are using int32 as type, i.e. you only have integer numbers and 0.23 is correctly rounded to 0. Try to cast the variable consRollKp to double before dividing it by 1000:

consRollKp = double(consRollKpTemp) / 1000;

To clarify: Using typecast with single will not work. Typecast converts data types without changing the underlying data. As single is a floating point number and uint8 and int32 are integer types, a typecast between those will not lead to the desired results.

Try to typecast to int32 (or probably uint32) and in a second step use dobule() or single() to convert this variable to a floating point type. Finally you should be able to divide by 1000 and get the correct result.

hbaderts
  • 14,136
  • 4
  • 41
  • 48