serial data communication between Matlab and Arduino

6 views (last 30 days)
Hi,
I have an example of serial data communication between Matlab and Arduino. I'm trying to write this code in Matlab but it's seems it's not right.
Here's Arduino code:
// Create a union to easily convert float to byte
typedef union{
float number;
uint8_t bytes[4];
} FLOATUNION_t;
// Create the variables you want to receive
FLOATUNION_t myValue1;
FLOATUNION_t myValue2;
FLOATUNION_t myValue3;
FLOATUNION_t myValue4;
FLOATUNION_t myValue5;
FLOATUNION_t myValue6;
// Create the variables to send
FLOATUNION_t send1;
FLOATUNION_t send2;
FLOATUNION_t send3;
void setup() {
// initialize serial, use the same boudrate in the Simulink Config block
Serial.begin(115200);
}
void loop(){
// Get the floats from serial
myValue1.number = getFloat(); // Give your float a value
myValue2.number = getFloat(); // Give your float a value
myValue3.number = getFloat(); // Give your float a value
myValue4.number = getFloat(); // Give your float a value
myValue5.number = getFloat(); // Give your float a value
myValue6.number = getFloat(); // Give your float a value
// Send some variables back
send1.number = myValue1.number+myValue2.number;
send2.number = myValue3.number+myValue4.number;
send3.number = myValue5.number+myValue6.number;
// Print header: Important to avoid sync errors!
Serial.write('A');
// Print float data
for (int i=0; i<4; i++){
Serial.write(send1.bytes[i]);
}
for (int i=0; i<4; i++){
Serial.write(send2.bytes[i]);
}
for (int i=0; i<4; i++){
Serial.write(send3.bytes[i]);
}
// Print terminator
Serial.print('\n');
// Use the same delay in the Serial Receive block
delay(50);
}
float getFloat(){
int cont = 0;
FLOATUNION_t f;
while (cont < 4 ){
f.bytes[cont] = Serial.read() ;
cont = cont +1;
}
return f.number;
}
And here's Matlab Code, which doesn't see correct:
clear
clc
close all
newobjs = instrfind;
fclose(newobjs);
s=serial('COM5','BaudRate',115200);
fopen(s);
readData=fscanf(s); %reads "Ready"
writedata=uint16(500); %0x01F4
fwrite(s,writedata,'uint16') %write data
readData=fscanf(s);
fclose(s);
delete(s);
Can you help me to this code? I've attached its simulink model here for more information.
Thanks!

Answers (0)

Categories

Find more on MATLAB Support Package for Arduino Hardware in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!