Simple turn on Lamp with switch in app designer

33 visualizzazioni (ultimi 30 giorni)
keaton
keaton il 11 Giu 2024
Modificato: Adam Danz il 25 Giu 2024
I am trying to learn about app designer and have tried to make a basic app that turn the lamp GREEN if the switch is ON, and RED if the switch is OFF. For some reason there is no change in color of the lamp? I am using R2023a version of matlab.
function SwitchValueChanged(app, event)
disp('SwitchValueChanged callback triggered'); % Confirm function call
value = app.Switch.Value;
disp(['Switch value: ', value]); % Display switch value
if strcmp(value, 'on')
disp('Setting lamp color to green') % Debugging message
set(app.Lamp,'Color','green')
elseif strcmp(value, 'off')
disp('Setting lamp color to red') % Debugging message
set(app.Lamp,'Color','red')
end
end

Risposte (2)

Shivani
Shivani il 11 Giu 2024
Hello @keaton,
I am not able to reproduce the issue with the given code snippet, so I may not be able to provide the most accurate solution. However, upon analyzing the code snippet shared, it is my understanding that the property to set the color of a lamp is not directly set using `set(app.Lamp, 'Color', 'green')` as you would in traditional MATLAB GUI programming (using set/get with handles). Instead, you work directly with the property of the component.
You can refer to the following code snippet for an example on how this can be done:
function SwitchValueChanged(app, event)
disp('SwitchValueChanged callback triggered'); % Confirm function call
value = app.Switch.Value;
disp(['Switch value: ', value]); % Display switch value
if strcmp(value, 'On')
disp('Setting lamp color to green') % Debugging message
app.Lamp.Color = 'green'; % Directly set the Color property
elseif strcmp(value, 'Off')
disp('Setting lamp color to red') % Debugging message
app.Lamp.Color = 'red'; % Directly set the Color property
end
end
I referred to the following documentation to understand the implementation details of sharing data within App Designer: https://www.mathworks.com/help/matlab/creating_guis/share-data-across-callbacks-in-app-designer.html
Hope this helps!

Adam Danz
Adam Danz il 11 Giu 2024
Modificato: Adam Danz il 25 Giu 2024
The problem is that the values the switch returns are On and Off with capital letters. Your string comparison is case sensitive so On (upper case O) does not match on (lower case o) and Off does not match off.
if strcmp(value, 'on')
^
elseif strcmp(value, 'off')
^
Change the values to
if strcmp(value, 'On')
^
elseif strcmp(value, 'Off')
^
or use strcmpi which ignore case.

Categorie

Scopri di più su Develop Apps Using App Designer in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by