- Create a Python script that implements your neural network controller. This script should take the motor RPM as input and return the PWM signal as output. Make sure your script is compatible with the version of Python installed on your system.
- Save the Python script as a ‘.py’ file on your computer.
- In Simulink, add a ‘MATLAB Function’ block to your model. This block will act as a wrapper for your Python function.
- Double-click on the ‘MATLAB Function’ block to open the block dialog.
- Define the inputs and outputs of the ‘MATLAB Function’ block to match the input and output of your Python function. For example, you may have an input for motor RPM and an output for the PWM signal.
- Inside the MATLAB Function block, use 'coder.extrinsic' and 'pyrunfile' to declare the function as an extrinsic function and execute the Python script. Here's an example code snippet:
Run Python function from inside Simulink
3 views (last 30 days)
Show older comments
Hello!
I have a simulink electric motor example that is being controlled via PWM.
I want the controller that spits out the PWM to be a Python function ( a NN controller I have written in Python INPUT: motor rpm OUT: PWM signal) -- and it returns in real time floating point numbers. e.g. 2,504; 2,103 etc.
I want that to be the input for the PWM block in the Simulink model. And the output of the electric motor (rpm) to be the input for the Python function (I have a special measurement input for that function).
Has anybody had any succes with linking .py files and Simulink ?
__________________________________________________________________________________________________________
And to run the python files, do I need to containerize them or to do something special ? Because there are 5 files in the whole project which I will need. I cannot run the function alone.
Thanks a lot!
0 Comments
Answers (1)
arushi
on 16 Aug 2024
Hi Andrei Tulbure
Yes, it is possible to link Python functions and Simulink models. The ‘MATLAB Function’ block in Simulink can be utilized to invoke Python functions and exchange data between Simulink and Python.
Here's an approach to achieve the desired integration between Simulink and your Python function:
function pwm_signal = myPythonController(rpm)
coder.extrinsic('pyrunfile');
coder.extrinsic('example');
pwm_signal = 0;
pwm_signal = double(pyrunfile("YourFile.py","OutputVariable",x=rpm))
end
In the code above, 'x' represents the parameter to be passed to your Python file.
7. Now you can run your model to observe the integration
For further details and additional information, you can consult the following documentation:
0 Comments
See Also
Categories
Find more on Call Python from MATLAB in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!