MATLAB: Send SERIAL commands from MATLAB GUI to Arduino

arduinoarduino matlab gui serialarduino matlab serialmakerMATLABmatlab arduino guimatlab guimatlab gui serialmatlab serialmatlab-arduino serial

Hey all,
I am working on making a GUI that takes in Three(3) 'int' values from the user separated by commas (i.e. 1000,1000,1000) and sends that entire string through the COM port to the Arduino which uses those 3 int values as the delay() time input for each of the 3 LEDs.
I have it working to the point where:
1) the user can select the COM port from the GUI that the Arduino is connected to
2) user can enter the 3 'int' values into a "edit text" box separated by commas as mentioned above
3) then the GUI code retrieves that string and saved it to a variable called: xyz
4) using the command fprintf(s,xyz), where "s" is the serial object, the value of xyz is sent to the Arduino without any errors
5) the Arduino "RX" led blinks indicating the value from serial port has been received
— now the problem is that Arduino is not doing anything with the received serial input from matlab! if I used the Arduino IDE's Serial Monitor to send 1000,1000,1000 it does what its suppose to!
So I am thinking Arduino doesn't like the "data type"/"format" of the value im sending through the matlab GUI and I am not sure how to fix this…!
I am a newbie with programing/arduino/matlab so please excuse any novice mistakes. ANY help will be greatly appreciated!!
Below is the TEST Arduino Code and the MATLAB GUI Code:
Thank you guys in advanced!!!
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Relevant MATLAB GUI CODE:
function stepInput_Callback(hObject, eventdata, handles)
xyz = get(hObject,'String');
disp('Value entered: ')
disp(xyz)
global COM;
global s;
s = serial(COM,'BaudRate',9600);
fopen(s);
disp('After OPEN')
disp(s)
fprintf(s,xyz);
fclose(s);
disp('After CLOSE')
disp(s)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Arduino Code:
int x;
int y;
int z;
void setup() {
pinMode(2,OUTPUT);
pinMode(6,OUTPUT);
pinMode(10,OUTPUT);
Serial.begin(9600);
}
void loop() {
while (Serial.available()) // check if Serial data is available to read
{
x = Serial.parseInt();
y = Serial.parseInt();
z = Serial.parseInt();
if (Serial.read() == '\n') // check if ENTER has been pressed (newline)
{
digitalWrite(2,1);
delay(x);
digitalWrite(6,1);
delay(y);
digitalWrite(10,1);
delay(z);
digitalWrite(10,0);
delay(z);
digitalWrite(6,0);
delay(y);
digitalWrite(2,0);
delay(x);
}
}
}

Best Answer

I would delete the while.serial from arduino code and do it as:
void loop()
{
if (Serial.available()>0)
{
my_data = Serial.read();
...
}
] // end loop()
Since you open the serial port every time you want to send anything and close it again, it will take some time to perform the operation. Did you try to add a connect/disconnect button in your GUI to perform that operation so that the data is sent straight away once it is introduced by the user?
Related Question