I'm new to Arduino and am learning how Serial communication works. I am trying to send a value from Matlab to Arduino, but it seems to be partly fruitful. If anyone can explain the difference between the acquiring input and predefined strings in Matlab Here is the program I tried, and it is successful. Arduino :
%This program receives an array of chars and stores them in array and transmits them back
const int no_of_fields = 3;
int field_index = 0;
int vec_to_hold[no_of_fields]; //Array to hold the numbers
void setup()
{
Serial.begin(9600);
}
void loop()
{
if(Serial.available())
{
char ch = Serial.read();
if(ch >= '0'&& ch<= '9') //check if the received chars are digits
{
if(field_index<no_of_fields)
{
vec_to_hold[field_index] = (vec_to_hold[field_index] * 10) + (ch -'0'); //accumulate values to form and integer
}
}
else if(ch == ',')
{
field_index++;
}
else if(ch == '\n')
{
for (int i = 0;i<min(no_of_fields,field_index+1);i++)
{
Serial.print(vec_to_hold[i]);
vec_to_hold[i] = 0;
}
Serial.println();
field_index = 0;
}
}
}
Here is the Matlab side of Code :
delete(instrfindall)
S = serial('COM3', 'BaudRate', 9600,'Terminator','LF'); %38400
fopen(S);
pause(0.1);
vec_sent = input('Enter : ','s');
fprintf(S,'%s\n',vec_sent);
pause(0.1);
t_value = fscanf(S,'%d');
disp(t_value);
delete(instrfindall)
The above code is working, but what if i don't want to enter the string. I want to be predefined. For example in the above matlab code
vec_sent = '200,300,400';
If i convert this line
vec_sent = input('Enter : ','s');
to
vec_sent = '200,300,400';
it does not work. The RX pin on the Arduino blinks indicating something is coming on the serial, but TX pin is not at all blinking, and nothing appears in MATLAB except an error stating
Warning: Unsuccessful read: A timeout occurred before the Terminator was reached..
I would be grateful if anybody points out what I am doing wrong. Thanks in advance.