필터 지우기
필터 지우기

If I write commands in the command window: s = serial('CO​M3','BaudR​ate',9600)​; fopen(s); fprintf(s,'l0'); , it is good. How to write this text in pushbutton?

조회 수: 1 (최근 30일)
Hi! I am doing a project for school and I need some help. If I write commands in the command window:
s = serial('COM3','BaudRate',9600);
fopen(s);
fprintf(s,'l0');
it works well. I create a button in GUI. How to write this text in pushbutton, so that it will be able to work correctly?

답변 (1개)

Walter Roberson
Walter Roberson 2016년 5월 8일
function pushdemo
fig = figure();
push = uicontrol('Style', 'push', 'String', 'Go!', 'Callback', @push_callback);
end
function push_callback(hObject, event)
s = serial('COM3','BaudRate',9600);
fopen(s);
fprintf(s,'l0');
disp('Sent it!')
pause(10);
fclose(s);
delete(s);
end
Since s is a variable local to the workspace of push_callback, it would be closed and deleted when the function returned; I just made it more clear that it was going to happen. If you do not want s to be deleted then you need to make sure that s lives on after the function returns.
  댓글 수: 2
Eve Stu
Eve Stu 2016년 5월 8일
편집: Walter Roberson 2016년 5월 8일
function pushdemo
fig = figure();
push = uicontrol('Style', 'push', 'String', 'Go!', 'Callback', @pushbutton1_Callback);
end
% --- Executes on button press in pushbutton1.
function pushbutton1_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
%Create the serial port object (s) in MATLAB, and select comm port 6 to use
s = serial('COM3','BaudRate',9600);
fopen(s);
fprintf(s,'l0');
disp('Sent it!')
pause(10);
fclose(s);
delete(s);
end
Error: File: sasaja.m Line: 103 Column: 1
The function "pushbutton1_Callback" was closed with an 'end', but at least one other function
definition was not. To avoid confusion when using nested functions, it is illegal to use both
conventions in the same file.
How can I solve this? Is it possible to use only function pushbutton1_Callback(hObject, eventdata, handles)?
Walter Roberson
Walter Roberson 2016년 5월 8일
You tried to mix GUIDE with hand-written code.
If you are using GUIDE, have it create a push button, and in the callback for that pushbutton add the code
s = serial('COM3','BaudRate',9600);
fopen(s);
fprintf(s,'l0');
disp('Sent it!')
pause(10);
fclose(s);
delete(s);
but be sure to decide between COM3 (your code) and COM6 (your comment)

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

카테고리

Help CenterFile Exchange에서 Migrate GUIDE Apps에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by