0% found this document useful (0 votes)
29 views

Raspberry Matlab

Uploaded by

Monica Hernandez
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views

Raspberry Matlab

Uploaded by

Monica Hernandez
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

What is going on, everybody.

My name is Meeshawn, and welcome to this video on


how to deploy MATLAB algorithms to Raspberry Pi. For a while, we have been
deploying algorithms from Simulink to Raspberry Pi. In this video, I will show you how
to deploy your MATLAB code to the Raspberry Pi hardware. I will help you get started
with a simple LED blink example. I will show you how to write MATLAB code to deploy
it on Raspberry Pi. Later, I will show a more complex edge detection example.

Let's quickly take a look at the things you will require-- a Raspberry Pi board powered
by a micro USB cable, and ethernet cable, a USB webcam, which is a V4L2-supported
webcam, and of course, MATLAB. You can use any Raspberry Pi board supported by
your MATLAB release. However, this example requires you to have MATLAB release
2018 and higher. For this video demonstration, I have used a Raspberry Pi 3 Model B
board. The webcam will be used for the edge detection example discussed towards
the end of the video. You will also need MATLAB Coder product, along with MATLAB
for code generation.

All right, so now that we are aware of the prerequisites, let's get started in MATLAB. In
order to work with Raspberry Pi in MATLAB, you would first need to install the MATLAB
Support Package for Raspberry Pi. The Support Package enables you to communicate
with the Raspberry Pi hardware remotely from a computer running MATLAB. It
includes a MATLAB command line interface for accessing the hardware's peripherals
and communication interfaces. To know more about the Support Package, refer to this
documentation with the help of this command.

Let's begin by creating a raspi object to connect to the hardware from MATLAB. If this
is the first time that you are connecting with the Raspberry Pi hardware, then you might
be prompted to enter the IP address, username, and password, as well. Using this
interface, you can collect data from sensors connected to the Raspberry Pi hardware
through SBI and I2C buses, process them in MATLAB and actual devices attached to a
Raspberry Pi hardware.

For example, you can set the on-board green LED on or off using the method writeLED.
In short, the Support Package lets you interactively control the Raspberry Pi hardware
from MATLAB. The Raspberry object also provides methods to execute Linux
commands on the Raspberry Pi hardware.

All right, so now let's create a script using this command to blink the LED. In addition
to this, let us perform some file operations as well on the Raspberry Pi hardware. For
this purpose, let's create an empty text file. W means write permission here.

Next, let's write a for loop to blink the LED for, let's say, seven times. Let's implement a
period of one second using the pause function. The pause function is Codegen
compatible for Linux boards. At the end of the cycle, we will write the count of the blink
operations to the file we just created. End of the loop. Now, after writing the data, let's
close the file and save the script. Let's call it blinkNWrite since we are doing both LED
blink and file write operations.

All right, so now let's take a look at a typical work flow to deploy algorithms to
Raspberry Pi hardware. The first step in the workflow is to create a MATLAB function.
We just created a MATLAB script a moment ago. And now we will be adding the
keyword function at the top, followed by the name of the function.

In order to deploy an algorithm to the Raspberry Pi hardware, it is required that we


implement the script as a MATLAB function. Currently, as of MATLAB 2019b, you can
deploy MATLAB functions without any input/output arguments. All right, so our next
step in the workflow is to execute this MATLAB function. Clicking on red button or
pressing F5 will run the function in MATLAB and control the LED on-board Raspberry Pi
based on the logic implemented in the function.

Right, so now we can see a file, sample.txt, has been created in the current directory.
And as you can see here, the LED has started to blink. And it just completed doing so 7
times. Now, let's open this file. Blinking on-board LED for count is equal to one up to
seven. Perfect. So our MATLAB function just toggled the LED and created a file in the
current working directory of MATLAB. Let's delete this file for now.

So this is the connected I/O workflow, wherein MATLAB interacts and controls the
peripherals of the Raspberry Pi hardware, which in this case is the on-board LED of the
Raspberry Pi hardware. Next, we look at deploying this MATLAB function to the
hardware. In this workflow, MATLAB coder will convert the MATLAB function into an
equivalent C C++ code, followed by a build, load, and execute on the hardware. This
executable will run independent of MATLAB, otherwise known as standalone
execution.

We begin by adding the directive on pragma %#codegen after the function signature to
indicate that we intend to deploy the MATLAB function on the hardware. Adding this
directive instructs the MATLAB Code Analyzer to help you diagnose and fix violations
that would result in possible errors during deployment. The Analyzer provides an
indicator at the top right of the editor window. Green glow indicates that no issues
were detected.

And as you can see here, green is displayed at the top for our function. And hence, we
can proceed to the next step. Please note that not all function calls are supported for
code generation. And hence, our next objective is to check for code generation
support.
To fix the unsupported function call errors, you can either declare the function as
coder.extrinsic, or replace the function with an equivalent function call that is
supported for code generation. For more information on coder.extrinsic, search in the
documentation by typing doc coder.extrinsic.

For a list of supported function calls, search in the documentation by typing doc
language support code generation. For a list of Raspberry Pi peripheral functions
submitted for deployment, search the documentation for doc functions supported for
deployment. Luckily in our case, we do not have any unsupported function calls.

Next, we'll talk about two important functions which will help us deploy the MATLAB
function as a standalone on the hardware, which is our final objective. We begin by
creating a hardware configuration object using the function target hardware. For
example, to create a configuration object for the Raspberry Pi hardware enter target
object equals target hardware Raspberry Pi.

The object created helps one to configure various options for deployment, such as the
hardware device address, username, and password. The default username and
password are Pi and Raspberry, respectively. The other options include setting the
Build Directory location on the hardware, build action preferences for deployment,
such as a build, load, and run, or only build, and RunOnBoot option to automatically
execute the function after the hardware is switched on. All these can be configured
prior to deploying the MATLAB function to the hardware.

Now we are ready to deploy our MATLAB function to the Raspberry Pi hardware. And
we will do so with the help of the function deploy. This function deploys the MATLAB
function as a standalone executable on the hardware. It also generates a deployment
report which contains the information about the deployment status.

In case of any errors generated during deployment, you can use the report to debug
the function and verify that the function is suitable for deployment. Additionally, we
must also take care that the MATLAB function to be deployed must not have any input
or output arguments as of MATLAB 2019b release. Deploy, target object, blinkNWrite.

This function requires two arguments, namely the hardware configuration object and
the name of the MATLAB function to be deployed, which is blinkNWrite in our case.
Executing this command will deploy the MATLAB function on the Raspberry Pi
hardware. Code generation is successful, and the code generation report is generated.
As you can see here, the LED is blinking.

The file sample.txt will be returned in a Linux directory, as specified in the Build
Directory of the target hardware configuration object. Note that the file sample.txt is
now generated on Raspberry Pi, unlike the connected I/O workflow, where it got
generated in the MATLAB Working Directory. We can now copy the file from the
hardware into MATLAB by executing these commands-- r is equal to raspi, getfiler,
Build Directory location.

As you can see here, the file pops up in the Working Directory. Let's open this file.
Blinking on-board LED for count equal to one up to seven.

All righty. So far, we have developed a MATLAB function, executed it initially in


MATLAB using the connected I/O workflow, and then successfully deployed it to the
Raspberry Pi hardware. The code generated out of the MATLAB function ran on the
hardware and manipulated the LED independent of MATLAB.

Now let's recap and understand the two workflows discussed so far, connected I/O
and deployment. Connected I/O lets you interact with the hardware and its peripherals
from MATLAB. You can collect data from sensors, process it in MATLAB, and control
the actuators accordingly. Whereas in deployment, code is generated from the
MATLAB function, loaded and executed on the hardware for a standalone execution.

The connected I/O workflow is better for debugging, takes less time to compile, and
hence, is useful for rapid prototyping. However, due to its tethered mode of operation,
a physical connection is always needed. This is to facilitate the on-demand request
response being shared between MATLAB and Raspberry Pi in the connected I/O
workflow. Hence, there is a turnaround time for every step of calculation.

On the other hand, deployment matches production workflows where the code has to
run independent of MATLAB and the host computer used to design the project. The
execution is in real time, as the deployed code doesn't have to wait for MATLAB for
every step of calculation. But it does involve compilation and deploy, which is not very
ideal for debugging and rapid prototyping.

¿Qué está pasando, todo el mundo. Mi nombre es Meeshawn y bienvenido a este


video sobre cómo implementar algoritmos de MATLAB en Raspberry Pi. Durante un
tiempo, hemos estado implementando algoritmos de Simulink a Raspberry Pi. En este
video, le mostraré cómo implementar su código MATLAB en el hardware Raspberry
Pi. Lo ayudaré a comenzar con un ejemplo simple de parpadeo de LED. Le mostraré
cómo escribir código MATLAB para implementarlo en Raspberry Pi. Más adelante,
mostraré un ejemplo de detección de bordes más complejo.

Echemos un vistazo rápido a lo que necesitará: una placa Raspberry Pi alimentada por
un cable micro USB y un cable ethernet, una cámara web USB, que es una cámara web
compatible con V4L2 y, por supuesto, MATLAB. Puede utilizar cualquier placa
Raspberry Pi compatible con su versión de MATLAB. Sin embargo, este ejemplo
requiere que tenga la versión 2018 de MATLAB y superior. Para esta demostración en
video, he usado una placa Raspberry Pi 3 Model B. La cámara web se usará para el
ejemplo de detección de bordes discutido hacia el final del video. También necesitará
el producto MATLAB Coder, junto con MATLAB para la generación de código.

Muy bien, ahora que conocemos los requisitos previos, comencemos con
MATLAB. Para trabajar con Raspberry Pi en MATLAB, primero debe instalar el paquete
de soporte de MATLAB para Raspberry Pi. El paquete de soporte le permite
comunicarse con el hardware Raspberry Pi de forma remota desde una computadora
que ejecuta MATLAB. Incluye una interfaz de línea de comandos de MATLAB para
acceder a los periféricos del hardware y las interfaces de comunicación. Para saber
más sobre el paquete de soporte, consulte esta documentación con la ayuda de este
comando.

Comencemos por crear un objeto raspi para conectarlo al hardware de MATLAB. Si es


la primera vez que se conecta con el hardware Raspberry Pi, es posible que también
se le solicite que ingrese la dirección IP, el nombre de usuario y la contraseña. Con
esta interfaz, puede recopilar datos de sensores conectados al hardware Raspberry Pi
a través de buses SBI e I2C, procesarlos en MATLAB y dispositivos reales conectados
a un hardware Raspberry Pi.

Por ejemplo, puede encender o apagar el LED verde incorporado usando el método
writeLED. En resumen, el paquete de soporte le permite controlar de forma interactiva
el hardware de Raspberry Pi desde MATLAB. El objeto Raspberry también proporciona
métodos para ejecutar comandos de Linux en el hardware Raspberry Pi.

Muy bien, ahora vamos a crear un script usando este comando para hacer parpadear
el LED. Además de esto, realicemos algunas operaciones de archivo también en el
hardware Raspberry Pi. Para este propósito, vamos a crear un archivo de texto
vacío. W significa permiso de escritura aquí.

A continuación, escribamos un bucle for para que el LED parpadee, digamos, siete
veces. Implementemos un período de un segundo usando la función de pausa. La
función de pausa es compatible con Codegen para placas Linux. Al final del ciclo,
escribiremos el recuento de las operaciones de parpadeo en el archivo que acabamos
de crear. Fin del bucle. Ahora, después de escribir los datos, cerremos el archivo y
guardemos el script. Llamémoslo blinkNWrite ya que estamos haciendo operaciones
de escritura de archivo y parpadeo de LED.

Muy bien, ahora echemos un vistazo a un flujo de trabajo típico para implementar
algoritmos en el hardware de Raspberry Pi. El primer paso en el flujo de trabajo es
crear una función de MATLAB. Acabamos de crear un script de MATLAB hace un
momento. Y ahora agregaremos la palabra clave función en la parte superior, seguida
del nombre de la función.

Para implementar un algoritmo en el hardware de Raspberry Pi, se requiere que


implementemos el script como una función de MATLAB. Actualmente, a partir de
MATLAB 2019b, puede implementar funciones de MATLAB sin argumentos de
entrada/salida. Muy bien, nuestro siguiente paso en el flujo de trabajo es ejecutar esta
función de MATLAB. Al hacer clic en el botón rojo o presionar F5, se ejecutará la
función en MATLAB y se controlará el LED integrado en la Raspberry Pi según la lógica
implementada en la función.

Bien, ahora podemos ver que se ha creado un archivo, sample.txt, en el directorio


actual. Y como puede ver aquí, el LED ha comenzado a parpadear. Y acaba de
completarlo 7 veces. Ahora, abramos este archivo. El parpadeo del LED incorporado
para el conteo es igual a uno hasta siete. Perfecto. Así que nuestra función MATLAB
simplemente cambió el LED y creó un archivo en el directorio de trabajo actual de
MATLAB. Eliminemos este archivo por ahora.

Este es el flujo de trabajo de E/S conectado, en el que MATLAB interactúa y controla


los periféricos del hardware Raspberry Pi, que en este caso es el LED integrado del
hardware Raspberry Pi. A continuación, analizamos la implementación de esta función
de MATLAB en el hardware. En este flujo de trabajo, el codificador de MATLAB
convertirá la función de MATLAB en un código C C++ equivalente, seguido de una
compilación, carga y ejecución en el hardware. Este ejecutable se ejecutará
independientemente de MATLAB, también conocido como ejecución independiente.

Comenzamos agregando la directiva sobre pragma %#codegen después de la firma


de la función para indicar que tenemos la intención de implementar la función
MATLAB en el hardware. Al agregar esta directiva, se le indica a MATLAB Code
Analyzer que lo ayude a diagnosticar y corregir infracciones que podrían generar
posibles errores durante la implementación. El Analizador proporciona un indicador en
la parte superior derecha de la ventana del editor. El brillo verde indica que no se
detectaron problemas.

Y como puede ver aquí, se muestra verde en la parte superior para nuestra función. Y
por lo tanto, podemos proceder al siguiente paso. Tenga en cuenta que no todas las
llamadas a funciones son compatibles con la generación de código. Y, por lo tanto,
nuestro próximo objetivo es verificar el soporte de generación de código.

Para corregir los errores de llamadas a funciones no admitidas, puede declarar la


función como coder.extrinsic o reemplazar la función con una llamada de función
equivalente que sea compatible con la generación de código. Para obtener más
información sobre coder.extrinsic, busque en la documentación escribiendo doc
coder.extrinsic.

Para obtener una lista de las llamadas a funciones admitidas, busque en la


documentación escribiendo doc language support code generation. Para obtener una
lista de las funciones periféricas de Raspberry Pi enviadas para la implementación,
busque en la documentación las funciones de documentos compatibles con la
implementación. Afortunadamente, en nuestro caso, no tenemos ninguna llamada de
función no admitida.

A continuación, hablaremos de dos funciones importantes que nos ayudarán a


implementar la función MATLAB de forma independiente en el hardware, que es
nuestro objetivo final. Comenzamos creando un objeto de configuración de hardware
usando la función target hardware. Por ejemplo, para crear un objeto de configuración
para el hardware de Raspberry Pi, ingrese el objeto de destino igual al hardware de
destino Raspberry Pi.

El objeto creado ayuda a configurar varias opciones para la implementación, como la


dirección del dispositivo de hardware, el nombre de usuario y la contraseña. El nombre
de usuario y la contraseña predeterminados son Pi y Raspberry, respectivamente. Las
otras opciones incluyen configurar la ubicación del Directorio de compilación en el
hardware, las preferencias de acción de compilación para la implementación, como
compilar, cargar y ejecutar, o solo compilar, y la opción RunOnBoot para ejecutar
automáticamente la función después de encender el hardware. Todo esto se puede
configurar antes de implementar la función MATLAB en el hardware.

Ahora estamos listos para implementar nuestra función MATLAB en el hardware


Raspberry Pi. Y lo haremos con la ayuda de la función deployment. Esta función
implementa la función MATLAB como un ejecutable independiente en el
hardware. También genera un informe de implementación que contiene información
sobre el estado de la implementación.

En caso de que se generen errores durante la implementación, puede usar el informe


para depurar la función y verificar que la función sea adecuada para la
implementación. Además, también debemos tener cuidado de que la función MATLAB
que se implementará no debe tener ningún argumento de entrada o salida a partir de
la versión 2019b de MATLAB. Despliegue, objeto de destino, blinkNWrite.

Esta función requiere dos argumentos, a saber, el objeto de configuración de hardware


y el nombre de la función de MATLAB que se implementará, que es blinkNWrite en
nuestro caso. Ejecutar este comando implementará la función MATLAB en el
hardware Raspberry Pi. La generación de código es exitosa y se genera el informe de
generación de código. Como puede ver aquí, el LED está parpadeando.
El archivo sample.txt se devolverá en un directorio de Linux, como se especifica en el
Directorio de compilación del objeto de configuración de hardware de destino. Tenga
en cuenta que el archivo sample.txt ahora se genera en Raspberry Pi, a diferencia del
flujo de trabajo de E/S conectado, donde se generó en el directorio de trabajo de
MATLAB. Ahora podemos copiar el archivo del hardware a MATLAB ejecutando estos
comandos: r es igual a raspi, getfiler, ubicación del directorio de compilación.

Como puede ver aquí, el archivo aparece en el Directorio de trabajo. Abramos este


archivo. Parpadeo del LED integrado para contar de uno a siete.

Muy bien. Hasta ahora, hemos desarrollado una función de MATLAB, la ejecutamos


inicialmente en MATLAB utilizando el flujo de trabajo de E/S conectado y luego la
implementamos con éxito en el hardware de Raspberry Pi. El código generado a partir
de la función MATLAB se ejecutó en el hardware y manipuló el LED
independientemente de MATLAB.

Ahora recapitulemos y entendamos los dos flujos de trabajo discutidos hasta ahora, la
E/S conectada y la implementación. La E/S conectada le permite interactuar con el
hardware y sus periféricos desde MATLAB. Puede recopilar datos de sensores,
procesarlos en MATLAB y controlar los actuadores en consecuencia. Mientras que en
la implementación, el código se genera a partir de la función MATLAB, se carga y
ejecuta en el hardware para una ejecución independiente.

El flujo de trabajo de E/S conectado es mejor para la depuración, toma menos tiempo
para compilar y, por lo tanto, es útil para la creación rápida de prototipos. Sin embargo,
debido a su modo de operación conectado, siempre se necesita una conexión
física. Esto es para facilitar que la respuesta a la solicitud bajo demanda se comparta
entre MATLAB y Raspberry Pi en el flujo de trabajo de E/S conectado. Por lo tanto, hay
un tiempo de respuesta para cada paso del cálculo.

Por otro lado, la implementación coincide con los flujos de trabajo de producción en
los que el código debe ejecutarse independientemente de MATLAB y de la
computadora host utilizada para diseñar el proyecto. La ejecución es en tiempo real,
ya que el código desplegado no tiene que esperar a MATLAB para cada paso del
cálculo. Pero implica la compilación y la implementación, lo que no es muy ideal para
la depuración y la creación rápida de prototipos.

You might also like