MATLAB Answers

how to control stepper motor speed via USB port

18 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.

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
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 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
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
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 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
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
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
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
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
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
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
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
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
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!