Arduino Matlab Communication

For this project, I want a stepper motor to move in response to the magnetometer. I'm using an Adafruit LSM9DS0 9DOF IMU for this project. I'm programming this in Matlab, using Arduino only to give me the magnetometer data and move the stepper motor.

I've tested many parts of my code individually and they work fine. But when I have them work together, then the stepper motor doesn't move, and in Matlab, the command window shows NaN, and then a timeout warning. Like I said, I've tested and troubleshooted a lot, and I can't find what the problem is.

Can someone tell me what I should do to get this to work? I've done a lot of forum reading, so if you want to give me some advice, please be as clear and specific as you can. Thank you.

Below is my matlab code

fclose(instrfind);
a = serial('com3', 'BaudRate', 115200);
fopen(a);


while 1
    temp = fscanf(a);
    mag = str2double(temp);
    disp(mag);
    flushinput(a);

    steps = pidCtrl_test(mag);
    fprintf(a, num2str(steps));
    while a.BytesAvailable == 0
    end
    fscanf(a);
    flushinput(a);
end

This is a function that works in matlab with the main script above:

function steps = pidCtrl_test(mag)

kP = 1;
ref = -0.20;
if isnan(mag) || mag > 1
        mag = 0;
end
err = ref - mag;
err = err*kP;
err = err*100;
steps = round(err);

northTracker_test.ino (1.11 KB)

Forget Matlab for the moment. Does your code work properly when you send data using the Serial Monitor app? If so, the problem is not the Arduino code.

If not, you need to define what you send, and what the Arduino actually does. "It doesn't work" doesn't provide any useful information.