Filter löschen
Filter löschen

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 Ansicht (letzte 30 Tage)
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?

Antworten (1)

Walter Roberson
Walter Roberson am 8 Mai 2016
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 Kommentare
Eve Stu
Eve Stu am 8 Mai 2016
Bearbeitet: Walter Roberson am 8 Mai 2016
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 am 8 Mai 2016
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)

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Migrate GUIDE Apps finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by