How to have an event when the mouse enters a particular area/polygon in Guide?

I would like an event whenever a mouse enters a particular area. Basically, i would like motors to be running when the mouse enters the area.Also i would like the area to turns green when the cursor is inside the area and turns red when it is out.
I had the code in appdesigner but appdesigner is paradoxically limited. I dont really know how to do it in Guide. *****Check the Next_buton callback
Furthermore, with the help of a "Next button", i would like data to be loaded from excel (data are different polygones)
function varargout = Hapticfinal(varargin)
% HAPTICFINAL MATLAB code for Hapticfinal.fig
% HAPTICFINAL, by itself, creates a new HAPTICFINAL or raises the existing
% singleton*.
%
% H = HAPTICFINAL returns the handle to a new HAPTICFINAL or the handle to
% the existing singleton*.
%
% HAPTICFINAL('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in HAPTICFINAL.M with the given input arguments.
%
% HAPTICFINAL('Property','Value',...) creates a new HAPTICFINAL or raises the
% existing singleton*. Starting from the left, property value pairs are
% handleslied to the GUI before Hapticfinal_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property handleslication
% stop. All inputs are passed to Hapticfinal_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% Edit the above text to modify the response to help Hapticfinal
% Last Modified by GUIDE v2.5 17-Feb-2022 21:51:18
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @Hapticfinal_OpeningFcn, ...
'gui_OutputFcn', @Hapticfinal_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
% --- Executes just before Hapticfinal is made visible.
function Hapticfinal_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to Hapticfinal (see VARARGIN)
% Choose default command line output for Hapticfinal
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes Hapticfinal wait for user response (see UIRESUME)
% uiwait(handles.finger);
% --- Outputs from this function are returned to the command line.
function varargout = Hapticfinal_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.output;
% --- Executes on mouse motion over figure - except title and menu.
function finger_WindowButtonMotionFcn(hObject,eventdata, handles)
% hObject handle to finger (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
pos = get(hObject, 'currentpoint'); % get mouse location on figure
global x;
global y;
x = pos(1);
y = pos(2); % assign locations to x and y
set(handles.xloc, 'string', ['x loc:' num2str(x)]); % update text for x loc
set(handles.yloc, 'string', ['y loc:' num2str(y)]); % update text for y loc
% --- Executes on button press in Start_button.
%function Start_button_Callback(hObject, eventdata, handles)
% --- Executes on button press in Start_button.
function Start_button_Callback(hObject, eventdata, handles)
% hObject handle to Start_button (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
%clear
%clc
handles.fileID = fopen('exp.txt','w');
handles.t = timer('ExecutionMode', 'fixedRate', ...
'Period', 0.5, ...
'TasksToExecute', Inf, ...
'TimerFcn', {@timerCallback, handles.fileID});
start(handles.t);
set(handles.Start_button,'Enable','off'); % -> Disable the button
guidata(hObject,handles);% -----> do this to save the updated handles object
function timerCallback(~,~,fileID)
fprintf(fileID,'(X, Y, time) = (%g, %g, %s)\n', get(0, 'PointerLocation'), datetime('now'));
%fprintf('calling timer callback\n');
% --- Executes on button press in Stop_button.
function Stop_button_Callback(hObject, eventdata, handles)
% hObject handle to Stop_button (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
handles = guidata(hObject);
stop(handles.t) %whenever we want to stop.
fclose(handles.fileID);
set(handles.Start_button,'Enable','on'); % -> Enable the button
guidata(hObject,handles);
% --- Executes on button press in Yes_button.
function Yes_button_Callback(hObject, eventdata, handles)
% hObject handle to Yes_button (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
answer = questdlg('ARE YOU SURE?','Confirm close',...
'OK',@(src,event)mycallback(handles,src,event));
clear
clc
fileID= fopen('exp.txt2','a');
YES = "I FEEL IT";
fprintf (fileID, "%s\n",YES);
fclose(fileID);
% --- Executes on button press in NO_button.
function NO_button_Callback(hObject, eventdata, handles)
% hObject handle to NO_button (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
answer1= questdlg('ARE YOU SURE?','Confirm Close',...
'OK',@(src,event)mycallback(handles,src,event));
clear
clc
fileID= fopen('exp.txt2','a');
NO = "I DON'T FEEL IT";
fprintf (fileID, "%s\n",NO);
fclose(fileID);
% --- Executes on button press in Next_button.
function Next_button_Callback(hObject, eventdata, handles)
% hObject handle to Next_button (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)uiconfirm(handles.UIFigure,'Are You sure?','Confirm Close',...
f = msgbox('Operation Completed','NEXT');
% Read experiment data from a CSV file
% region1 = patch(axes1,[-10 10 10 -10],[-5 -5 -4.4 -4.4],'r','FaceAlpha',1,...
%'LineWidth',0.01,'LineStyle','-','tag','region1');
load_folder = "C:\Users\Hp\Desktop\thesis\excel_data\";
load_name = "excel_data.xlsx";
load_addr = load_folder + load_name;
T = readtable(load_addr,'NumHeaderLines',1);
exp_counter = 1;
v_thickness_1 = T.Var1;
v_thickness_2 = T.Var2;
h_thickness_1 = T.Var3;
h_thickness_2 = T.Var4;
amplitude_array = T.Var5;
v_or_h_array = T.Var6;
v_thick1 = v_thickness_1(exp_counter);
v_thick2 = v_thickness_2(exp_counter);
h_thick1 = h_thickness_1(exp_counter);
h_thick2 = h_thickness_2(exp_counter);
%%
v_or_h = v_or_h_array(exp_counter);
%Vertical line
if v_or_h == 0
patch([v_thick1 v_thick2 v_thick2 v_thick1],[-10 -10 10 10],'red');
xlim([-5 0])
grid on
%Horizontal line
elseif v_or_h == 1
patch([-10 10 10 -10],[h_thick1 h_thick1 h_thick2 h_thick2],'red');
ylim([0 5])
grid on
end
% % Create the Arduino serial object
% %arduinoObj = serialport("COM3", 9600);
% %configureTerminator(arduinoObj,"CR/LF");
% %flush(arduinoObj);
% %
% for i=1:8
% message = readline(arduinoObj);
% disp(message)
% end
global Start;
Start=1;
if v_or_h == 0
patch([v_thick1 v_thick2 v_thick2 v_thick1],[-10 -10 10 10],'red');
xlim([-5 0])
grid on
%Horizontal line
elseif v_or_h == 1
patch([-10 10 10 -10],[h_thick1 h_thick1 h_thick2 h_thick2],'red');
ylim([0 5])
grid on
end
% Create the Arduino serial object
arduinoObj = serialport("COM3", 9600);
configureTerminator(app.arduinoObj,"CR/LF");
%flush(app.arduinoObj);
%
for i=1:8
message = readline(arduinoObj);
disp(message)
end
function cursorPositionFeedback(app, hobj, inout) %This is a code from appdesigner
% When inout is 'in', change hobj facecolor to green and update textbox.
% When inout is 'out' change hobj facecolor to red, and clear textbox.
% Check tag property of hobj to identify the object.
switch lower(inout)
case 'in'
% facecolor = 'g';
% txt = 'Motor(s) vibrating';
pointer = 'fleur';
writeline(app.arduinoObj, "4&MOTOR_1_2&0!"); % motors running
% message = readline(app.arduinoObj);
% disp(message)
case 'out'
% facecolor = 'r';
%txt = 'No';
pointer = 'crosshair';
writeline(app.arduinoObj, "0&MOTOR_1_2_3_4&0!");
drawnow;
% message = readline(app.arduinoObj);
% disp(message)
end
hobj.FaceColor = facecolor;
app.TextAreaEditField.Value = txt;
set(app.UIFigure, 'Pointer', pointer)
% --- Executes on button press in pushbutton7.
function pushbutton7_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton7 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --- Executes during object creation, after setting all properties.
function finger_CreateFcn(hObject, eventdata, handles)
% hObject handle to finger (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called

19 Kommentare

Once you have loaded the polygons' vertices and you have the mouse position (and converted them to a common coordinate system if necessary), you can use inpolygon() to determine whether the mouse is inside one or more of the polygons.
@_ i dont know in which callback i have put it...Actually, it is a line. (Rectangle) . I think i have to use patch
Voss
Voss am 18 Feb. 2022
Bearbeitet: Voss am 18 Feb. 2022
It belongs in whatever function is your figure's WindowButtonMotionFcn (specifically the WindowButtonMotionFcn at the time when the update needs to be made, if more than one function could be the WindowButtonMotionFcn at any given time) or in some helper function called by the figure's WindowButtonMotionFcn.
From your code here, looks like that would be finger_WindowButtonMotionFcn() (or possibly cursorPositionFeedback() - if you intend to adapt that function to be used with a GUIDE figure rather than an AppDesigner uifigure), though I cannot see how those are associated to the figure (that may be in the .fig file).
You can use patch() to create the patches you will need, yes. This can be done in the OpeningFcn, and store the handles to the patches in the handles structure (or as a global variable if you like). Then update the patches' properties like FaceColor or whatever in the WindowButtonMotionFcn, based on whether the cursor is inside or outside the relevant rectangle.
I think i did what you have advised me...But i am having some issues now.
Error using plot
Not enough input arguments
The issue is this line : plot(handles.region1) % polygon .
Furthermore , i have problem with the "Next Button" i am supposed to have different lines each time i click on it(But i am still having the same line).
I would like that everytime the mouse goes into the region , the motors start vibrating. I did it on the Next buton and finger_windowmotion callbacks but i am not sure that , it is the right ways to go for it....
function varargout = Hapticfinal(varargin)
% HAPTICFINAL MATLAB code for Hapticfinal.fig
% HAPTICFINAL, by itself, creates a new HAPTICFINAL or raises the existing
% singleton*.
%
% H = HAPTICFINAL returns the handle to a new HAPTICFINAL or the handle to
% the existing singleton*.
%
% HAPTICFINAL('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in HAPTICFINAL.M with the given input arguments.
%
% HAPTICFINAL('Property','Value',...) creates a new HAPTICFINAL or raises the
% existing singleton*. Starting from the left, property value pairs are
% handleslied to the GUI before Hapticfinal_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property handleslication
% stop. All inputs are passed to Hapticfinal_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% Edit the above text to modify the response to help Hapticfinal
% Last Modified by GUIDE v2.5 17-Feb-2022 21:51:18
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @Hapticfinal_OpeningFcn, ...
'gui_OutputFcn', @Hapticfinal_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
% --- Executes just before Hapticfinal is made visible.
function Hapticfinal_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to Hapticfinal (see VARARGIN)
% Choose default command line output for Hapticfinal
handles.output = hObject;
clc
% Plot patch on uiaxes
hold on
% Read experiment data from a CSV file
load_folder = "C:\Users\Hp\Desktop\thesis\excel_data\";
load_name = "excel_data.xlsx";
load_addr = load_folder + load_name;
T = readtable(load_addr,'NumHeaderLines',1);
exp_counter = 1;
v_thickness_1 = T.Var1;
v_thickness_2 = T.Var2;
h_thickness_1 = T.Var3;
h_thickness_2 = T.Var4;
amplitude_array = T.Var5;
v_or_h_array = T.Var6;
v_thick1 = v_thickness_1(exp_counter);
v_thick2 = v_thickness_2(exp_counter);
h_thick1 = h_thickness_1(exp_counter);
h_thick2 = h_thickness_2(exp_counter);
v_or_h = v_or_h_array(exp_counter);
%Vertical line
if v_or_h == 0
handles.region1 = patch([v_thick1 v_thick2 v_thick2 v_thick1],[-10 -10 10 10],'blue');
xlim([-5 0])
grid on
%Horizontal line
elseif v_or_h == 1
handles.region1= patch([-10 10 10 -10],[h_thick1 h_thick1 h_thick2 h_thick2],'blue');
ylim([0 5])
grid on
end
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes Hapticfinal wait for user response (see UIRESUME)
% uiwait(handles.finger);
% --- Outputs from this function are returned to the command line.
function varargout = Hapticfinal_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.output;
% --- Executes on mouse motion over figure - except title and menu.
function finger_WindowButtonMotionFcn(hObject,eventdata, handles)
% hObject handle to finger (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
handles = guidata(hObject);
pos = get(hObject, 'currentpoint'); % get mouse location on figure
global x;
global y;
x = pos(1);
y = pos(2); % assign locations to x and y
set(handles.xloc, 'string', ['x loc:' num2str(x)]); % update text for x loc
set(handles.yloc, 'string', ['y loc:' num2str(y)]); % update text for y loc
% Determine if mouse is within the region
plot(handles.region1) % polygon
axis equal
hold on
plot(handles.region1(in),'g+') % points inside
%writeline(arduinoObj, "4&MOTOR_1_2&0!");
plot(handles.region1(~in),'r+') % points outside
%writeline(arduinoObj, "0&MOTOR_1_2_3_4&0!");
drawnow;
hold off
guidata(hObject,handles);
% --- Executes on button press in Start_button.
%function Start_button_Callback(hObject, eventdata, handles)
% --- Executes on button press in Start_button.
function Start_button_Callback(hObject, eventdata, handles)
% hObject handle to Start_button (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
%clear
%clc
handles.fileID = fopen('exp.txt','w');
handles.t = timer('ExecutionMode', 'fixedRate', ...
'Period', 0.5, ...
'TasksToExecute', Inf, ...
'TimerFcn', {@timerCallback, handles.fileID});
start(handles.t);
set(handles.Start_button,'Enable','off'); % -> Disable the button
guidata(hObject,handles);% -----> do this to save the updated handles object
function timerCallback(~,~,fileID)
fprintf(fileID,'(X, Y, time) = (%g, %g, %s)\n', get(0, 'PointerLocation'), datetime('now'));
fprintf('calling timer callback\n');
% --- Executes on button press in Stop_button.
function Stop_button_Callback(hObject, eventdata, handles)
% hObject handle to Stop_button (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
handles = guidata(hObject);
stop(handles.t) %whenever we want to stop.
fclose(handles.fileID);
set(handles.Start_button,'Enable','on'); % -> Enable the button
guidata(hObject,handles);
% --- Executes on button press in Yes_button.
function Yes_button_Callback(hObject, eventdata, handles)
% hObject handle to Yes_button (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
answer = questdlg('ARE YOU SURE?','Confirm close',...
'OK',@(src,event)mycallback(handles,src,event));
clear
clc
fileID= fopen('exp.txt2','a');
YES = "I FEEL IT";
fprintf (fileID, "%s\n",YES);
fclose(fileID);
% --- Executes on button press in NO_button.
function NO_button_Callback(hObject, eventdata, handles)
% hObject handle to NO_button (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
answer1= questdlg('ARE YOU SURE?','Confirm Close',...
'OK',@(src,event)mycallback(handles,src,event));
clear
clc
fileID= fopen('exp.txt2','a');
NO = "I DON'T FEEL IT";
fprintf (fileID, "%s\n",NO);
fclose(fileID);
% --- Executes on button press in Next_button.
function Next_button_Callback(hObject, eventdata, handles)
% hObject handle to Next_button (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)uiconfirm(handles.UIFigure,'Are You sure?','Confirm Close',...
handles = guidata(hObject);
f = msgbox('Operation Completed','NEXT');
% Read experiment data from a CSV file
% region1 = patch(axes1,[-10 10 10 -10],[-5 -5 -4.4 -4.4],'r','FaceAlpha',1,...
%'LineWidth',0.01,'LineStyle','-','tag','region1');
exp_counter = exp_counter + 1;
v_or_h = v_or_h_array(exp_counter);
v_thick1 = v_thickness_1(exp_counter);
v_thick2 = v_thickness_2(exp_counter);
h_thick1 = h_thickness_1(exp_counter);
h_thick2 = h_thickness_2(exp_counter);
if ishandle(handles.region1)
delete(handles.region1);
end
if v_or_h == 0
handles.region1 = patch([v_thick1 v_thick2 v_thick2 v_thick1],[-10 -10 10 10],'blue');
xlim([-5 0])
grid on
%Horizontal line
elseif v_or_h == 1
handles.region1= patch([-10 10 10 -10],[h_thick1 h_thick1 h_thick2 h_thick2],'blue');
ylim([0 5])
grid on
end
% Create the Arduino serial object
% arduinoObj = serialport("COM3", 9600);
%configureTerminator(arduinoObj,"CR/LF");
%flush(arduinoObj);
%
%for i=1:8
% message = readline(arduinoObj);
%disp(message)
%end
% Plot patch on uiaxes
plot(handles.region1) % polygon
axis equal
hold on
plot(handles.region1(in),'g+') % points inside
writeline(arduinoObj, "4&MOTOR_1_2&0!");
plot(handles.region1(~in),'r+') % points outside
writeline(arduinoObj, "0&MOTOR_1_2_3_4&0!");
drawnow;
hold off
guidata(hObject,handles);
% --- Executes on button press in pushbutton7.
function pushbutton7_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton7 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --- Executes during object creation, after setting all properties.
function finger_CreateFcn(hObject, eventdata, handles)
% hObject handle to finger (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
Regarding the error with plot(), it doesn't make sense to plot a patch that already exists, and in fact you cannot call plot() with a patch object as an argument. Maybe you mean to set(handles.region1,'Visible','on') or set(handles.region1,'FaceVertexCData','g') or similar.
Once you call patch() the patch is created; there is no need to plot() it.
Also, I haven't looked in detail yet, but I don't see any usage of inpolygon(), and the variable 'in' seems to be undefined. These two things seem related; perhaps a line of code was inadvertently deleted. I will check more thoroughly in a bit.
Can you attach the .fig file you're using?
I knew i was doing something weird with that plot thing .
Voss
Voss am 19 Feb. 2022
Bearbeitet: Voss am 19 Feb. 2022
Take a look at the attached m-file. I basically only did enough to get the patch to update correctly. (I commented out the arduino stuff because I don't have one attached to my system.) And I didn't touch Start/Stop/timer functionality.
The problem you described about the new patch not showing up when you create it in the Next button callback is because the new patch was being created in the message box axes. msgbox() creates a figure, and if you issue plot() or patch(), etc., commands, without saying which axes to plot to, then they go to the current axes. When the message box pops up, it is the current figure (until you click on another figure), so the plot commands go there. So, to avoid that, I made sure to always issue patch creation and other axes commands to handles.axes1. Take a look at the code to see what that looks like.
Also, I put in the coordinate conversion necessary to test whether the cursor is over the patch, within the window button motion function. Because the figure's CurrentPoint is in pixels relative to the lower-left corner of the figure, but the patch XData and YData are in axes units, you must take into account the axes' Position (and Units), XLim, and YLim to be able to compare the patch location to the cursor location.
And I decided it's a good idea to store the data loaded from the input file in the handles structure. The file would be readin the OpeningFcn, like you had it, but I didn't have that file, so I just hard-coded some values. Keeping that information in the handles structure is useful because you need it when you click Next in order to create the next patch, without having to read the file again. And because a patch is created on starting the program and also when Next is clicked, I made a helper function (called create_patch()) that does the actual creation of the patch (and deletion of the old one, if it exists). Then that helper function is called from OpeningFcn and the Next callback. This simplifies the code in those two places as well.
@_ Thank you very much . It was quite hectic for me... Been working on this for a While . However , i have 2 issues .
1) After clicking on the Next button like 3 to 4 times , the problem of the deleting the old one appears.
2) I would like that when the region turns green, the motor start vibrating and when it is out of the region it stops vibrating. Am i not supposed to put the arduino code in the OpeningFcn and Next button callbacks? Or is it in the finger_windowbuttonmotion callback?
The problem is that I cannot put that code under the Next buttor since there is no "Indicator" that will tell me when the region is changing colors.
a) Start vibrating =writeline(handles.arduinoObj, "4&MOTOR_1_2_3_4&0!");
b)Stop vibrating= writeline(handles.arduinoObj, "0&MOTOR_1_2_3_4&0!");
Attached is the excel sheet and the code. I have modified a lil bit.
1) I included an if statement in the Next button callback which checks if you're already on the last region, and if so, then do nothing (return). This may be what you are observing. You can modify it to behave differently, but you want to avoid trying to index off the end of your data, so some check is necessary there.
2) I think the window button motion function is the place to interact with the Arduino. That function is called not only when the mouse moves but is also called from create_patch(), which is called whenever a new patch is made (i.e. from opening fcn and Next callback), so that should cover all possibilities.
1) After trying it with your data, I see what the problem is here: The regions 5 and 7 (the last two "vertical" regions) in the data are outside the x-limits of the axes specified in the code (which is [-5 0] for a vertical line).
Maybe set the XLim and YLim each time the patch is created. Since axis 'equal' is also used, this seems to work for this data. See attached.
@_ unfortunately, it did not fix it...It went worse
What's worse?
The code I attached most recently worked for me.
@_ Like each time i am having 2 lines instead of one. By running your code , i am having the same issue.
furthermore what about the running motors where should i put them?
The multiple patches is because of this part in your opening function:
%Vertical line
if handles.v_or_h == 0
handles.region1 = patch([handles.v_thick1 handles.v_thick2 handles.v_thick2 handles.v_thick1],[-10 -10 10 10],'red');
xlim([-5 0])
grid on
%Horizontal line
elseif handles.v_or_h == 1
handles.region1= patch([-10 10 10 -10],[handles.h_thick1 handles.h_thick1 handles.h_thick2 handles.h_thick2],'red');
ylim([0 5])
grid on
end
handles.region1 = [];
create_patch(handles);
This creates a patch in axes1, then overwrites handles.region1 to [] but the patch remains in the axes. Then another patch is created in create_patch(), and the old one is not deleted because it is no longer stored in handles.region1.
There is no need to create any patches except by using the function create_patch() (that's what it's for). Therefore, you can remove that if/else block in the opening function. Refer to my latest code to see how it is there. (I'm loading the data differently but that's not related.)
[Also, you may notice that I don't store v_thick1, etc., in the handles structure (i.e., individual elements from the arrays v_thickness_1, etc.) because they don't need to be there - the entire arrays are stored in handles and the appropriate element is grabbed and used when needed in create_patch().]
About the motors: "2) I think the window button motion function is the place to interact with the Arduino. That function is called not only when the mouse moves but is also called from create_patch(), which is called whenever a new patch is made (i.e. from opening fcn and Next callback), so that should cover all possibilities."
@_ Thank you. That problem has been fixed. Do i need to initialize the arduino in the openingFcn?
No problem.
Yes, initializing the arduino in openingFcn makes sense to me, but I have not used an arduino with MATLAB so I don't know exactly what that entails or what pitfalls there may be.
@_ sorry for disturbing you again....
I would like to edit the code with this. But the code is in appdesigner,i dont know how to implement this in guide.
function cursorPositionFeedback(app, hobj, inout)
% Responds to cursor entering/exiting vertical band
persistent timein
switch inout
case 'in'
hobj.FaceColor = 'g';
timein = datetime('now');
case 'out'
hobj.FaceColor = 'c';
timeInPatch = seconds(datetime('now')-timein);
ax = ancestor(hobj, 'axes');
cp = ax.CurrentPoint;
text(ax, 0.52, cp(1,2), sprintf('%.3f sec.', timeInPatch), ...
'HorizontalAlignment','Left', ...
'VerticalAlignment','bottom', ...
'FontSize', 12, ...
'FontWeight', 'bold', ...
'Color', 'g')
end
end
function WindowButtonMotion(uifig, event, ax)
% Responds to cursor moving in figure window.
cp = ax.CurrentPoint;
isInAxes = cp(1,1) >= ax.XLim(1) && ...
cp(1,1) <= ax.XLim(2) && ...
cp(1,2) >= ax.YLim(1) && ...
cp(1,2) <= ax.YLim(2);
if isInAxes
plot(ax, cp(1,1), cp(1,2), 'k.')
end
end
That code looks like it is using an iptPointerManager, which is not something I have worked with before. It may be possible to still use an iptPointerManager in your existing GUIDE code, but I don't think it's really necessary.
It looks like that function cursorPositionFeedback creates a text when the cursor exits the patch region that shows the amount of time the cursor was over the patch. You can achieve the same thing with something like the following.
First, in your OpeningFcn, create the text object and additional variables that say whether the cursor is currently on the patch and when the cursor last entered the patch region:
handles.time_text = text(handles.axes1);
handles.on_patch_region = false;
handles.time_entered_patch_region = NaN;
Then in finger_WindowButtonMotionFcn, you could have some logic like this (which replaces the block currently at the bottom of that function, where the patch's FaceColor is set):
if x >= p_x(1) && x <= p_x(2) && y >= p_y(1) && y <= p_y(2)
set(handles.region1,'FaceColor','g');
if ~handles.on_patch_region
handles.on_patch_region = true;
handles.time_entered_patch_region = datetime('now');
end
else
set(handles.region1,'FaceColor','r');
if handles.on_patch_region
handles.on_patch_region = false;
set(handles.time_text, ...
'String',sprintf('%.3f sec.', seconds(datetime('now')-handles.time_entered_patch_region)), ...
'Position',[0 0]); % update the Position too if you want to
end
end
% now it is necessary to store the updated handles structure
% because handles.on_patch_region, etc., might have changed
guidata(hObject,handles);

Melden Sie sich an, um zu kommentieren.

Antworten (1)

Cris LaPierre
Cris LaPierre am 19 Feb. 2022
Bearbeitet: Cris LaPierre am 20 Feb. 2022
See the demo towards the bottom of this page.

2 Kommentare

@Cris LaPierre Well, I am working on Guide not in appdesigner
I think guide do not support that action whit mouse, in the other hand app designer can do it

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu App Building finden Sie in Hilfe-Center und File Exchange

Kommentiert:

am 23 Feb. 2022

Community Treasure Hunt

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

Start Hunting!

Translated by