Search code examples
c++matlabserial-communication

What is the C++ equivalent to this MATLAB code?


In my project, I am responsible for migrating some MATLAB code to C++. The code below refers to serial communication from a computer to a microcontroller. The function CreatePackage generates a package which is then sent to the microcontroller using MATLAB's fwrite(serial) function.

function package = CreatePackage(V)
for ii = 1:size(V,2)
    if V(ii) > 100
        V(ii) = 100;
    elseif V(ii) < -100
        V(ii) = -100;
    end
end

vel = zeros(1, 6);
for ii = 1:size(V,2)
    if V(ii) > 0
        vel(ii) = uint8(V(ii));
    else
        vel(ii) = uint8(128 + abs(V(ii)));
    end
end

package = ['BD' 16+[6, vel(1:6)], 'P' 10 13]+0;

And then, to send the package:

function SendPackage(S, Package)

for ii = 1:length(S)
    fwrite(S(ii), Package);
end

How can I create an array/vector in C++ to represent the package variable used in the MATLAB code above?

I have no experience with MATLAB so any help would be greatly apreciated.

Thank you!


Solution

  • The package variable is being streamed as 12, unsigned 8-bit integers in your MATLAB code, so I would use a char[12] array in C++. You can double check sizeof(char) on your platform to ensure that char is only 1 byte.

    Yes, MATLAB default data-type is a double, but that does not mean your vector V isn't filled with integer values. You have to look at this data or the specs from your equipment to figure this out.

    Whatever the values are coming in, you are setting/clipping the outgoing range to [-100, 100] and then offsetting them to the byte range [0, 255].

    If you do not know a whole lot about MATLAB, you may be able to leverage what you know from C++ and use C as an interim. MATLAB's fwrite functionality lines up with that of C's, and you can include these functions in C++ with the #include<cstdio.h> preprocessor directive.

    Here is an example solution:

    #include <cstdio.h>    // fwrite 
    #include <algorithm>  // min, max
    ...
    
    void makeAndSendPackage(int * a6x1array, FILE * fHandles, int numHandles){
    
       char packageBuffer[13] = {'B','D',24,0,0,0,0,0,0,'P','\n','\r',0};
    
       for(int i=0;i<6;i++){
           int tmp = a6x1array[i];
           packageBuffer[i+3] = tmp<0: abs(max(-100,tmp))+144 ? min(100,tmp)+16;
       }
    
       for(int i=0;i<6;i++){
           fwrite(fHandles[i],"%s",packageBuffer);
       }
    
    }
    

    Let me know if you have questions about the above code.