Hello, I am using my Arduino to power a stepper motor and I am using Matlab to interface with the Serial port. I would like to read in integers with multiple digits into the serial port, like 78 or 234. I understand that the Serial.read() function in the Arduino environment reads integers in from the Serial port one at a time and hopefully my code makes up for that:
int value() {
int val [] = { 0, 0, 0 };
int n = 0;
while( Serial.available() > 0 && n <= 2)
//Serial.available() > 0 && n == 2)
{
val[n] = Serial.read();
val[n] -=48;
n++;
}
if (val[0] > 0 && val[1] > 0 && val[2] > 0) {
val[0] *= 100;
val[1] *= 10;
}
else if (val[0] > 0 && val[1] > 0 && val[2] < 0 ) {
val[0] *= 10;
val[2] = 0;
}
else if (val[0] > 0 && val[1] < 0 ) {
val[1] = 0;
val[2] = 0;
}
return new_val;
}
the matlab code looks like:
s = serial('COM3');
data = 15; % Number of times to blink. Currently only 0-9 supported.
fclose(s);
%clear all;
%s = serial('/dev/tty.usbmodemfd111');
s.BaudRate=9600;
s.ReadAsyncMode = 'continuous';
s.BytesAvailableFcnMode = 'byte';
%s.TimerPeriod=1;
%set(s,'Timeout',600);
s.Terminator='CR';
try
fopen(s);
s.BytesAvailable
display('Opened')
fscanf(s);
display('Scanned')
fprintf(s, '%d', data);
% fprintf(s, '*IDN?');
s.BytesAvailable
%fscanf(s, '%d')
%out = fscanf(s,'%d');
display('Sent')
fclose(s);
display('Closed')
catch problem
% fclose(s);
display('Problem Caught')
end
I am running into a very important problem. The stepper motor runs fine when I tell it to rotate 0-9 steps, but when I tell it to run 10 or more steps, it messes up! It turns out it adds up the digits and moves that many times around. I guess this is how Serial.read() works, right? It takes all of the numbers it recieves and adds them up and spits it back out? How do you get it to stop doing that?
I tried on Matlab's end to turn the number into a string, but I ended up with the same result. I also tried different data types with no avail.
How can I fix this problem?