Description
I have tried your code to control a stepper motor through matlab, but I have a problem where the motor keeps running away all the time turns out the getFloat() keeps returning a inf number when not connected to anything. Im not sure where my problem lies here are the code that I used to recreate the problem.
`// 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
Serial1.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
// Do whatever you want here
Serial1.println(myValue1.number);
Serial1.println("GAE");
//Serial1.println(myValue1);
// 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!
Serial1.write('A');
// Print float data
for (int i=0; i<4; i++){
Serial1.write(send1.bytes[i]);
}
for (int i=0; i<4; i++){
Serial1.write(send2.bytes[i]);
}
for (int i=0; i<4; i++){
Serial1.write(send3.bytes[i]);
}
// Print terminator
Serial1.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] = Serial1.read() ;
cont = cont +1;
}
return f.number;
}`