On/off button matlab designer

21 views (last 30 days)
Kizito Amungwa Achembong
Kizito Amungwa Achembong on 6 Jul 2021
Answered: Pratyush on 19 Apr 2024
Hello, I am designing an app to control a switch in simulink. I want to use a single switch from app designer to turn the swicht in simulink on and off. But unfortunately it works only one way. It turns the switch on but it stays that way through out the simulation even when i turn the switch off in the app. Am not sure if there is some other way to go about it. Below is my code in app designer.
This will be enough for my project but I will also like to ask if it is possible to have a button that the first push turns the switch on and the second push turns it off.
% Startup function
function startupFcn(app)
app.UIFigure.Visible = 'off';
movegui(app.UIFigure,"center");
app.UIFigure.Visible = 'on';
set_param('ChargingProcess/ChargeMyCar','sw','0');
set_param('ChargingProcess/Hello, I am back soon','sw','0');
end
% Code to control switch
function Charge1SwitchValueChanged(app, event)
value = app.Charge1Switch.Value;
if strcmp(value,'off')
set_param('ChargingProcess/ChargeMyCar','sw','0');
else
set_param('ChargingProcess/ChargeMyCar','sw','1');
end
end

Answers (1)

Pratyush
Pratyush on 19 Apr 2024
Hi Kizito,
To control a switch in Simulink from an App Designer UI and ensure it toggles correctly throughout the simulation, follow these steps:
Check Simulation Setup: Ensure the Simulink model allows parameter changes during the simulation, preferably in 'Normal' mode, and that your switch logic is part of a discrete system for continuous checking.
Implementing a Toggle Button:
  • Add a private property, ToggleState, to track the switch state.
  • In the button push function, toggle this state between true and false.
  • Update the Simulink switch parameter ('sw') based on the ToggleState.
properties (Access = private)
ToggleState = false; % Initialize as off
end
function ToggleSwitchButtonPushed(app)
app.ToggleState = ~app.ToggleState; % Toggle the state
set_param('ChargingProcess/ChargeMyCar', 'sw', app.ToggleState ? '1' : '0'); % Update Simulink switch
end
Ensure Correct Configuration:
  • Verify the simulation mode supports real-time updates.
  • Confirm the path and parameter name used in set_param calls are correct.

Categories

Find more on Develop Apps Using App Designer in Help Center and File Exchange

Products


Release

R2020b

Community Treasure Hunt

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

Start Hunting!