how to control stepper motor speed via USB port

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

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.

댓글을 달려면 로그인하십시오.

 채택된 답변

Walter Roberson
Walter Roberson 2011년 3월 27일

0 개 추천

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.

추가 답변 (17개)

fremond khoo
fremond khoo 2011년 3월 27일

0 개 추천

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

Ummm, so you don't have a COM8. Is it a USB based port? If so, then you have to have it connected _before_ you start Matlab.
I am not sure why you are restricting your instrfind to the case where the Tag is the empty string? If you are not using the Tag for some purpose then it just confuses the readers. If you _are_ using the Tag for some purpose, then a comment in the code would be appreciated.
oic..ok..i will change the tag function later^^
i have COM8 and i tried running the system but still the same error comes out..is there something wrong with my code?
The obvious thing to try is to close matlab and start it up again, and then without executing anything else, command,
obj1 = instrfind('Type','serial','Port','COM8')
If it cannot find COM8 then you know it isn't a problem with the rest of your code.
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?
can someone teach me how to solve this problem?..im really short of time..really hope to get some advices and help..
Doesn't this case correspond to you closing the existing port and opening it again? Or did you remove that code?

댓글을 달려면 로그인하십시오.

fremond khoo
fremond khoo 2011년 3월 29일

0 개 추천

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

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.)
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
Is there a reference document that discusses the command format expected by the motor?

댓글을 달려면 로그인하십시오.

fremond khoo
fremond khoo 2011년 3월 31일

0 개 추천

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

fwrite(obj1, [uint8('S') uint8(str2num(sv2))], '*uint8');
Or you might need 'uint8' instead of '*uint8'
Note that with this formula, the string sv2 that you get, the slider value, will be clamped to 0 if it is below 0 and will be clamped to 255 if it is above 255. You should arrange your slider to have a top value of 255.
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
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?..
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()

댓글을 달려면 로그인하십시오.

fremond khoo
fremond khoo 2011년 4월 2일

0 개 추천

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

It isn't obvious to me what "tracking" does for you, but according to that code, it takes as input a 16 bit integer (0 to 65535) and has no output.
tval16 = uint16(Tval);
tval16H = tval16 / 256;
tval16L = tval16 - tval16H * 256;
fwrite(s, [uint8('T') uint8(tval16H) uint8(tval16L)])
the track function is to stop the motor when a certain value is inserted into a textbox
for example:
if i insert 3400 encoder value into the textbox then the stepper motor will receive the signal and stop exactly at 3400..
walter, can i ask lets say:
obj1 = serial('COM8');
t1 = num2str(get(handles.text_track_m1,'String'));
then i should write:
fwrite(obj1,[uint8('T') uint8(t1) uint8(tval16L)])
is it correct?
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.
thanks walter..really thanks a lot..cheers!!
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()

댓글을 달려면 로그인하십시오.

fremond khoo
fremond khoo 2011년 4월 6일

0 개 추천

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

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

댓글을 달려면 로그인하십시오.

fremond khoo
fremond khoo 2011년 4월 7일

0 개 추천

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

See above, I gave you the wrong information about strcmp.
Beyond that, though, remember that the String property of a listbox is all of the configured entries for the list, not the one that is currently selected. The index of the one that is currently selected can be retrieved by getting the Value property. If you happen to want the string that corresponded to that, you can get the String property and index that by the Value; a lot of the time, though, it is better to use just the value to make it easier to change the wording of the strings (e.g., if you wanted to translate to a different language.)
thanks walter..i have gotten the hang of it thanks to you^^..i finally be able to control the microstepping of motor..walter..can i ask u something..is it possible for me to control both motor to move to a desired position at the same time without using microcontroller?..because my supervisor asked me to do inverse kinematics on the robot arm..
is it possible for me to control only one of my motor to a desired angle through serial communication?..or is it impossible without using microcontroller?
i really would like an advice from that^^
I don't see any reason why you couldn't send Track commands to two different ports.
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?
erm..wait for a while walter..i try to edit the code again first^^

댓글을 달려면 로그인하십시오.

fremond khoo
fremond khoo 2011년 4월 7일

0 개 추천

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

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.
can i ask what does it mean by
t=fread(obj1,2,'uint8');
what does the number '2' define?
The 2 means to read two items; each item will be of type uint8.

댓글을 달려면 로그인하십시오.

fremond khoo
fremond khoo 2011년 4월 7일

0 개 추천

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

You missed the str2num() or str2double() around t2
t2 = str2double(get(handles.text_track_m2,'String'));
Anything that needs to be displayed as text to the user needs to be converted to a numeric value with str2double() or str2num() or sscanf() or textscan() before it can be used for computation.
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?..
Insufficient information. No correspondence has been documented between angles and the values sent for the 'T' command.
ic..ok..thanks a lot walter for your help..i will try to find out more info in the mean time..thanks^^..

댓글을 달려면 로그인하십시오.

fremond khoo
fremond khoo 2011년 4월 8일

0 개 추천

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

I don't see anything obviously wrong with that, but I continue to say that it is a distinct tactical error to keep opening and closing the com ports: that you should open the ports once and keep them open unless some error is encountered that forces a re-open.
yeah..i changed the opening and closing sequence then it's working already..thanks once again walter..walter..got one part i dun understand..why is the
output = uint16(t(1))*256+uint16(t(2))
what is the meaning of this code?..i really cant understand this code..
t(1) is a uint8, which is an unsigned 8 bit integer. Multiplying an integer by 256 has the same effect as shifting the binary representation of the integer left by 8 bits, like (highbyte << 8) in C. Adding the 8-bit integer t(2) to the multiplied number then effectively puts t(2) in as the low-order 8 bits of the 16 bit number. The uint16() calls are there because in MATLAB when you do arithmetic operations on an 8 bit number, you get an 8 bit number out as a result but we need a 16 bit number as the result.
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^^
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...
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..^^

댓글을 달려면 로그인하십시오.

fremond khoo
fremond khoo 2011년 4월 11일

0 개 추천

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

For the other buttons, you should probably use find_and_open() as well.
oh..then i will just include obj1 = find_and_open('COM',9600) at the initialization for every push button?..then fopen() is not require anymore until we close the port at the end?
walter..way to go..i have already altered all my pushbutton to find_and_open format..^^..now no need to fopen() anymore..thanks once again
I suspect that if you put disp() in to appropriate places in find_and_open() that you will discover that opening only once at the beginning is enough. Still, there is always the possibility of the port getting closed somehow, so it's worth testing a while first.
somehow..there is an error when i excuted for my 2nd motor using other com port..
??? Error while evaluating uicontrol Callback
??? Error using ==> serial.fprintf at 144
An error occurred during writing.
Error in ==> GUI_xyplotter>on_m2_Callback at 150
fprintf(obj2,'%s\n','O');
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_m2_Callback',hObject,eventdata,guidata(hObject))
??? Error while evaluating uicontrol Callback
why does it work for motor 1 but nor for motor 2??
i really am confuse now..@.@
I don't have any particular ideas. At that point, what does get(obj2) say about the object properties?
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?
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.

댓글을 달려면 로그인하십시오.

fremond khoo
fremond khoo 2011년 4월 12일

0 개 추천

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

That looks okay.
ok^^..then about the try/catch bracket..i never learn the function yet..izzit i arrange my code to be like this:
obj2=find_and_open('COM9',9600)
try
fprintf(obj2,'%s\n','O');
catch
end
sorry i am not very sure about the usage of try and catch..
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
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
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

댓글을 달려면 로그인하십시오.

fremond khoo
fremond khoo 2011년 4월 12일

0 개 추천

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

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

댓글을 달려면 로그인하십시오.

fremond khoo
fremond khoo 2011년 4월 12일

0 개 추천

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

Sorry, where I wrote ODF_plot change that to find_and_open .

댓글을 달려면 로그인하십시오.

fremond khoo
fremond khoo 2011년 4월 13일

0 개 추천

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

Typo, should have been BytesAvailableFcnMode
yup..that's the prob^^..changed already..now is functioning..but for the receive encoder part..it still came out the same error eventhough i din open and close my port the whole time..
same error..
??? Attempted to access t(1); index out of bounds
because numel(t)=0.
Error in ==> GUI_xyplotter>request_m1_Callback at 249
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_m1_Callback',hObject,eventdata,guidata(hObject))
??? Error while evaluating uicontrol Callback
is it because i use the function t(1) for both COM until COM9 cannot read t(1) function because it is open in COM8?
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.
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.
it's working walter^^..try again and success!!..deepest gratitude towards walter~~..thanks

댓글을 달려면 로그인하십시오.

keycamel villegas
keycamel villegas 2011년 4월 16일

0 개 추천

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

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

댓글을 달려면 로그인하십시오.

keycamel villegas
keycamel villegas 2011년 4월 19일

0 개 추천

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

you can try them out..u are using serial port or parallel?
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 :)

댓글을 달려면 로그인하십시오.

keycamel villegas
keycamel villegas 2011년 4월 19일

0 개 추천

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

RS232 is your stepper motor model??..for my project..i use RS440-442 and RS440-420 unipolar stepper motor and connect them to two driver motor and from the driver motor connect them to laptop using UART converter (UC00A)..you are welcome..people help me then im glad i can help others back^^
RS232 is a usb to serial connector then it will be connected to a serial to parallel converter(using 4 bit shift register) and it will be connected to a L298 motor driver, connected to a bipolar stepper motor.
sorry for many questions im asking...it just that im a newbie in matlab..thanks for the effort answering my problems
Our goal is: Matlab controlling stepper motor
Please take this to a new Question, "keycamel": this one is already long enough to make it difficult to find useful information in.
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
can i asked you a question? how uart of a microcontroller communicate with the uart of matlab?.thank you
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.

댓글을 달려면 로그인하십시오.

커뮤니티

더 많은 답변 보기:  Power Electronics Community

Community Treasure Hunt

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

Start Hunting!

Translated by