MATLAB Answers

how to control stepper motor speed via USB port

15 views (last 30 days)
i really need some help over here..i have connected and run my stepper motor but how come i cannot control the speed of my motor?..can someone give me some hints?
below are my coding:
function text_speed_m1_Callback(hObject, eventdata, handles)
sliderValue = get(handles.text_speed_m1,'String');
%convert from string to number if possible, otherwise returns empty
sliderValue = str2nm(sliderValue);
%if user inputs something is not a number, or if the input is less than 0
%or greater than 100, then the slider value defaults to 0
if (isempty(sliderValue) || sliderValue < 0 || sliderValue > 256)
set(handles.slider_speed_m1,'Value',0);
set(handles.text_speed_m1,'String','0');
else
set(handles.slider_speed_m1,'Value',sliderValue);
end
% --- Executes during object creation, after setting all properties.
function text_speed_m1_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on slider movement.
function slider_speed_m1_Callback(hObject, eventdata, handles)
sliderValue = get(handles.slider_speed_m1,'Value');
%puts the slider value into the edit text component
set(handles.text_speed_m1,'String', num2str(sliderValue));
% Update handles structure
guidata(hObject, handles);
% --- Executes on button press in pushbutton_speed_m1.
function pushbutton_speed_m1_Callback(hObject, eventdata, handles)
obj1 = instrfind('Type','serial','Port','COM8','Tag','');
if isempty(obj1)
obj1 = serial('COM8');
else
fclose(obj1);
obj1 = obj1(1)
end
fopen(obj1);
sv2 = get(handles.text_speed_m1,'String');
fprintf(obj1,'%s','rs')
fprintf(obj1,int2str(get(hObject,'Value')));
please give me some hints on what i do wrong..really need help now..thanks

  1 Comment

Walter Roberson
Walter Roberson on 27 Mar 2011
Please reformat your code to be more readable. If you go in to the editor and select the code and press the '{} Code' button then it will be reformatted.
Please also check that the code output is what you wanted. For example one of your lines shows up as "if (isempty(sliderValue) sliderValue < 0 sliderValue > 256)" which is invalid syntax. I suspect that you had or-bar there but that your or-bar was interpreted by the forum as formatting instructions.

Sign in to comment.

Accepted Answer

Walter Roberson
Walter Roberson on 27 Mar 2011
We can't tell why you cannot control the speed of the motor. You have not described what happens when you try.
Closing and reopening the serial port each time is not advisable. If you find a serial port and it is open, then you should use it.
In your code, if obj1 is empty after the instrfind, then when you associate the serial port with obj1, you have omitted setting anything like port speed. The default probably is not what you want; even if it happens to be, other people reading your code are going to be left wondering and the defaults might change in other versions, so it is better to set port characteristics explicitly.

  0 Comments

Sign in to comment.

More Answers (17)

fremond khoo
fremond khoo on 27 Mar 2011
thanks walter for the advice, i have altered my coding but the error is still there..
function text_speed_m1_Callback(hObject, eventdata, handles)
val = str2num (get(handles.text_speed_m1,'String'));
set(handles.slider_speed_m1,'Value',val);
%convert from string to number if possible, otherwise returns empty
sliderValue = str2num(sliderValue);
%if user inputs something is not a number, or if the input is less than 0
%or greater than 100, then the slider value defaults to 0
if (isempty(sliderValue) || sliderValue < 0 || sliderValue > 256)
set(handles.slider_speed_m1,'Value',0);
set(handles.text_speed_m1,'String','0');
else
set(handles.slider_speed_m1,'Value',sliderValue);
end
% --- Executes during object creation, after setting all properties.
function text_speed_m1_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on slider movement.
function slider_speed_m1_Callback(hObject, eventdata, handles)
val = get(handles.slider_speed_m1,'Value');
set(handles.text_speed_m1,'String',num2str(val));
obj1 = instrfind('Type','serial','Port','COM9','Tag','');
if isempty(obj1)
obj1 = serial('COM8');
fopen(obj1);
fprintf(obj1,'%s\n','S');
end
fclose(obj1);
%puts the slider value into the edit text component
set(handles.text_speed_m1,'String', num2str(sliderValue));
% Update handles structure
guidata(hObject, handles);
the error shown when i move the slider is:
??? Error using ==> serial.fopen at 72
Port: COM8 is not available. Available ports: COM3.
Use INSTRFIND to determine if other instrument objects
are connected to the requested device.
Error in ==> GUI_xyplotter>slider_speed_m1_Callback at
479
fopen(obj1);
Error in ==> gui_mainfcn at 96
feval(varargin{:});
Error in ==> GUI_xyplotter at 16
gui_mainfcn(gui_State, varargin{:});
Error in ==>
@(hObject,eventdata)GUI_xyplotter('slider_speed_m1_Callback',hObject,eventdata,guidata(hObject))
??? Error while evaluating uicontrol Callback
and can i ask what do you mean by "invalid syntax"?

  6 Comments

Show 3 older comments
fremond khoo
fremond khoo on 27 Mar 2011
i tried..i can connect to COM8..i connected and run my motor in clockwise and anticlockwise direction but when i want to change the speed of the motor by changing the slider value, the same error occured..i think there is a problem with my speed control coding but i don't know where the problem lies..
i am using stepper motor..is there a special way for stepper motor coding?
fremond khoo
fremond khoo on 28 Mar 2011
can someone teach me how to solve this problem?..im really short of time..really hope to get some advices and help..
Walter Roberson
Walter Roberson on 28 Mar 2011
Doesn't this case correspond to you closing the existing port and opening it again? Or did you remove that code?

Sign in to comment.


fremond khoo
fremond khoo on 29 Mar 2011
Mr walter, my senior give me another different code to control the speed by using decimal to binary code such as this:
% --- Executes on button press in pushbutton_speed_m1.
function pushbutton_speed_m1_Callback(hObject, eventdata, handles)
sv2 = get(handles.text_speed_m1,'String');
a = dec2bin(83,8);
b = dec2bin(sv2);
c = [a b];
fwrite(obj1,c,'int16')
but when i try to execute the pushbutton to set the speed, a different error occur:
??? Error using ==> horzcat
CAT arguments dimensions are not consistent.
Error in ==> GUI_xyplotter>pushbutton_speed_m1_Callback
at 614
c = [a b];
Error in ==> gui_mainfcn at 96
feval(varargin{:});
Error in ==> GUI_xyplotter at 16
gui_mainfcn(gui_State, varargin{:});
Error in ==>
@(hObject,eventdata)GUI_xyplotter('pushbutton_speed_m1_Callback',hObject,eventdata,guidata(hObject))
i dun quite understand the function of dec2bin(83,8) means and what is the error of this codes..can you help me?..thanks

  3 Comments

Walter Roberson
Walter Roberson on 29 Mar 2011
That code seems highly unlikely to work, but here is the code you would need to change:
b = dec2bin(sv2,8);
c = reshape([a;b] .', 1, []);
I would be startled fwrite(obj1,c,'int16') produces the result you are hoping for. Please re-check to see whether your senior had a bin2dec() call after c was created. Please also recheck to see if your senior converted a 10 (linefeed) or 13 (carriage return)
Your senior's code seems to be created with the idea that you send 'S' followed by a _single_ character to indicate the speed, except that the code doesn't actually do that.
Are you aware that in your original code, you do not send any value derived from the slider after the 'S'? You carefully build "val" but do not sent it to the COM port.
Please cross-check exactly what format of numbers the motor control expects. I do not see anything in your code that would restrict val to being an integer. With the range of values you are restricting to, and the code your senior provides, I wonder whether what the motor control is expecting is 'S' followed by a single byte whose decimal equivalent is the number of 1/255 of full speed -- e.g., byte value 0 for stop, byte value 128 for half speed, byte value 255 for full speed. If so then your senior's code starts to hint at some sense (but would still not be correct in the form posted.)
fremond khoo
fremond khoo on 31 Mar 2011
im sorry walter for the late reply..i have been busying with the assembly and modifications of my robot arm..
i have checked my senior code..he does not have a bin2dec() call after c was created..his code is simply based on what i have shown above..btw i have changed the
b = dec2bin(sv2,8);
c = reshape([a;b] .', 1, []);
but still nothing happens..can you enlighten me more? and about the 'S' to control motor speed..my senior said he took from a VB source code saying the command 'S' is supposed to control the speed of the motor. Like command 'B' is the command for brake..How should i write my coding to make sure i can control my motor speed based on my senior code?..i have altered some parts of my senior code but still no luck..once again, really hope can get some help from you..
thanks a lot for your time
Walter Roberson
Walter Roberson on 31 Mar 2011
Is there a reference document that discusses the command format expected by the motor?

Sign in to comment.


fremond khoo
fremond khoo on 31 Mar 2011
actually i dont have any reference document that discusses the command format expected by the motor..but i have the coding of visual basic which i got from my senior..he said he refer to that code to run his motor..
the code is:
Private Sub hsbSPEED_scroll( _
ByVal sender As Object, ByVal e As System.EventArgs) _
Handles hsbSpeed.Scroll
txtSpeed.Text = CStr(hsbSpeed.Value)
data(0) = CByte(hsbSpeed.Value)
SerialPort.Write("S")
SerialPort.Write(data, 0, 1)
End Sub
i used the visual basic code to control my stepper motor speed and it work well..so, walter does this code means anything?

  4 Comments

Show 1 older comment
fremond khoo
fremond khoo on 1 Apr 2011
thanks once again walter:)..i have set my slider value to a top value of 255..and i have successfully control my motor speed..thanks once again walter..u have been a great help..cheers!!..now i can move on to the next step..thanks
fremond khoo
fremond khoo on 1 Apr 2011
walter..i want to ask how do you know what code to write after looking at the visual basic coding which i paste above?..how do you convert them into matlab coding?..can you teach me about that?..
Walter Roberson
Walter Roberson on 1 Apr 2011
It was through experience, Fremond. Without looking it up, I could see that CByte was obviously a "convert to byte" call, and the matlab equivalent of converting to byte is uint8()

Sign in to comment.


fremond khoo
fremond khoo on 2 Apr 2011
oh..i understand now..so if i want to track my encoder value is also the same right?..the visual basic code is around the same with controlling the speed..
Private Sub btnTrack_Click( _
ByVal sender As System.Object, ByVal e As System.EventArgs) _
Handles btnTrack.Click
data(0) = CByte((CLng(nudTrack.Value) >> 8) And &HFF) 'High byte
data(1) = CByte(CLng(nudTrack.Value) And &HFF) 'Low byte
SerialPort.Write("T")
SerialPort.Write(data, 0, 2)
End Sub

  5 Comments

Show 2 older comments
Walter Roberson
Walter Roberson on 3 Apr 2011
No, after you have obtained t1,
tval16 = uint16(t1);
tval16H = tval16 / 256;
tval16L = tval16 - tval16H * 256;
fwrite(obj1, [uint8('T'), uint8(tval16H), uint8(tval16L)])
In particular uint8(t1) is _not_ right for extracting the top 16 bits from t1: uint8(t1) when t1 is more than 255 would result in the 8 bit value 255.
fremond khoo
fremond khoo on 4 Apr 2011
thanks walter..really thanks a lot..cheers!!
Walter Roberson
Walter Roberson on 7 Apr 2011
In the above,
t1 = num2str(get(handles.text_track_m1,'String'));
should instead be
t1 = str2num(get(handles.text_track_m1,'String'));
or one of its equivalents. str2double() is better than str2num()

Sign in to comment.


fremond khoo
fremond khoo on 6 Apr 2011
im sorry walter..i got another thing to ask you..i have asked my senior and he also dun knw how to program for this..I dun knw how to write the condition for this microstepping process..i need to change the microstep to 1/10 means 0.18 degree per step for my motor..can u help me?..thanks
here is the code:
Private Sub btnMstep_Click( _
ByVal sender As System.Object, ByVal e As System.EventArgs) _
Handles btnMstep.Click
If cbbMicroStep.Text = "None (1 / 1)" Then
data(0) = CByte(1)
ElseIf cbbMicroStep.Text = "1 / 2" Then
data(0) = CByte(2)
ElseIf cbbMicroStep.Text = "1 / 5" Then
data(0) = CByte(5)
ElseIf cbbMicroStep.Text = "1 / 10" Then
data(0) = CByte(10)
End If
SerialPort.Write("M")
SerialPort.Write(data, 0, 1)
End Sub
End Class

  3 Comments

Walter Roberson
Walter Roberson on 6 Apr 2011
stepfactors = [1 2 5 10];
t1 = get(handles.WHATEVER, 'String');
[tf, idx] = strcmp(t1, {'None (1 / 1)', '1 / 2', '1 / 5', '1 / 10'});
if tf
stepfactor = stepfactors(idx);
fwrite(obj1, [uint8('M') uint8(stepfactor)];
else
%warn about the text not being what was expected
end
This code gets even easier if the text such as 'None (1 / 1)' are the entries for a listbox: in such a case, just get the 'Value' parameter from the handle, and as long as it is non-zero, it will be the index into the stepfactors array.
fremond khoo
fremond khoo on 7 Apr 2011
walter..i changed into using listbox but got error:
??? Error using ==> strcmp
Too many output arguments.
Error in ==> GUI_xyplotter>pushbutton_ms_m2_Callback at
641
[tf,idx]=strcmp(M2,{'None(1/1)','1/2','1/5','1/10'});
Error in ==> gui_mainfcn at 96
feval(varargin{:});
Error in ==> GUI_xyplotter at 16
gui_mainfcn(gui_State, varargin{:});
Error in ==>
@(hObject,eventdata)GUI_xyplotter('pushbutton_ms_m2_Callback',hObject,eventdata,guidata(hObject))
??? Error while evaluating uicontrol Callback
what it means?..too much output argument?
Walter Roberson
Walter Roberson on 7 Apr 2011
Sorry, I misused strcmp. I should have written
tf = strcmp(t1, {'None (1 / 1)', '1 / 2', '1 / 5', '1 / 10'});
if any(tf)
stepfactor = stepfactors(idx);
fwrite(obj1, [uint8('M') uint8(stepfactor)];
else
%warn about the text not being what was expected
end
With a listbox, you would use this as the body of the callback:
stepfactors = [1 2 5 10];
idx = get(hObject,'Value');
if ~isempty(idx)
stepfactor = stepfactors(idx);
fwrite(obj1, [uint8('M') uint8(stepfactor)];
end

Sign in to comment.


fremond khoo
fremond khoo on 7 Apr 2011
did i write the wrong code?..
fopen(obj2);
L2 = [1 2 5 1 0];
M2=get(handles.listbox2,'String');
[tf,idx]=strcmp(M2,{'None(1/1)','1/2','1/5','1/10'});
if tf
stepfactor=L2(idx);
fwrite(obj1,[uint('M') uint8(L2)]);
else
fprintf('Sorry,unable to microstep');
end

  5 Comments

Show 2 older comments
Walter Roberson
Walter Roberson on 7 Apr 2011
I don't see any reason why you couldn't send Track commands to two different ports.
fremond khoo
fremond khoo on 7 Apr 2011
i know why already..because i do not know the encoder value so i could not track the movement of the motor..i used the C++ code to find the encoder value but the value comes out to be a very large number..something like 2000 then to 8000..When i put the track value to be 3500 the motor will stop exactly at that number..
i have converted the 'receive encoder' code to matlab code..i try to run it..matlab shows no error but unfortunately there is no value comes out from my textbox..did i set the wrong code?
fremond khoo
fremond khoo on 7 Apr 2011
erm..wait for a while walter..i try to edit the code again first^^

Sign in to comment.


fremond khoo
fremond khoo on 7 Apr 2011
Im sorry walter..in the end..i still cant change the code from C++ to matlab form..i try the same way like tracking command..but i used fscanf to get the data and want to put the value in the edit textbox..the code is around the same like track function:
Private Sub btnAcquire_Click( _
ByVal sender As System.Object, ByVal e As System.EventArgs) _
Handles btnAcquire.Click
SerialPort.Write("E")
Dim recH As Integer = ((SerialPort.ReadByte() << 8) And &HFF00) 'High byte
Dim recL As Integer = (SerialPort.ReadByte() And &HFF) 'Low byte
txtEncoder.Text = CStr(recH Xor recL) 'Combined to a 16 bits value
End Sub
can i again ask too much of your help walter?

  3 Comments

Walter Roberson
Walter Roberson on 7 Apr 2011
fwrite(obj1,uint8('E'));
t = fread(obj1,2,'uint8');
output = uint16(t(1)) * 256 + uint16(t(2));
A literal translation of the original code would require using char(output) instead of output as a 16 bit integer, but I suspect that the numeric form is what you want.
fremond khoo
fremond khoo on 7 Apr 2011
can i ask what does it mean by
t=fread(obj1,2,'uint8');
what does the number '2' define?
Walter Roberson
Walter Roberson on 7 Apr 2011
The 2 means to read two items; each item will be of type uint8.

Sign in to comment.


fremond khoo
fremond khoo on 7 Apr 2011
thanks a lot Mr walter..i can acquire encoder value already but how to track the encoder value to stop the motor..the code is:
function text_track_m2_Callback(hObject, eventdata, handles)
% --- Executes on button press in track_m2.
function track_m2_Callback(hObject, eventdata, handles)
obj2 = instrfind('Type','serial','Port','COM9','Tag','');
if isempty(obj2)
obj2 = serial('COM9');
end
fopen(obj2);
t2 = get(handles.text_track_m2,'String');
tval16 =uint16(t2);
tval16H = tval16/256;
tval16L = tval16-tval16H*256;
fwrite(obj2,[uint8('T'),uint8(tval16H),uint8(tval16L)]);
did i define something wrong?

  4 Comments

Show 1 older comment
fremond khoo
fremond khoo on 8 Apr 2011
yeah..you are right walter..i missed the str2double part..thanks a lot for your help walter^^..Walter..now that im able to track my encoder value but will i be able to change the encoder value to theta value?
i mean how can i change the encoder value to theta value (0-180 degree)?..i mean if i press a theta value in the edit textbox (text_track_m2) will the motor be able to read the theta value and stop moving?..
Walter Roberson
Walter Roberson on 8 Apr 2011
Insufficient information. No correspondence has been documented between angles and the values sent for the 'T' command.
fremond khoo
fremond khoo on 8 Apr 2011
ic..ok..thanks a lot walter for your help..i will try to find out more info in the mean time..thanks^^..

Sign in to comment.


fremond khoo
fremond khoo on 8 Apr 2011
im sorry walter..i face some sort of malfunction when trying to receive the encoder value for motor 2..my coding format follows exactly like motor 1 but somehow it comes out this error:
Warning: The specified amount of data was not returned
within the Timeout period.
??? Attempted to access t(1); index out of bounds
because numel(t)=0.
Error in ==> GUI_xyplotter>request_m2_Callback at 569
output=uint16(t(1))*256+uint16(t(2));
Error in ==> gui_mainfcn at 96
feval(varargin{:});
Error in ==> GUI_xyplotter at 16
gui_mainfcn(gui_State, varargin{:});
Error in ==>
@(hObject,eventdata)GUI_xyplotter('request_m2_Callback',hObject,eventdata,guidata(hObject))
??? Error while evaluating uicontrol Callback
motor 2 code:
fopen(obj2);
fwrite(obj2,uint8('E'));
t=fread(obj2,2,'uint8');
output=uint16(t(1))*256+uint16(t(2));
set(handles.text_request_m2,'String',output)

  6 Comments

Show 3 older comments
fremond khoo
fremond khoo on 10 Apr 2011
thanks a lot walter..you really help me a lot this time..^^..i will try harder next time to learn more about matlab^^..thanks a lot..cheers..btw..walter..do u have any tips on learning more about matlab?..i mean do u know any links to learn other than the tutorials?..i would like to have more experience like you^^
Walter Roberson
Walter Roberson on 10 Apr 2011
There are some suggestions about learning MATLAB in a previous Question, http://www.mathworks.com/matlabcentral/answers/1148-how-to-learn-matlab
It would be fairly difficult these days to get the same kind of experience that I got -- I've been programming for 35 years, from the days when I was the only person in my class who could afford to buy a computer that could fit as many as 99 instructions...
fremond khoo
fremond khoo on 10 Apr 2011
woa..35 years??..think i can never get the same kind of experience like you..but anyhow..i will try my best to understand more..thanks..^^

Sign in to comment.


fremond khoo
fremond khoo on 11 Apr 2011
Walter..i have a question for you..do you still remember the first time you help me in the connection of the motor?..
you gave me this code:
function obj=find_and_open(port,wantbaud)
obj = instrfind('Type','serial','Port',port);
if isempty(obj);
obj = serial(port);
end
if get(obj,'BaudRate')~=wantbaud
if strcmpi(get(obj,'Status'),'open');
fclose(obj);
end
set(obj,'BaudRate',wantbaud);
end
if ~strcmpi(get(obj,'Status'),'open');
fopen(obj);
end
i want to ask this code should be place first before any pushbutton is callback right?..after i have define the obj, i should be able to connect to the COM by writing code like this right?
% --- Executes on button press in connect_m1.
function connect_m1_Callback(hObject, eventdata, handles)
%Create a serial port object
obj1 = find_and_open('COM8',9600);
handles.obj1=obj1
guidata(hObject,handles)
thereafter..if i want to control other buttons..can i just write like this?
% --- Executes on button press in on_m1.
function on_m1_Callback(hObject, eventdata, handles)
obj1 = instrfind('Type','serial','Port','COM8','Tag','');
fprintf(obj1,'%s\n','O');

  8 Comments

Show 5 older comments
Walter Roberson
Walter Roberson on 11 Apr 2011
I don't have any particular ideas. At that point, what does get(obj2) say about the object properties?
fremond khoo
fremond khoo on 11 Apr 2011
obj2 = find_and_open('COM9',9600)
im also confuse what went wrong..what about the object properties?..do i need to change anything about that?
Walter Roberson
Walter Roberson on 11 Apr 2011
Put that fprintf() statement in a try/catch block, and when the exception occurs, display the output of get(obj2) in order to see what the internal status of the object was.

Sign in to comment.


fremond khoo
fremond khoo on 12 Apr 2011
before that, walter..can i arrange my code like that?..or the arrangement is totally wrong?
%find and open serial port
function obj=find_and_open(port,wantbaud)
obj = instrfind('Type','serial','Port',port);
if isempty(obj);
obj = serial(port);
end
if get(obj,'BaudRate')~=wantbaud
if strcmpi(get(obj,'Status'),'open');
fclose(obj);
end
set(obj,'BaudRate',wantbaud);
end
if ~strcmpi(get(obj,'Status'),'open');
fopen(obj);
end
% --- Executes on button press in connect_m1.
function connect_m1_Callback(hObject, eventdata, handles)
%Create a serial port object
obj1 = find_and_open('COM8',9600);
% --- Executes on button press in connect_m2.
function connect_m2_Callback(hObject, eventdata, handles)
%Create a serial port object
obj2 = find_and_open('COM9',9600);

  5 Comments

Show 2 older comments
Walter Roberson
Walter Roberson on 12 Apr 2011
obj2=find_and_open('COM9',9600)
try
fprintf(obj2,'%s\n','O');
catch
disp('It blew up real good!')
get(obj2) %no semi-colon
end
fremond khoo
fremond khoo on 12 Apr 2011
walter..i use ur way of using try and catch function and it work..now i can control two motor at the same time^^..cheers!!..the only prob left is still the receive encoder..always comes out the same error:
??? Attempted to access t(1); index out of bounds
because numel(t)=0.
Error in ==> GUI_xyplotter>request_m2_Callback at 280
output=uint16(t(1))*256+uint16(t(2));
Error in ==> gui_mainfcn at 96
feval(varargin{:});
Error in ==> GUI_xyplotter at 16
gui_mainfcn(gui_State, varargin{:});
Error in ==>
@(hObject,eventdata)GUI_xyplotter('request_m2_Callback',hObject,eventdata,guidata(hObject))
??? Error while evaluating uicontrol Callback
Walter Roberson
Walter Roberson on 12 Apr 2011
Where you have the
t = fread(obj2, 2, 'uint8');
change that to
[t,count,msg] = fread(obj2, 2, 'uint8');
if count < 2
if ischar(msg)
fprintf(1,'request_m2 obj2 read returned only %d bytes, saying that %s\n', count, msg);
else
fprintf(1,'request_m2 obj2 read returned only %d bytes for an unknown reason);
end
return
end

Sign in to comment.


fremond khoo
fremond khoo on 12 Apr 2011
i am sorry walter..but it seems that the code is unstable..sometimes can sometimes cant..now it shows me this object properties:
It blew up real good!
ByteOrder = littleEndian
BytesAvailable = 26
BytesAvailableFcn =
BytesAvailableFcnCount = 48
BytesAvailableFcnMode = terminator
BytesToOutput = 0
ErrorFcn =
InputBufferSize = 512
Name = Serial-COM9
ObjectVisibility = on
OutputBufferSize = 512
OutputEmptyFcn =
RecordDetail = compact
RecordMode = overwrite
RecordName = record.txt
RecordStatus = off
Status = open
Tag =
Timeout = 10
TimerFcn =
TimerPeriod = 1
TransferStatus = idle
Type = serial
UserData = []
ValuesReceived = 0
ValuesSent = 35
SERIAL specific properties:
BaudRate = 9600
BreakInterruptFcn =
DataBits = 8
DataTerminalReady = off
FlowControl = none
Parity = none
PinStatus = [1x1 struct]
PinStatusFcn =
Port = COM9
ReadAsyncMode = continuous
RequestToSend = off
StopBits = 1
Terminator = LF

  1 Comment

Walter Roberson
Walter Roberson on 12 Apr 2011
Change the find_and_open function as follows and try again:
function obj=ODF_plot(port,wantbaud)
needed_open = true;
obj = instrfind('Type','serial','Port',port);
if isempty(obj);
fprintf(1,'find_and_open: note that instrfind did not find port %s\n', port);
obj = serial(port);
end
curspeed = get(obj,'BaudRate');
if curspeed ~= wantbaud
if strcmpi(get(obj,'Status'),'open');
fclose(obj);
needed_open = false;
fprintf(1,'find_and_open: note that port %s was already open but had the wrong speed, %d\n', port, curspeed)
end
set(obj,'BaudRate',wantbaud);
end
curmode = get(obj,'BytesAvailabelFcnMode');
if ~strcmpi(curmode, 'byte')
if strcmpi(get(obj,'Status'),'open');
fclose(obj);
needed_open = false;
fprintf(1,'find_and_open: note that port %s was already open but had the wrong mode, %s\n', port, curmode)
end
set(obj,'BytesAvailabelFcnMode', 'byte');
end
if ~strcmpi(get(obj,'Status'),'open');
fopen(obj);
if needed_open
fprintf(1,'find_and_open: needed to open port %s\n', port);
end
end

Sign in to comment.


fremond khoo
fremond khoo on 12 Apr 2011
Walter..it come out this error:
??? Undefined function or method 'find_and_open' for
input arguments of type 'char'.
Error in ==> GUI_xyplotter>on_m1_Callback at 106
obj1 = find_and_open('COM8',9600);
Error in ==> gui_mainfcn at 96
feval(varargin{:});
Error in ==> GUI_xyplotter at 16
gui_mainfcn(gui_State, varargin{:});
Error in ==>
@(hObject,eventdata)GUI_xyplotter('on_m1_Callback',hObject,eventdata,guidata(hObject))
??? Error while evaluating uicontrol Callback
it seems it cannot read the find_and_open function when i executed the buttons..

  1 Comment

Walter Roberson
Walter Roberson on 12 Apr 2011
Sorry, where I wrote ODF_plot change that to find_and_open .

Sign in to comment.


fremond khoo
fremond khoo on 13 Apr 2011
yeah..i changed the code into find_and_open and try it out..but the error is something i never seen before..
??? Error using ==> serial.get at 71
There is no 'BytesAvailabelFcnMode' property for serial
port objects.
Error in ==> GUI_xyplotter>find_and_open at 63
curmode = get(obj,'BytesAvailabelFcnMode');
Error in ==> GUI_xyplotter>connect_m1_Callback at 84
obj1 = find_and_open('COM8',9600);
Error in ==> gui_mainfcn at 96
feval(varargin{:});
Error in ==> GUI_xyplotter at 16
gui_mainfcn(gui_State, varargin{:});
Error in ==>
@(hObject,eventdata)GUI_xyplotter('connect_m1_Callback',hObject,eventdata,guidata(hObject))
??? Error while evaluating uicontrol Callback

  5 Comments

Show 2 older comments
Walter Roberson
Walter Roberson on 13 Apr 2011
No, t is a local variable, not a function, and the value in one routine would not affect the value in another.
Did you not make the parallel change to the one I indicated earlier?
=== begin quote ===
Where you have the
t = fread(obj2, 2, 'uint8');
change that to
[t,count,msg] = fread(obj2, 2, 'uint8');
if count < 2
if ischar(msg)
fprintf(1,'request_m2 obj2 read returned only %d bytes, saying that %s\n', count, msg);
else
fprintf(1,'request_m2 obj2 read returned only %d bytes for an unknown reason);
end
return
end
=== end quote ===
Do the same thing for request_m1_Callback except changing 2 to 1 for the object number and warning messages.
fremond khoo
fremond khoo on 14 Apr 2011
im sorry walter..i did not change to parallel before that..now that i have changed..it has no error..but it state it receive 0 bytes from my motor..
the statement:
request_m1 obj1 read returned only 0 bytes, saying that The specified amount of data was not returned within the Timeout period.
fremond khoo
fremond khoo on 15 Apr 2011
it's working walter^^..try again and success!!..deepest gratitude towards walter~~..thanks

Sign in to comment.


keycamel villegas
keycamel villegas on 16 Apr 2011
hi fremond khoo..did you used a motor driver for your stepper motor?and may i know what are the connections?thank you!!.. im a newbie in matlab..and my thesis project involves the movement of a bipolar stepper motor. :)

  1 Comment

fremond khoo
fremond khoo on 19 Apr 2011
im sorry keycamel villegas for the late reply..yup..i use SD02B motor driver(u can search from www.cytron.com)..the connection is fairly easy..just go to cytron and u will know everything^^..cheers..they even provide a manual for you..just go ahead and try it out..my project is about unipolar stepper motor^^

Sign in to comment.


keycamel villegas
keycamel villegas on 19 Apr 2011
my project involves a bipolar stepper motor and im using L298 motor driver..would it be possible that your code above can be used in our project?

  2 Comments

fremond khoo
fremond khoo on 19 Apr 2011
you can try them out..u are using serial port or parallel?
keycamel villegas
keycamel villegas on 19 Apr 2011
our professor said that our connection would be:
RS232 to serial to parallel converter(using 4 bit shift register) to l298 motor driver connected to bipolar stepper motor,,
would that be possible?or can you suggest other connection for our bipolar stepper motor because i have difficulty analyzing the connections of this components,,
by the way THANK YOU for your reply :)

Sign in to comment.


keycamel villegas
keycamel villegas on 19 Apr 2011
our professor said that our connection would be:
RS232 to serial to parallel converter(using 4 bit shift register) to l298 motor driver connected to bipolar stepper motor,,
would that be possible?or can you suggest other connection for our bipolar stepper motor because i have difficulty analyzing the connections of this components,,
by the way THANK YOU for your reply :)

  6 Comments

Show 3 older comments
fremond khoo
fremond khoo on 20 Apr 2011
walter^^..today i finish my final presentation and my evaluator was very impressed with my project..at here i wish to say thanks again to all of your help from the bottom of my heart..^^..thanks again
keycamel villegas
keycamel villegas on 6 May 2011
can i asked you a question? how uart of a microcontroller communicate with the uart of matlab?.thank you
Walter Roberson
Walter Roberson on 6 May 2011
The program running on the microcontroller uses system-specific methods to cause the microcontroller's UART to send the bytes out.
Please start a new question for these kinds of topics; this question is very long and difficult to follow.

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by