.st0{fill:#FFFFFF;}

Raspberry Pi with MATLAB and Simulink 

 November 12, 2019

By  

What are you going to learn in this article?

In this article, we will be covering some interesting hobby project with Raspberry Pi using MATLAB & Simulink. By the end of this article, you will learn the basics of Raspberry Pi and how to program it using MATLAB & Simulink. 
Following are the interesting things that are we going to do in this article using MATLAB & Simulink on Raspberry Pi
  1. Blinking LED i.e. 'Hello World' of Hardware
  2. Sending motion detection data PIR 
Yup, it’s a lot of amazing things you going to learn. Don’t fear. We are here to help you so these things will look easier to you all.

What all things you need to required for this article?

First of all, you need a MATLAB R2017b or later and Raspberry Pi 3 Model B or B+. So now let’s start with our article. Let’s wrap the information quickly so we can start with our micro project that you will feel amazing to do.

What is Raspberry Pi?

The Raspberry Pi is a low cost, credit-card sized computer that plugs into a computer monitor or TV, and uses a standard keyboard and mouse.

What is MATLAB & Simulink?

MATLAB is a programming platform designed specifically for engineers and scientists. The heart of MATLAB is the MATLAB language, a matrix-based language allowing the most natural expression of computational mathematics.

MATLAB combines a desktop environment tuned for iterative analysis and design processes with a programming language that expresses matrix and array mathematics directly.

Simulink is a block diagram environment for multidomain simulation and Model-Based Design. It supports system-level design, simulation, automatic code generation, and continuous test and verification of embedded systems. Simulink provides a graphical editor, customizable block libraries, and solvers for modelling and simulating dynamic systems. It is integrated with MATLAB, enabling you to incorporate MATLAB algorithms into models and export simulation results to MATLAB for further analysis.

Why MATLAB & Simulink for programming Raspberry Pi?

MATLAB & Simulink are being used in this article cause MATLAB has an extensive processing ability i.e. it can process matrix of data and it has a lot of inbuilt functions thus when programming Raspberry Pi all the processing capability along with all the inbuilt functions can be used making the complex tasks simple.

Also, Simulink provides an option of visual programming which helps us visualise the flow of data in the components forming the entire circuit.

Because of these advantages, we are using MATLAB & Simulink for programming Raspberry Pi.

Setup – Support Package

Before starting, we have to install

  • MATLAB Support Package for Raspberry Pi hardware

  • Simulink Support Package for Raspberry Pi hardware

Let’s see how to install it.

Start by opening the MATLAB and then click on Add-Ons present in the Home section of the menu. Then in the sub-menu click on the Get Hardware Support Packages as shown in the image.

image 20190910 143008 | Raspberry Pi with MATLAB and Simulink | MATLAB Helper ®

A new window Add-Ons explorer pops up, which has all the available hardware support packages which can be installed if needed. As we don't need all of them, let us just search for our support package which is “MATLAB support package for Raspberry pi Hardware” first one which has the same name as the bold text here, click on that as shown in the image below.

image 20190910 143657 | Raspberry Pi with MATLAB and Simulink | MATLAB Helper ®

Which takes us to our next window where you can read an overview of the hardware package and also a note about which versions of MATLAB does this package support. You would also notice a blue colour Learn More button on the right- top side of the window followed by an install button. To install this support package you just need to click on that install button and then sit and relax as it downloads and installs the support packages for you.

After this, we are left with Simulink support packages for raspberry pi hardware.

As we opened the Add-Ons window earlier we can directly type in the search bar “Simulink Support Package for Raspberry pi Hardware“ and then click enter. If at all you closed the Add-Ons window you can just reopen it by following the starting steps of installation of MATLAB support packages for Raspberry pi Hardware. and then typing the “Simulink Support Package for Raspberry pi Hardware“ in the search bar.

image 20190910 152653 | Raspberry Pi with MATLAB and Simulink | MATLAB Helper ®

Click on the Simulink Support Package for Raspberry Pi Hardware link shown in the image above.
Which takes us to our next window where you can read an overview of the hardware package and also a note about which versions of MATLAB does this package support. You would also notice a blue colour Learn More button on the right- top side of the window followed by an install button. To install this support package you just need to click on that install button and then sit and relax as it downloads and installs the support packages for you.

There we go we are done with installing the support packages for Raspberry Pi hardware in our MATLAB.

Setup-Booting Raspberry Pi

First, we need to download the image of the OS which can be burned into the Micro SD card. Before I say you where to download it from there is a small issue I need to discuss. Raspberry Pi comes in different models starting from Raspberry Pi zero to the latest one Raspberry Pi 4. But till now MATLAB has a supported OS till Raspberry Pi 3 B plus. So if at all you bought a Raspberry Pi 4, well don't worry I have a solution to the problem you might face in the troubleshooting section of this page.

A New Raspberry Pi :

If you got a new R-Pi then you have to install an OS in it and you can follow the below steps to do so. Before you start you need a Micro SD card of minimum 4GB storage space and a connector to connect it to your computer.

Step: 1

Open MATLAB and click on the Add-Ons present in the home section of the menu in the top. Now click on the Manage Add-Ons which pops a new window.

image 20190910 143008 | Raspberry Pi with MATLAB and Simulink | MATLAB Helper ®

Step: 2

In this New window know as Add-On Manager you will find all the available support packages that you have downloaded. There you have to search for our recently downloaded support package i.e. MATLAB support package for Raspberry Pi Hardware. You will find a small gear like figure on the right side of the support package saying setup.

image 20190915 114311 | Raspberry Pi with MATLAB and Simulink | MATLAB Helper ®

When you click on it a new window pops up with an R-Pi image on it as shown in the figure below.

Step: 3

There is a drop-down menu beside the Hardware board where you can select the model of your R-Pi.

image 20190915 114515 | Raspberry Pi with MATLAB and Simulink | MATLAB Helper ®

It has all the options starting from model R-Pi zero to R-Pi 3 B plus. After you select your model click on Next. Which takes you to the next page with two options.

image 20191010 192928 | Raspberry Pi with MATLAB and Simulink | MATLAB Helper ®

Since we don’t have a Rasbian OS already we select the first option and then click on Next.

image 20191010 193037 | Raspberry Pi with MATLAB and Simulink | MATLAB Helper ®

Here you see a MathWorks provided Rasbian OS which can be downloaded by clicking on the download button. After you are done downloading the file click on Next. Where you have to Browse the Files and select the file that you have downloaded or you can just add the path/address of the file that you just downloaded in the given space and then press validate. If the file that you downloaded is correct it shows a message saying valid Raspbian image. Then you have to click on Next.

image 20190915 115703 | Raspberry Pi with MATLAB and Simulink | MATLAB Helper ®

Below screenshot shows the process of extracting and validating the Raspbian Image.

Validate 01 | Raspberry Pi with MATLAB and Simulink | MATLAB Helper ®

After valid Raspbian Image, you will get the below status. Congrats for successful validation.

Validate done | Raspberry Pi with MATLAB and Simulink | MATLAB Helper ®

Step: Network Settings

After validation, we have to select the network configuration from four option that are given

We will select Connect to wireless network since most of us use a wireless connection for internet and data transfer.

image 20191010 194220 | Raspberry Pi with MATLAB and Simulink | MATLAB Helper ®

Step: Wireless Configuration

Now you have to enter Wifi Name “SSID“ and password. We have got two types of IP assignment. One Automatic and other Manually. I would suggest you select Manually enter IP address so we can know the IP address of Raspberry Pi easily.

In this, we use IPv4 we have 4 octets separated by a dot. First three octet must be same of IP address and Default Gateway. For knowing your Default Gateway enter ipconfig in your cmd(Command Prompt) for Windows user.

The output shown in below image will be there.

ipconfig | Raspberry Pi with MATLAB and Simulink | MATLAB Helper ®

You can see Default Gateway as 192.168.0.1. You can enter any number in fourth octet of IP address from 2 to 255 that is not used by other devices if other devices are connected.

image 20191010 193121 | Raspberry Pi with MATLAB and Simulink | MATLAB Helper ®

Please enter the SSID (Wifi Name) and password of your router or hotspot.

Step: Select a Drive

For this procedure, you will need two things

  • Micro SD card reader

  • Micro SD card (at least 4GB) - make sure you have formatted your SD card

You can use SD Card Formatter for formatting it. Now insert the Micro SD card into your PC and select it. If it is not showing then click on the Refresh button and your SD card will appear.

image 20191010 193143 | Raspberry Pi with MATLAB and Simulink | MATLAB Helper ®

Step: Write Firmware

It can take time for writing firmware. Normally it depends upon your PC specs.

image 20191010 193215 | Raspberry Pi with MATLAB and Simulink | MATLAB Helper ®
image 20191010 193236 | Raspberry Pi with MATLAB and Simulink | MATLAB Helper ®
Hardware 01 1 | Raspberry Pi with MATLAB and Simulink | MATLAB Helper ®
Hardware 02 | Raspberry Pi with MATLAB and Simulink | MATLAB Helper ®
image 20191010 193310 | Raspberry Pi with MATLAB and Simulink | MATLAB Helper ®

Step: Another way of checking hardware connection

checking | Raspberry Pi with MATLAB and Simulink | MATLAB Helper ®

Troubleshooting Raspberry Pi 4:

If you have already installed an OS in your Raspberry Pi 2/3 or you have a New Raspberry Pi 4 and don’t want to reboot the OS, you have but one option.

MATLAB has included customization of OS option starting from MATLAB release 2017b.

For customization of OS follow the below steps.

Note: For Raspberry Pi 4 Mathworks has not yet released an OS so if at all you have a new Raspberry Pi and want Raspbian OS you can download from the link mentioned below. You will also need software for burning the image into the micro SD card, you can use any software but I did provide a link for you to download one such software.

Raspbian OS: https://www.raspberrypi.org/downloads/raspbian/

Balena Etcher: https://www.balena.io/etcher/

Steps for customization of OS:

First, open MATLAB and then click on Add-Ons present in the Home section of the menu on the top. Click on the drop-down menu and then click on Add-Ons manager.

Add-Ons Manager window opens and on the top right side, a search bar is present.

image 20190910 143008 | Raspberry Pi with MATLAB and Simulink | MATLAB Helper ®

Start typing in the search bar “MATLAB Support Packages for Raspberry Pi Hardware“ and then click on enter. In the search results, you will find MATLAB Support Packages for Raspberry Pi Hardware with a settings symbol on the right side as shown in the figure.

image 20190915 114311 | Raspberry Pi with MATLAB and Simulink | MATLAB Helper ®

Click on the setup and a new window “Hardware Setup“ pops as shown below. In this, you can see the Hardware Board, there you have to select the model of your Raspberry Pi. (Note: if you have a Raspberry Pi 4 and don't see any option in the Hardware Board just select Raspberry Pi 3 Model B+)

image 20190915 114515 | Raspberry Pi with MATLAB and Simulink | MATLAB Helper ®

Click on Next and you will see the next window with two options. As shown in the figure below.

image 20191010 192928 | Raspberry Pi with MATLAB and Simulink | MATLAB Helper ®

Now select the second option i.e. “Customize the existing operating system running on my hardware” since we are not booting a new OS instead customizing the existing OS. After you select the option click on Next. Then you will be asked to enter the Device address where you have to enter the IP address of your Raspberry Pi. and In device username enter the Pi user ID and then in the device password type the password of your Rpi and then click on Test connection button.

image 20191010 193916 | Raspberry Pi with MATLAB and Simulink | MATLAB Helper ®

Then if it is MATLAB is able to connect to the Raspberry Pi then you will see a figure as shown below.

image 20191010 193443 | Raspberry Pi with MATLAB and Simulink | MATLAB Helper ®

Now click on Next to proceed to the next window, where all the required software packages are listed in two different columns as shown below.

image 20191010 193537 | Raspberry Pi with MATLAB and Simulink | MATLAB Helper ®

Now click on Next, then you will see an Install button in the window as shown below. Click on Install to install the software packages and libraries, but before you click on install make sure that the Raspberry Pi is connected to internet.

image 20191010 193600 | Raspberry Pi with MATLAB and Simulink | MATLAB Helper ®

After successful installation you can click on next 

image 20191010 193619 | Raspberry Pi with MATLAB and Simulink | MATLAB Helper ®

The next window has four options i.e I2C module, SPI module, Serial(UART) module and Camera module. You can individually choose if you want to enable or disable these modules. Don’t worry even if you disable them now and want to use them later you can enable them through MATLAB using a single command.

image 20191010 193640 | Raspberry Pi with MATLAB and Simulink | MATLAB Helper ®

Now click on Next to move to the next window which has 2 option Reboot now and Reboot later. Better select Reboot now as the changes that you made till now will be effective only after a successful reboot. thus click on Reboot now and then click on Next.

image 20191010 193709 | Raspberry Pi with MATLAB and Simulink | MATLAB Helper ®

That’s it congratulations you are with customizing the OS. Now to check if we are able to interface Raspberry pi with MATLAB type the command as shown in the figure

>>mypi=raspi('IP Address of RPi','Rpi username','Rpi password')

image 20190919 163918 | Raspberry Pi with MATLAB and Simulink | MATLAB Helper ®

if you see something like the above image everything is working fine and you just interfaced MATLAB with Raspberry Pi.

If you get an error message as shown below:

>> r = raspi()
### Updating Raspberry Pi I/O server...
### Connecting to board...
### Connected to 172.29.43.43...
### Creating server folder...
### Transferring source files...
### Building MATLAB I/O server...
Error executing command "make -C /opt/MATLAB/server_v19.1.0 -f Makefile". Details:
STDERR: handler.c: In function ‘updateSourceInfoâ€:
handler.c:435:41: warning: ‘,0†directive writing 2 bytes into a region of size
between 0 and 2 [-Wformat-overflow=]
sprintf(pData->audioCard, "plughw:%d,0", cardType);
^~
handler.c:435:5: note: ‘sprintf†output between 11 and 13 bytes into a destination of size 10
sprintf(pData->audioCard, "plughw:%d,0", cardType);
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
I2C.c: In function ‘I2C_openâ€:
I2C.c:29:23: warning: unused variable ‘i2c_funcs†[-Wunused-variable]
unsigned long i2c_funcs = 0;
^~~~~~~~~
I2C.c: In function ‘EXT_I2C_readRegisterâ€:
I2C.c:74:24: error: array type has incomplete element type ‘struct i2c_msgâ€
struct i2c_msg msg[2];
^~~
I2C.c:83:24: error: ‘I2C_M_RD†undeclared (first use in this function); did you mean ‘I2C_open�
msg[1].flags = I2C_M_RD | I2C_M_NOSTART; // Read
^~~~~~~~
I2C_open
I2C.c:83:24: note: each undeclared identifier is reported only once for each function it appears in
I2C.c:83:35: error: ‘I2C_M_NOSTART†undeclared (first use in this function)
msg[1].flags = I2C_M_RD | I2C_M_NOSTART; // Read
^~~~~~~~~~~~~
I2C.c:74:24: warning: unused variable ‘msg†[-Wunused-variable]
struct i2c_msg msg[2];
^~~
I2C.c: In function ‘EXT_I2C_writeRegisterâ€:
I2C.c:110:24: error: array type has incomplete element type ‘struct i2c_msgâ€
struct i2c_msg msg[2];
^~~
I2C.c:122:24: error: ‘I2C_M_NOSTART†undeclared (first use in this function)
msg[1].flags = I2C_M_NOSTART; // Write
^~~~~~~~~~~~~
I2C.c:110:24: warning: unused variable ‘msg†[-Wunused-variable]
struct i2c_msg msg[2];
^~~
I2C.c: In function ‘EXT_I2C_writeâ€:
I2C.c:148:24: error: storage size of ‘msg†isnâ€t known
struct i2c_msg msg;
^~~
I2C.c:148:24: warning: unused variable ‘msg†[-Wunused-variable]
I2C.c: In function ‘EXT_I2C_readâ€:
I2C.c:178:24: error: storage size of ‘msg†isnâ€t known
struct i2c_msg msg;
^~~
I2C.c:182:21: error: ‘I2C_M_RD†undeclared (first use in this function); did you mean ‘I2C_open�
msg.flags = I2C_M_RD;
^~~~~~~~
I2C_open
I2C.c:178:24: warning: unused variable ‘msg†[-Wunused-variable]
struct i2c_msg msg;
^~~
make: *** [Makefile:56: obj/I2C.o] Error 1

Then you did nothing wrong just don’t worry.

Actually with the new version of Raspbian OS, “Raspbian Buster”, some header files of “i2c-dev” library got re-organized and I2C source code is not compatible with the same. MATLAB IO server needs to be updated to fix this issue.

As a result, users working with this newer OS image and running OS customization from our Raspberry Pi Support Package during Hardware Setup will get this build error while trying to run the command “r=raspi()”, or when using the I2C block from Simulink and trying to build the model.

MATLAB releases R2017b, R2018a, R2018b, and R2019a will be affected by this error as OS Customization support has been available from R2017b.

Is there no solution to this?

Well, there is for solving this error you need to type edit two source files. We follow this step by step.

First MATLAB and then Simulink OK?

For solving the error in MATLAB first type below command in command window of MATLAB.

>>edit(fullfile(raspi.internal.getRaspiRoot,'server','I2C.c'))

This command opens a file I2C.c to which you have to add a small 3 line code as shown below

#ifndef I2C_M_RD

           #include<linux/i2c.h>

#endif

image 20191010 193732 | Raspberry Pi with MATLAB and Simulink | MATLAB Helper ®

Then save the file and close it and now try running the command, you will notice that build error will not pop up and interfacing works.

Next is the problem in Simulink.

For solving the I2C related issues in Simulink type the below command in the command window of MATLAB.

>>edit(fullfile(codertarget.raspi.internal.getSpPkgRootDir,'src','MW_I2C.c'))

This command opens a file MW_I2C.c to which you have to add a small three-line code as shown below.

#ifndef I2C_M_RD

           #include<linux/i2c.h>

#endif

image 20190919 165828 | Raspberry Pi with MATLAB and Simulink | MATLAB Helper ®

Now everything is done you will find that Built error or error related to I2C will no longer pop.

Get instant access to the code, model, or application of the video or article you found helpful! Simply purchase the specific title, if available, and receive the download link right away! #MATLABHelper #CodeMadeEasy

Ready to take your MATLAB skills to the next level? Look no further! At MATLAB Helper, we've got you covered. From free community support to expert help and training, we've got all the resources you need to become a pro in no time. If you have any questions or queries, don't hesitate to reach out to us. Simply post a comment below or send us an email at [email protected].

And don't forget to connect with us on LinkedIn, Facebook, and Subscribe to our YouTube Channel! We're always sharing helpful tips and updates, so you can stay up-to-date on everything related to MATLAB. Plus, if you spot any bugs or errors on our website, just let us know and we'll make sure to fix it ASAP.

Ready to get started? Book your expert help with Research Assistance plan today and get personalized assistance tailored to your needs. Or, if you're looking for more comprehensive training, join one of our training modules and get hands-on experience with the latest techniques and technologies. The choice is yours – start learning and growing with MATLAB Helper today!

Education is our future. MATLAB is our feature. Happy MATLABing!

About the author 

  • May Sapal Thant says:

    Hello.. I use “Set up hardware with Mathworks Rasbian Image”. And in the stage of “Firmware Write”, I can write that firmware to my SD card till the end. But after writing, I can’t “Next” for next stage. It shows “Can’t access SD card”. I can’t continue my way… Kindly advice me.. thank you

    • Abhishek Agrawal says:

      It happens some time when the user hasn’t formatted the SD card using SD formatting tool and some times due to loose connection between card reader and PC. Please try to format the SD card using proper formatting tool that can be downloaded from sdcard.org and repeat the same process again. Hope this solves your problem !

  • الأستاذ وليد بن شوش لرياضيات المتوسط says:

    This is amazing, thanks for sharing, i have done all of this, turned some LEDs using GPIO pins, and many other stuff, however, i can’t get the ultrasonic sensor from arduino hc sr to work with the raspberry and matlab, can you please post a small thing about it.

  • {"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}

    MATLAB Helper ®

    Follow: YouTube Channel, LinkedIn Company, Facebook Page, Instagram Page

    Join Community of MATLAB Enthusiasts: Facebook Group, Telegram, LinkedIn Group

    Use Website Chat or WhatsApp at +91-8104622179

    >