Vous êtes sur la page 1sur 88

TLS4102

Getting Started with


MPLAB® Harmony Framework

Lab Manual
(for Harmony v1.06)

Alain SORIN v1.21


Principal Technical Training Engineer 25/01/2016

1
Creating Graphical Applications Using
MPLAB® Harmony

Table of Contents
Hardware: Special Instructions for Hardware Setup ................................................................ H-1
Software: Description of Software Setup ................................................................................. S-1
Labs installation procedure ..................................................................................................... S-2

Lab 1a : Blinky LED ................................................................................................................... 1-1


Lab 1b : Adding UART Communication ................................................................................... 2-1
Lab 2a : Adding Graphics Library .............................................................................................. 3-1
Lab 2b : Multi-Stacks—Creating complex Harmony projects ................................................. 4-1
Lab 3 : Migration in MPLAB Harmony .................................................................................. 5-1
Lab 4 : MPLAB Harmony and RTOSes ................................................................................... 6-1

The Microchip name, logo, The Embedded Control Solutions Company, PIC, PICmicro, PICSTART, PICMASTER,
PRO MATE, MPLAB, SEEVAL, KEELOQ and the KEELOQ logo are registered trademarks, In-Circuit Serial Programming,
ICSP, microID, are trademarks of Microchip Technology Incorporated in the USA and other countries.
Windows is a registered trademark of Microsoft Corporation.
SPI is a trademark of Motorola.
I2C is a registered trademark of Philips Corporation.
Microwire is a registered trademark of National Semiconductor Corporation.
All other trademarks herein are the property of their respective companies.

© 2015 Microchip Technology Incorporated. All rights reserved.


“Information contained in this publication regarding device applications and the like is intended through suggestion only and may be super-
seded by updates. No representation or warranty is given and no liability is assumed by Microchip Technology Inc. with respect to the accu-
racy of such information, or infringement of patents arising from any such use of otherwise. Use of Microchip’s products as critical compo-
nents in life support systems is not authorized except with express written approval by Microchip. No licenses are conveyed, implicitly or
otherwise, under any intellectual property rights.”

2
TLS4102

Hardware
Special Instructions for Hardware Setup

Hardware Description
All of the labs included in this manual are designed to use the PIC32MZ EF Starter Kit and the
Multimedia Expansion Board II (MEB-II). This section gives a brief description of those devel-
opment boards and how to set them up for use in this class.

The PIC32MZ EF Starter Kit


The PIC32MZ EF Starter Kit has a 200MHz PIC32MZ2048EFx144 microcontroller on-board
with 2MB Flash, 512 KB RAM and Floating Point Unit. The board features two Mini-B USB
ports, one for debugging and one for USB-to-UART or I2C™ communications, a Standard-A
USB port for the embedded host, and a Micro-AB USB Host/Device/OTG port. The PHY
daughter board features an RJ-45 Ethernet port for network connectivity.
The PIC32MZ EF Starter Kit uses the LCC software driver (included in the GFX library) to
drive the MEB II TFT display without the need for a separate graphics controller.

Figure H.1 PIC32MZ EF Starter Kit (DM320007)

H-1
TLS4102

The MEB-II display board


The MEB-II Multimedia Expansion Board includes a 24-bit stereo audio codec, integrated
802.11 b/g wireless module, low-cost Bluetooth HCI transceiver, optional EBI SRAM
memory, 4.3” WQVGA PCAP touch display daughter board, microSD slot, mTouch sensing
solutions buttons, analog temperature sensor and a VGA camera.

Figure H.2
MEB-II (DM320005-2)

Set jumper J9 on MEB II board


The MEB II has two memory options External or Internal. For this lab, we will setup the MEB
II to run in Internal mode. Make sure EBIWE and LCD_PCLK are short-circuited with J9

JP9 position
Failure to position properly JP9
will not allow display from the
LCD panel to operate properly

Figure H.3 : Jumper J9 at the back of MEB-II

H-2
TLS4102

Set up the hardware development platform


Connect the PIC32MZ EF Starter kit to the back of the Multimedia Expansion board II (MEB II) :
1. Plug the PIC32MZ EF Starter kit onto the 168-pin Hirose female connector

OPTION 1 : Pickit On Board (PKOB) debugger (figure H.4)


a. Make sure that the jumper JP2 is ON to enable the on-board debugger
b. Connect a mini-B USB cable to your PC

Figure H.4 : on-board


debugger (PKOB)
through USB cable

OPTION 2 : Real-Ice or ICD3 external debugger (figure H.5)


a. Remove the jumper JP2 to disable the on-board debugger (Pickit On Board = PKOB)
b. Connect the power supply to the 9V-15V DC receptacle
c. Attach the Real ICE / ICD3 ICSP cable to the RJ-11 connector

Figure H.5 : external


debugger and power
supply

H-3
TLS4102

Software
Description of Software Setup

Software Description
All of the labs included in this manual are designed to use :

1/ MPLAB X
MPLAB®X IDE v3.10 or higher with MPLAB Harmony Configurator (MHC) Plugin 1.06.12 or higher
2/ XC32 Compiler
XC32 Compiler v1.40 or higher
3/ Harmony framework
Harmony framework version 1.06 must be installed and present in the default location.
4/ (Note) USB <==> UART driver (MCP2200/MCP2221)
Launch and install the MCP2200/MCP2221 driver installation utility (look in Utilities directory)
5/ (Note) TERA TERM PRO (freeware terminal software)
Launch and install the freeware terminal Tera Term Pro (look in Utilities directory)

Note : if you follow this class using Microchip Regional Training Center (RTC) laptops,
these software are already installed

OPTIONAL : MPLAB Harmony Configurator icon installation in MPLAB X icon toolbar :

If you don’t already have the MPLAB Harmony Configurator icon in MPLAB X icon toolbar and
you want to add it, please follow this step by step procedure :

1/ Right click in the MPLAB X icon toolbar :


2/ Select the Customize
3/ In the customize Toolbars dialog window
at the bottom left push New Toolbar button
4/ In the New Toolbar dialog window, give a
name to the icon like MHC and press the OK button
5/ You should see <MHC> in the icon toolbar
6/ Scroll down in the Customize Toolbars until
the Tools > Embedded category and
highlight MPLAB Harmony Configurator
7/ Drag and Drop the MPLAB Harmony
Configurator on the <MHC> icon.
You should now see the Harmony icon in the MPLAB X icon toolbar :

S-1
TLS4102

Labs platform setup


All of the labs included in this manual are designed to use Harmony v1.06

Move downloaded lab files into a specific Harmony folder :


(*) for TLS4102 Regional Training Center (RTC) class participants see alternative installation procedure at
the bottom of this page

Important!
The lab files downloaded from the Microchip Developer Help site need to be placed in a specific
directory level, relative to the Harmony installation directory ( C:/microchip/harmony/v1_xx ).
If this is not done, the lab projects will not build successfully because the projects won’t be able
to find files that have been included using relative paths.

Unzip the files to this directory: <harmony install path>/apps/

With Harmony v1.06, the “apps” directory will


look like this once you are done:

(*) TLS4102 RTC class installation


Please execute the following batch file
( TLS4102_Restore_v1_xx.bat ) in
C:\MTT\TLS4102 directory which will cleanup any
previous labs and copy fresh labs from
C:\MTT\TLS4102 directory to
C:\microchip\harmony\v1_xx\apps folder

S-2
TLS4102

Lab 1a
Blinky LED

Objective

After completing Lab1a, you will have an understanding of the fundamental elements, layout, and exe-
cution model of a MPLAB® Harmony project. You will also gain hands-on knowledge in using the
MPLAB® Harmony Configurator tool (MHC) to configure the MPLAB® Harmony project and to
add features and functionality.

Procedure

For Lab1a, there are seven steps shown in Part 1 and Part 2. All steps must be completed before you
will be ready to build, download, and run the application.

Part 1: Create project and configure PIC32MZ


Step 1 – Create MPLAB® X IDE and MPLAB® Harmony project
Step 2 – With MHC, set up Device Configuration
Step 3 – With MHC, set up BSP, and then Clocks
Step 4 – With MHC, set up the Timer
Step 5 – With MHC, Generate Code
Part 2: Add Application code
Step 6 – Add code in App Tasks function
Step 7 – In Timer interrupt handler, add code to increment (change) the app state

Each step has a short list of requirements to guide you in the solution development. Following each set
of requirements, answers are provided. You can refer to the answers as needed.

Solution project may be found in:


C:\microchip\harmony\v1_06\apps\Lab1a_solution\firmware\Lab1a_solution.X

Expected Results
At the completion of this lab, you are expected to see the led LED3 on the PIC32MZ EF Starter
Kit (or led D4 on the MEB II board) blink briefly, once every second.

1-1
TLS4102

Overview

After completing Lab1a, you will have an understanding of the fundamental elements, layout, and exe-
cution model of a MPLAB® Harmony project. You will also gain hands-on knowledge in using the
MPLAB® Harmony Configurator tool (MHC) to configure the MPLAB® Harmony project and to
add features and functionality.

The LED blinking will use the default state machine mechanism implemented in Harmony framework.
The various states of the LED state machine are described in below figure 1.1

Figure 1.1 : APP_Tasks() LED state machine

1-2
TLS4102

Objective – Create MPLAB® Harmony Project (figure 1.1)


1. Start MPLAB® X IDE and create a New Project by selecting File > New Project.
2. In the Categories pane of the New Project dialog, select Microchip Embedded.
3. In the Projects pane, select MPLAB Harmony Project, and then click Next to launch the
MPLAB Harmony Project Wizard.

Figure 1.1 : MPLAB X New Project Window : Choose Project

Specify the following in the New Project dialog (figure 1.2) :


 Harmony Path (path to the folder containing the MPLAB Harmony framework)
(make sure to read page S-1 of this manual about Harmony path)
 Project Location (navigate where you want to put your project)
 Enter Project Name : Lab1a
 Configuration Name : PIC32MZ
 Target Device (select the PIC32MZ according to your starter kit) – See Note below

Figure 1.2 : MPLAB X New Project Window: Name and Location

1-3
TLS4102

Note: The labs will support either the PIC32MZ Embedded Connectivity Starter Kit, DM320007
(PIC32MZ2048EFH144 MCU) or PIC32MZ Embedded Connectivity Starter Kit w/Crypto Engine,
DM320007-C, (PIC32MZ2048EFM144 MCU).

Setup the Configuration bits (figures 1.3 & 1.4)


1. In the central window, under MPLAB Harmony configurator tab, Options sub-tab expand
the Device & Project Configuration tree and select the PIC32MZ2048EFH/(EFM)144 De-
vice Configuration
2. Note: You only need to update DEVCFG1 and DEVCFG0.
a. DEVCFG3 and DEVCFG2 – No change
b. DEVCFG1
 Disable (OFF) WDT (FWDTEN)
 Disable (OFF) Deadman Timer (FDMTEN)
c. DEVCFG0
 Disable (OFF) JTAG (JTAGEN)
 Configure comm. channel pair for “ICS_PGx2” (ICESEL)
 Disable (OFF) Trace (TRCEN)

Figure 1.3 : Configuration bits menu

Figure 1.4 : Configuration


bits registers

1. Note the colored background shading, when default settings are changed. This helps the user visu-
alize what was changed in the dfault configuration
2. Before moving to step3, you may want to collapse the Device & Project Configuration tree

1-4
TLS4102

Set BSP and Configure Clocks (figure 1.5)


1. First, expand the BSP Configuration tree, check the Use BSP? box and select the correct BSP:
PIC32MZ EF Starter Kit w/Multimedia Expansion Board II (MEB II)
2. Now, we want to setup the various clock options of the PIC32MZ.
Select the MPLAB® Harmony Clock Configuration tab to set PIC32MZ clocks:

Figure 1.5 : Harmony Clock Configurator

3. Use the following clock parameters : (figure 1.6)


a. Primary Oscillator mode (POSCMOD) à EC mode (see Note).
b. PLL Input Clock (FPLLICLK) à Primary Oscillator (POSC).
c. Enable System PLL (FNOSC) à SPLL.
d. Push the Auto Calculate button in the system PLL box
e. Confirm that Desired System Frequency is 200 MHz.

Figure 1.6 : Clock Configurator parameters

Before moving to Step 4, you may want to collapse the BSP Configuration tree

1-5
TLS4102

Solution
1. Using MHC, enable and select the BSP as shown : (figure 1.7)

Figure 1.7 : BSP configuration (solution)

This board has been chosen to match the PIC32MZ hardware you are using .

2. Using MHC, configure the PIC32MZ2048EFH/(EFM)144 clocks:


a. Select the MPLAB® Harmony Clock Configuration tab.
b. Select the PIC32MZ Clock Configurations as shown (figure 1.8)

Figure 1.8 : Clock configuration (solution)

1-6
TLS4102

Enable and Configure the Timer Driver (figure 1.10)


1. To accurately control the blink rate of the LED, we need to use the Timer Driver to generate a
fixed blinking frequency.
2. Select the MPLAB Harmony Configurator tab, Options sub-tab
3. Expand the Harmony Framework Configuration tree, expand Drivers, expand Timer tree.
a. Check the Use Timer Driver? checkbox
b. Chose Driver Implementation : STATIC
c. Check the Interrupt Mode box if not already checked
d. Number of Timer Driver Instances à 1
e. Select and Expand TMR Driver Instance 0 tree option (leave default values for pa-
rameters other than below)
 Set Timer Module ID to TMR_ID_2
 Set Operation Mode to DRV_TMR_OPERATION_MODE_32_BIT
 Set Timer Period to xxx (see below how to calculate value for 1s).
Make sure to press the ENTER key after entering the value

Reference information : Timer2 peripheral is on Peripheral Bus 3 (PBCLK3) and the default
clock divisor for PBCLK3 is 2 (figure 1.9), giving Timer2 an input clock of 100 MHz. Since the
Timer Driver is configured for 32-bit mode and the default prescale setting is 256:1, we need to
calculate a period value that will enable us to achieve the desired interrupt rate (1s) : 100.106 /
(256 * Timer Period) = 1Hz

Timer Period = 100.106 / 256 = 390625

Figure 1.9 : PBCLK3 default divider by 2 Figure 1.10 : Timer Driver configuration

Before moving to Step 5, you may want to collapse the Driver tree

1-7
TLS4102

Generate, save and build generated project (figure 1.11)


At this point, generate and save the configuration as shown below :

Figure 1.11 : Generate Code

Compile the project to verify that the generated project compiles properly without generating

errors. Click on (Clean and Build Main Project) to check that the project compiles correctly.

Effectively, you have a running MPLAB Harmony system.


However, it is not yet ready to do anything as the application specific code has not yet been added
Next, you will develop your application state machine logic and make sure the system does what
you want it to do. So, you’re ready to start implementing the application now.

In Steps 6, 7 and 8 you will:


1. Implement constants of “enumerated” types.
 Set of named integer constants.
2. Declare, define and access elements of “struct” type.
 Do you remember structures?
3. Add declarations in the app.h file.
4. Add code in the app.c and the system_interrupt.c files.

1-8
TLS4102

C language Refresher (figure 1.12)


Remember this refresher slide on “emum” and “struct” types for future reference in following
labs. You may need it. It may come in handy.

NO CHANGE NEEDED IN YOUR PROJECT ON THIS PAGE


(this page is just for reference regarding enumerated types & structures)

Figure 1.12 : “enum” type refresher

MPLAB® X IDE EDITOR TIPS

1. Use the auto-complete function after typing a few characters : type CTRL+SPACE

2. To navigate labels, functions, structures use hyperlink navigation : CTRL+”click”

1-9
TLS4102

Add application states (figure 1.13)


In this step we will add two named constants within an enum. These constants are implement-
ed in switch case statements as well as in an interrupt handler to determine the current application
state as well as set the next application state for processing.
In short, you are adding states to service in your application.

1. If not already opened or visible, open the Projects window ( Window > Projects )
2. If not expanded, expand the Lab1a project tree
3. If not expanded, expand Lab1a header files
4. Open the file app.h: (located under Header Files, in app folder)
a. In typedef enum “APP_STATES”, add two constants under
/* TODO: Define states used by the application state machine. */,:
 APP_STATE_EVENT
 APP_STATE_IDLE

These two “states” will be used in the following Steps 8 and 7 respectively (figure 1.14)

Figure 1.13 : app.h header file

1-10
TLS4102

Solution
1. Open file app.h
2. Add two named constants (application states) (figure 1.14)
3. Save the file, before closing.

Figure 1.14 : app.h header file (solution)

Start Timer Driver and set application states


1. Open file app.c: (located under Source Files in the app folder).
2. In the function APP_Tasks(), you will add code in three switch case statements:
In the existing case statement: APP_STATE_INIT :
a. Add code to start Timer Driver Service (figure 1.16)
Hint: to help you, look in the drv_timer_static.h file for function prototypes (figure 1.15a)
b. Add code to update appData.state to APP_STATE_IDLE (figure 1.16)
Hint : Look in app.h file to find the various appData.state states

Figure 1.15a : drv_tmr_static.h APIs

1-11
TLS4102

Figure 1.15b : for reference : appData.state enumerated states

Solution
See figure 1.16 and figures 1.17a to 1.17c on the follwoign pages

Figure 1.16 : solution to APP_STATE_INIT

1-12
TLS4102

 Under /* TODO: implement your application state machine.*/


c. Add a new case APP_STATE_EVENT: state (figure 1.17b)
d. Add code to Toggle LED 3 on PIC32MZ SK (figure 1.17b)
Hint: see file bsp_sys_init.c for BSP_LEDToggle(arg) function. You want to toggle LED 3
(figure 1.17a)
e. Add code to set appData.state back to APP_STATE_IDLE (after toggling the
led) (figure 1.17b). Look figure 1.15b for appData.state states.
f. Do not forget to also add a break; at the end of this 2nd case (figure 1.17b)

Figure 1.17a : BSP_LEDToggle API

Figure 1.17b : APP_STATE_EVENT

f. Finally, create a 3rd case statement for the remaining IDLE appData.state :
case APP_STATE_IDLE: (figure 1.17c)
 This state (APP_STATE_IDLE) does nothing so just add a break; inside

Figure 1.17c : APP_STATE_IDLE

1-13
TLS4102

Service ISR and update state for next event (figure 1.18)
1. Open the file system_interrupt.c

Figure 1.18 : system_interrupt.c


location

a. Preceding the ISR Handler, below the header files #include, declare and provide ex-
ternal reference for APP_DATA appData. (The appdata declaration is located in app.c
file)
b. In TIMER3 interrupt function __ISR(_Timer_3_Vector, …) before the existing func-
tion which already clears the TIMER3 interrupt flag
 Add code to à Update appData.state to the EVENT state.
Hint: Access variable as a structure member

Setting this next state will enable BSP_LedToggle(BSP_LED_3) to be executed in file app.c.

Congratulations! You’re done. First do a clean build

You are now able to build, program, and run the “blinky LED” application .

NOTE : Most probably MPLAB X will request you to select the programmer tool you want to
use to flash the PIC32MZ. The choice will depend upon your programming tool.

In case you use a direct connection from your PC to the MEB II using a mini USB cable, the Mi-
crochip Starterkit with Pickit On Board (PKOB) will be detected by MPLAB X. Just select it as
shown in figure 1.19

You should now see LED3 on the PIC32MZ EF Starter Kit (or led D4 on the MEB II board)
blink briefly, once every second.

1-14
TLS4102

Figure 1.19 : select the debugger tool used


to flash the PIC32MZ (solution).

NOTE : if you use an ICD3 or Real-Ice


select your tool under the category ICD3
or Real ICE

Solution (figure 1.20)


1. In file system_interrupt.c:
a. Declare external reference for APP_DATA appData.
b. Update appData.state for next event.

Figure 1.20 : system_interrupt.c (solution)

1-15
TLS4102

The LED blinks at a constant rate (1 Hz) while the main super loop in the system is run-
ning. But, if the super loop hangs (or suffers excessive delays) the LED stops blinking (or
“skips a beat”). So, the blinky LED” application is a very useful indicator of the health of the
system.

Feel free to debug it and step through the code to see how it works. As you continue
stepping through the project, you will eventually arrive back at the super loop in the main func-
tion. Fundamentally, this is how polled state machines execute within a MPLAB Harmony sys-
tem

Note: Don’t be surprised if you cannot step into the PLIB function calls. They are implement-
ed as inline functions and source code is provided in the MPLAB® Harmony installation. It is
possible to rebuild the PLIB, converting them to actual function calls, without optimizations and
with debug symbols enabled, so that you can step through them. But, they are generally very
simple functions that provide access to peripheral Special Function Registers (SFRs) through an
abstracted C-language function call interface that remains the same on all parts on which they
are supported.

Time permitting, explore the Lab1a project files and folders. Observe that the project
consists of several “logical” folders within the MPLAB® X IDE and several physical folders on
disk. This organization is used consistently by MPLAB Harmony applications to keep the files
well organized. The MPLAB® X IDE separates header (.h) files from source (.c) files, so the
logical folder structure duplicates (with some small differences) the physical folder structure on
disk under both the Header Files and Source Files top-level logical folders. In most cases, the
folders on disk correspond directly to the logical folders in the MPLAB® X IDE, but the header
files and source files are not separated on disk as they are in the MPLAB X IDE logical folder
tree. Also, the app logical folder corresponds to the src folder on disk.

The application’s src folder contains the main.c file as well as the app.c and app.h files
that implement the application. (Note: By convention, the main.c file is identical for all
MPLAB® Harmony applications.) The system_config folder normally holds one or more con-
figuration-specific folders (system_config\PIC32MZ in this case) that each contains a complete
set of configuration files for an MPLAB Harmony application.

1-16
TLS4102

Lab 1b
Adding UART Communication

Purpose
After completing Lab1b, you will have an introduction to the UART Static Driver and continue your
learning with the capabilities of the MPLAB Harmony Configurator.

Procedure
1. First, close the Lab1a project and open the Lab1b project :
File > Close Project (Lab1a)
File > Open Project > C:\microchip\harmony\v1_06\apps\Lab1b\firmware\Lab1b.X
1. We must set Lab1b as Main Project to be able to use MHC : Set as Main Project
2. We need to enable MHC : Tools > Embedded > MPLAB Harmony Configurator
3. For Lab 1b, there are six steps, shown in Part 1 and Part 2. All six steps must be completed before
you will be ready to build, download, and run the application.

Part 1: With MHC, add UART Functionality


Step 1 – Configure the USART Driver
Step 2 – Connect UART2 TX to pin 61
Step 3 – Generate Code
Step 4 – Merge Auto-Generated and custom code
Step 5 – Using MHC help, find USART API for sending a byte
Part 2: Add Application code
Step 6 – Add code to send USART byte

Each step has a short list of requirements to guide you in the solution development. Following each set
of requirements, answers are provided. You can refer to the answers as needed.

Solution project may be found in:


C:\microchip\harmony\v1_06\apps\Lab1b_solution\firmware\Lab1b_solution.X

Expected Results
At the completion of this lab, you are expected to see the led LED3 on the PIC32MZ EF Starter
Kit (or led D4 on the MEB II board) blink briefly, once every second and simultaneously the character
‘a’ should be send to the UART to USB bridge and visible on the PC terminal SW like Teraterm.

2-1
TLS4102

Enable and Configure the USART Driver


1. Select the MPLAB® Harmony Configurator tab
2. Select the Options tab
3. Expand the Harmony Framework Configuration tree, expand Drivers, expand USART tree.
a. Check the Use USART Driver? box
b. Select Driver Implementation à STATIC
c. Make sure that Interrupt Mode checkbox is deselected.
d. Number of USART Instances à 1 (default)
i. Select and Expand USART Driver Instance 0
ii. Set USART Module ID à USART_ID_2
iii. Disable USART RX => uncheck Enable RX

Solution (figure 2.1)


1. Select and Configure USART TX Driver as shown.
2. Ensure that Interrupt Mode is deselected.
3. Disable USART RX.

Figure 2.1 UART driver configuration

2-2
TLS4102

Map UART2 TX to the pin 61


1. Using MHC, map UART2 TX to pin 61.
a. Select MPLAB® Harmony Pin Diagram tab.
b. In the bottom window, select the MPLAB Harmo-
ny Configurator tab
c. Finally select the Pin Table tab

Note : You may have to enlarge the Pin Table window in order to see the UART2 module which
is at the very bottom of the window.
d. Locate and click on the blue square cell on the
device pin 61 column to enable UART 2
“USART_ID_2”
Note : as you move your mouse away from the cell, it should now be green.

IMPORTANT : this pin is shared with pushbutton SWITCH_3 (unused


in this Lab), so do not care about the Pin conflict detected message if any)

Figure 2.2 Pin configuration tool

2-3
TLS4102

Solution (figure 2.3)


1. Enable UART2 TX on Pin 61.
a. Select the Pin Table Manager Tab as shown and then scroll to the U2TX field (Y-axis)
and then pin 61 (X-Axis) and then click once in the shared cell. You should see the cell
turn to green.

Figure 2.3 : Pin table tab


for pin assignment

At this point generate and save the configuration as shown (Figure 2.4)
First, select the MPLAB® Harmony Configurator tab and follow instructions :

Figure 2.4 : Saving configuration and Generate project

2-4
TLS4102

Merge Auto-Generated and custom code (Figure 2.5)


The “DIF” window opens up and shows the differences between auto-generated code (left)
and the manual modifications (right) we just made in previous steps.
Of course we want to keep our manual additions and therefore you need to click on Close
button.

Figure 2.5 Generate and Merge Code

This tool is a great way to check and accept the code changes you just made against the previous
source. We have added the USART functionality to the existing running MPLAB Harmony sys-
tem.
Build the project to make sure there is no error at this step. Push the icon
Now, you’re ready to start implementing the application code.

2-5
TLS4102

Locate the UART APIs in documentation (figure 2.6)


It is recommended to open the Harmony help file to browse it with a standard browser :
C:\microchip\harmony\vx_xx\doc\help_harmony.chm
1. In help file, locate and familiarize yourself with USART API for sending a byte.
2. On PC, within MHC, select the MPLAB® Harmony Configurator tab (figure 2.6)
3. Expand the Harmony Project Configuration tree to see the USART :
a. Right click on Use the USART Driver. USART Driver Library help topic will appear
on right pane.
b. Next, find the Library Interface link and click on it to see the APIs
c. Look at the DRV_USART_WriteByte API.

Note: The Library Help syntax reflects a USART Dynamic Driver. The Static USART API is ef-
fectively the same as with Dynamic. See the Framework Help note below for the suitable change
in the Dynamic API to accommodate the Static Driver.

Figure 2.6 : Framework help

Solution (figure 2.7)


Find & familiarize yourself with USART API for sending byte. It will be used in step 6.

Figure 2.7 : UART


Driver API

2-6
TLS4102

Write byte to UART


1. In the Projects window, under Source Files > app subfolder, open the file app.c:
a. In function APP_Tasks(), we need to add code to the APP_STATE_EVENT case
statement to transmit one byte over the UART at the same time we blink the LED :
i. case APP_STATE_EVENT:
 Add code to send the byte character ‘a’ as function argument.
 Hint: You just looked up the API for this function.
 Remember you’re using USART Driver Instance 0 (static)

Congratulations! You’re almost there. Before proceeding just two more quick items:

2. Connect a mini-B USB cable between the J11 connector (below the PHY daughter PCB) on
the PIC32MZ EF Starter kit & the host PC (figure 2.8) to add a virtual COM port
3. Connect a USB cable to the PC and launch Tera Term Pro freeware or any other terminal em-
ulator with these settings: 9600 baud, 8, N, 1. ( Setup > Serial port > …)

First do a clean build and you are now able to build, program, run and see LED D4
blink on MEB II once every second, and also see the character ‘a’ show up on the terminal each
and every second.

Figure 2.8 :
Mini-B USB connector
to virtual COM port

Solution (figure 2.9)


1. Write a byte (character ‘a’) for each and every APP_STATE_EVENT state.

Figure 2.9 :
UART Driver API to
Write a character

2-7
TLS4102

Lab 2a
Adding Graphics Library

Purpose
After completing Lab2a, you will have an understanding of how to use MHC to add and enable
graphics into your application. We will keep the graphics simple and basic for this lab. You can build
on this foundational knowledge at a later time.

Overview
In this lab, you will start with your previous project after you completed Lab1b.
Using MHC, you will select and enable a Graphics Library application and add it to Lab1b.

Procedure
1. First, close the Lab1b project and open the Lab2a project :
File > Close Project (Lab1b)
File > Open Project > C:\microchip\harmony\v1_06\apps\Lab2a\firmware\Lab2a.X
2. We must set Lab2a as Main Project to be able to use MHC : Set as Main Project
3. We need to enable MHC : Tools > Embedded > MPLAB Harmony Configurator

With MHGC, add Graphics Functionality


Step 1 – Launch MHGC
Step 2 – Select background color for the main screen
Step 3 – Import Font resources
Step 4 – Rename the main screen
Step 5 – Add the title, the footer and the D4 label to the LCD screen
Step 6 – Add a rectangle to the LCD screen
Step 7 – Generate and merge code
Step 8 – Change the rectangle color on LCD as the LED toggles

Each step has a short list of requirements to guide you in the solution development. Following each set
of requirements, answers are provided. You can refer to the answers as needed.
Solution project may be found in:
C:\microchip\harmony\v1_06\apps\Lab2a_solution\firmware\Lab2a_solution.X

Expected Results
At the completion of this lab, you are expected to see a blinking rectangle on the TFT LCD dis-
play, blinking at the same rate than the led.

3-1
TLS4102

Launch MPLAB Harmony Graphics Composer (figure 3.1)


1. Close Lab1b project and open Lab2a project
2. Set Lab2a project as main project
3. Launch MPLAB Harmony Configurator (MHC)
4. Expand Harmony Framework Configuration tree
5. Expand the Graphics Library tree
6. Select Use Graphics Library
7. Check Use MPLAB Harmony Graphics Composer Design
8. Click on the Execute button to launch MPLAB Harmony Graphics Composer (MHGC)

Figure 3.1 :
launch MHGC

3-2
TLS4102

Select the background color for the main screen


MHGC is now launched and we can start to build a graphics screen for the application.
To select the background color, we can use the Color Picker menu .
1. In the Graphics Composer Properties window on the right side, launch Color Picker by press-
ing the “…” (figure 3.2a). The Color Picker Dialog window will open up

To see the “…” you may need to widen the Graphics Composer Properties window

Figure 3.2a : Launch Color Picker

2. Select the white background color using Color Picker and press OK (figure 3.2b)

Figure 3.2b : Select white background color using Color Picker

3-3
TLS4102

Import font resources (figure 3.3)


There are 2 options for font resources. The MHGC can import fonts in .tf format or import
fonts that are already installed in the operating system. For this lab, we will chose the latter.
1. In bottom left corner of MHGC display, select the Graphics Composer Management tab
2. Clikcon the Asset tab at the bottom of that window
3. Click on the System Font icon to import fonts from the OS
4. Chose the SEGOE_UI font, with size 24 and Bold style. We will use this font for the display
title. Press OK
5. Click again on System Font icon . Chose Trebuchet_MS font , with size 16.We will use this
font for standard text. Press OK

Figure 3.3 : import font resources

Rename the main screen (figure 3.4)


1. In bottom left corner of MHGC display, select the Graphics Composer Management tab
2. To change the name of the main screen, click on the Screen tab. The default main screen name
is underlined (Screen1)
3. Double click on Screen1 and change it to MainScreen

Figure 3.4: Rename the main screen

3-4
TLS4102

A. Add the Title to the LCD screen


1. (Usually) In the upper left Graphics Composer Tool Box window, under Primitives tree,
drag the Text icon onto the white screen in the left top corner (figure 3.5). (exact coordinates
changed in 3.)
2. In the upper right Graphics Composer Properties window, expand Object tree and change
this text object name to Title1 in the Name row
3. Expand Text tree and expand Origin row. Change the coordinates (if needed) to X :20, Y : 20
4. Then, in the Text field of the Text row enter “Lab 2a - MHGC generated screen”
5. Assign with the pull-down menu , if not shown as default, the Segoe_UI font on the Font row
6. Expand the Color tree and click on the ”…” button . It will launch the Color Picker Dialog
window. Select the Blue color ( RGB (0;0;255))

Figure 3.5: Add the Title


to the LCD screen

B. Add the footer text to he LCD screen (figure 3.6)


Follow the same procedure as in 5/A/ with the following parameters :
1. Name > Footer
2. Text > Origin > X : 20, Y : 230
3. Text > Text > (c) 2015 - Microchip Technology, Inc.
4. Text > Font > Trebuchet_MS
5. Text > Font > Color > RGB (0,0,0) = black

Figure 3.6: Add the foot-


er text on the LCD screen

3-5
TLS4102

C. Add the D4 label text to he LCD screen(figure 3.7)


Follow the same procedure as in 5/A/ with the following parameters :
1. Name > D4_label
2. Text > Origin > X : 20, Y : 150
3. Text > Text > D4
4. Text > Font > Trebuchet_MS
5. Text > Font > Color > RGB (0,0,0) = black

Figure 3.7 : Add the D4


label to the LCD screen

Add a rectangle to the LCD screen (figure 3.9)


1. In the upper left Graphics Composer Tool Box window, under Primitives tree, drag the Rec-
tangle icon onto the white screen above the D4 text (figure 3.8) and modify its shape to have
approximately the size and position shown (exact size/coordinates changed in 3.)
2. Name > Rectangle1
3. Rectangle > Point1 > X : 20, Y : 80
4. Rectangle > Point1 > X : 40, Y : 140
5. Rectangle > Outline Color > RGB (0,0,0)
6. Line Thickness > Thick

Figure 3.8 : Add a rectangle Figure 3.9: Rectangle properties

3-6
TLS4102

A. Generate code for the added graphics objets


1. In the MPLAB Harmony Configurator main window , click on the Generate Code button
(figure 3.10)
2. Click on the Save button to save the new settings of MHGC in MHC configuration file
3. Finally, push the Generate button to generate the code corresponding to the objects added in
MHGC

Figure 3.10 : Generate code for the added graphics objects

3-7
TLS4102

B. Merge the graphics code with existing code


At this stage it is very important to understand that the code on the RIGHT window will
be the code used to compile after merging. The code on the left is the newly added code /
changed code. We want to keep the existing Application code and merge it with the newly gener-
ated code coming from MHGC.
1. Merge the code (pink color) : click on the —> on (or near) line 80 to merge code (figure 3.11)
2. Push the Close button to merge the code (figure 3.12)

Figure 3.11 : system_interrupt.c BEFORE merging code

Figure 3.12 : system_interrupt.c AFTER merging code

3-8
TLS4102

C. Intermediate test
This tool is a great way to check and accept the code changes you just made against the
existing source.
Compile the project to verify that the generated project compiles properly without generat-
ing errors. If it compiles, without errors, please proceed to (8)

Change the rectangle color on LCD as the LED toggles


In this step you will update one switch case statements in the app.c file.
Open file app.c, and locate case statement APP_STATE_EVENT :
After the line DRV_USART0_WriteByte('a'); add if-else code below to blink the rectangle :
/* TODO: implement your application state machine */
case APP_STATE_EVENT:
{
BSP_LEDToggle( BSP_LED_3 );
DRV_USART0_WriteByte( 'a' );

if ( BSP_LEDStateGet(BSP_LED_3) == BSP_LED_STATE_ON )
{
GFX_ColorSet( GFX_INDEX_0, BRIGHTRED );
GFX_RectangleFillDraw( GFX_INDEX_0, 20, 80, 40, 140 );
}
else
{
GFX_ColorSet( GFX_INDEX_0, WHITE );
GFX_RectangleFillDraw( GFX_INDEX_0, 20, 80, 40, 140 );
}
appData.state = APP_STATE_IDLE;
break;
}
/* The default state should never be executed. */
default:
{
/* TODO: Handle error in application's state machine. */
break;
}

First do a clean build and you are now able to build, program, run and see LED D4
blink on MEB II once every second, a screen widget named D4 blink at the same speed as LED
D4 toggle rate and also see the character ‘a’ show up on the terminal each and every second.

3-9
TLS4102

Lab 2b
Multi-stack : Creating Complex
MPLAB Harmony Projects
Purpose
After completing Lab2b, you will have gained additional experience using MHC to add, enable, and
configure PIC32 Harmony USB Host MSD and File System Library components.

Procedure
 In Lab2b, you will add Harmony USB Host MSD and File System components to the previous pro-
ject. When the final application is running and you insert a USB Pen Drive into the PIC32MZ EC
Starter Kit, a stored message is read from the Pen Drive and displayed on the MEB II glass and also
transmitted on UART TX.
 In this lab you will become familiar with several USB Host MSD and File System APIs and how to
bring these elements into a system with MHC.
 Also, you will understand how to create a second application configuration and how to process the
application states within the overall application.
 There are 12 steps in Lab2b. All 12 steps must be completed before you will be ready to build,
download, and run the application.
 Here are the steps you will work through:
Adding USB Host MSD and File Systems Components
Step 1 – Launch MHGC and update main screen Title
Step 2 – Enable HOST USB & MSD class and merge Auto-Generated code
Step 3 – Reconfigure Timer Services
Step 4 – Generate Code, merge Auto-Generated and custom code
Step 5 – Create two Application Configurations
Step 6 – Generate Code, Merge Auto-Generated and custom code
Step 7 – Add USB and MSD callback functions
Step 8 – Start Timer Service as 1 second event
Step 9 – Use Timer Service as 1 second event
Step 10 – Add USB MSD application states
Step 11 – Add USB MSD application state machines execution code
Step 12 – Update Initialization code in app.c and generate code

Expected Results
At the completion of this lab, you are expected to see the message “MPLAB Harmony” dis-
played on the TFT LCD after a USB Pen Drive is inserted into the PIC32MZ EF Starter Kit.

4-1
TLS4102

Each step has a short list of actions to guide you in the solution development. Following each set
of requirements, answers are provided. You can refer to the answers as needed

Ensure that the USB debugger cable is attached and the correct hardware and language tools are
selected.

All three of these “applications” (Graphics, USB Host MSD and File System Libraries) are run-
ning, effectively independently within the MPLAB Harmony system with no conflicts.

Launch Graphics Composer (MHGC)


1. First, close the Lab2a project and open the Lab2b project :
File > Close Project (Lab2a)
File > Open Project > C:\microchip\harmony\v1_06\apps\Lab2b\firmware\Lab2b.X
 We must set Lab2b as Main Project to be able to use MHC : Set as Main Project
 We need to enable MHC : Tools > Embedded > MPLAB Harmony Configurator
2. Launch MHGC : select Graphics Composer in the pull-down menu of the “window” icon
(figure 4.1a)

Figure 4.1a : Launch Graphics Composer

Update main screen Title


1. In the Graphics Composer Screen window, click on the Lab2a—MHGC generated screen
title to select it. (figure 4.1b)
2. In the Graphics Composer Properties window, locate the Text row and change the text to
“Lab2b - Graphics & USB” (figure 4.1b)

Figure 4.1b : Update main screen title

4-2
TLS4102

(A) Enable USB Host with MSD (figure 4.2)


1.Select/Expand the Harmony Framework Configuration tree then select/expand USB Library
to configure it (you may want to collapse the Drivers & System Services trees under Harmony
Framework Configuration tree).
a. Select/enable “Use USB Stack”. (interrupt should be already selected)
b. Next expand Select Host or Device Stack, and select USB Host (Recommended).
c. Select “Use MSD Host Client Driver”
d. Verify that Interrupt Mode is enabled (default)

Figure 4.2 : USB & MSD HOST configuration

4-3
TLS4102

(B) Configure MSD class (figure 4.3)


We need to configure the FAT file system for use in the USB HOST MSD class
1.Select/Expand the Harmony Framework Configuration tree then select/expand System Ser-
vices
2. Expand File System
3. Select Use File System Auto Mount feature
4. Expand Media0
5. Expand Media Configuration (0)
6. In the Media Type pull-down menu select SYS_FS_MEDIA_TYPE_MSD
7. Verify that the Media Mount Name is /mnt/myDrive1

Figure 4.3 : Configure MSD class

4-4
TLS4102

(C) Generate and save the configuration (figure 4.4)

Figure 4.4 : Regenerate the code

(D) Merge Auto-Generated code (figure 4.5)

Figure 4.5 : Merge existing code with USB HOST + MSD


We have just added the USB Host with MSD functionality to the existing MPLAB Harmony project.

4-5
TLS4102

Reconfigure the Timer Driver (figure 4.6)


In this lab you will use the Dynamic Timer System Service instead of a single Static Timer Driv-
er implemented in the previous labs.
1. Expand the Harmony Framework Configuration tree, expand Drivers, and then expand
Timer , and validate Use Timer Driver checkbox.
2. For Driver Implementation, select DYNAMIC
3. Expand TMR Driver Instance 0 tree
4. Change Timer Module ID to TMR_ID_1 (Timer1)
5. Change Operation Mode to DRV_TMR_OPERATION_MODE_16_BIT (16-bit mode)

Figure 4.6 : Reconfig-


ure the Timer Driver

Using MHC, set Application Configurations to “2” (figure 4.7)


This setting will create the framework for two Application state machines. We will retain the pre-
vious lab functionalities (blinky LED, UART TX and graphics library) as one application (app.c)
and add USB Host MSD and File System for the second application (app1.c).

Figure 4.7 : Select the number of applications

4-6
TLS4102

Generate and save the configuration (figure 4.8)


At this point you should see two sets of nearly identical files in your project (app.h and app.c) and
(app1.h and app1.c). Generate the code

Figure 4.8 : Regenerate the code

(A) Declare & define USB and MSD callback functions


1. Open the app1.c file and declare the USB and MSD callback functions as shown. (figure 4.9)
Note: Generally these two function prototype definitions would be included in the app1.h file.
For this lab, you can include them in app1.c file.

Figure 4.9 : Add USB and MSD callback functions

You may want to copy & paste below code from the app1_solutionRTC.c file

void APP_SYSFSEventHandler( SYS_FS_EVENT event, void* eventData, uintptr_t context);

USB_HOST_EVENT_RESPONSE APP_USBHostEventHandler (USB_HOST_EVENT event, void* eventData, uintptr_t context );

4-7
TLS4102

(B) Add a switch state machine for MSD related events


1. Locate : // Section: Application Local Functions in the source file (figure 4.10) and add
the switch state machine below.

Figure 4.10 : Add MSD related events

You may want to copy & paste below code from the app1_solutionRTC.c file

/* TODO: Add any necessary local functions.


*/
void APP_SYSFSEventHandler ( SYS_FS_EVENT event, void* eventData, uintptr_t context)
{
switch(event)
{
case SYS_FS_EVENT_MOUNT:
app1Data.deviceIsConnected = true;
break;

case SYS_FS_EVENT_UNMOUNT:
app1Data.deviceIsConnected = false;
break;

default:
break;

4-8
TLS4102

(C) Add a switch state machine for additional USB HOST events
1. Below the code added in (7)(B), add the switch state machine below. (figure 4.11)

Figure 4.11 : Add USB HOST additional events

You may want to copy & paste below code from the app1_solutionRTC.c file

USB_HOST_EVENT_RESPONSE APP_USBHostEventHandler (USB_HOST_EVENT event, void* eventData, uintptr_t context)


{
switch(event)
{
case USB_HOST_EVENT_DEVICE_UNSUPPORTED:
break;

default:
break;
}
return USB_HOST_EVENT_RESPONSE_NONE;
}

4-9
TLS4102

Start Timer Service as a one second event


Before changing our new files app1.c and app1.h, we just need to make a few more changes to
app.c and app.h files :

1. Open app.h file and declare a SYS_TMR_HANDLE sysTmrHandle; (Timer handle) ele-
ment in struct APP_DATA after the element APP_STATES state; (figure 4.12)
2. Open app.c file and locate case statement APP_STATE_INIT in the APP_Tasks function.
Within this case statement you will add code to start the Timer Service for a one second delay :
a. Remove or comment out the DRV_TMR0_Start(); function call. ( Remember that this
function was used when we implemented a Static Timer Driver for the previous labs).
b. Replace this call (within this same if statement) with a function call to start the Timer
Service for a 1000ms delay. ( Refer to the Integrated Help “Timer System Service Li-
brary”, by right double clicking on Use Timer System Service
Timer System Service Library > Library Interface > Timed Delay Functions :
SYS_TMR_DelayMS. ) (figure 4.13)

Figure 4.12 : Add a Timer handle in app.h

Figure 4.13 : Start the Timer service with 1000ms value in app.c

4-10
TLS4102

Use Timer Service as 1 second event (figure 4.14)


1. Further in app.c file , locate the case statement APP_STATE_IDLE. Within this case
statement add code to do the following:
a. Test if Timer Service has expired using SYS_TMR_DelayStatusGet(arg). If test is
TRUE, then:
i. Update appData.state to APP_STATE_EVENT
Hint: Remember that you defined this state in app.h file
ii. Restart the Timer Service for one second delay

Figure 4.14 : Update IDLE state

4-11
TLS4102

(A) Add USB MSD application states (figure 4.15)


Open app1.h file, locate Section: Type Definitions and add nine new USB MSD Application
states as shown below.

Figure 4.15 : add states in APP1_STATES

You may want to copy & paste below code from the app1_solutionRTC.h file.

typedef enum
{
/* Application's state machine's initial state. */
APP1_STATE_INIT=0,

/* USB STATES used by the application state machine. */


APP1_STATE_BUS_ENABLE,
APP1_STATE_WAIT_FOR_BUS_ENABLE_COMPLETE,
APP1_STATE_WAIT_FOR_DEVICE_ATTACH,
APP1_STATE_DEVICE_CONNECTED,
APP1_STATE_OPEN_FILE,
APP1_STATE_READ_FROM_FILE,
APP1_STATE_CLOSE_FILE,
APP1_STATE_IDLE
APP1_STATE_ERROR
} APP1_STATES;

4-12
TLS4102

(B) Add application variables (Figure 4.16)


Next, also in app1.h file,
a. Declare a global buffer for the string contained in the text file file.txt on the USB key
b. add USB_HOST_HANDLE structure element as shown below.
c. add SYS_FS_HANDLE structure element as shown below.

Figure 4.16 : add structure elements

You may want to copy & paste below code from the app1_solutionRTC.h file.

uint8_t readData[12];
typedef struct
{
/* The application's current state */
APP1_STATES state;

/* TODO: Define any additional data used by the application. */


SYS_FS_HANDLE fileHandle;

bool deviceIsConnected;

} APP1_DATA;

4-13
TLS4102

Note: Step 11 has many code development requirements. Please refer to the solution file
(app1_solutionRTC.c) if you want to copy&paste some or all of the code (many changes needed).

(A) Open app1.c file. First, we need to remove the existing APP1_STATE_INIT state from the
(void) APP1_Initialize(void) function (figure 4.18a)

Figure 4.18a : remove APP1_STATE_INIT

(B) Continue in app1.c file & in the void APP1_Initialize (void) function add 2 new initialization
states (figure 4.18b)

Figure 4.18b : add 2 new initialization states

(C1) Continue with app1.c file. We need to remove the existing APP1_STATE_INIT state from
the (void) APP1_Tasks(void) function (figure 4.19a)

Figure 4.19a : add APP1_STATE_OPEN_HOST_LAYER state

4-14
TLS4102

(C2) continue with app1.c file. and add a new USB MSD Application State in the existing
APP1_Tasks () function : STATE: APP1_STATE_BUS_ENABLE

Figure 4.19b : add APP1_STATE_BUS_ENABLE state

(D) continue with app1.c file and add another USB MSD Application State :
STATE: APP1_STATE_WAIT_FOR_BUS_ENABLE_COMPLETE

Figure 4.20 : add APP1_STATE_WAIT_FOR_BUS_ENABLE _COMPLETE state

4-15
TLS4102

(E) continue with app1.c file and add another USB MSD Application State :
STATE: APP1_STATE_WAIT_FOR_DEVICE_ATTACH

Figure 4.21 : add APP1_STATE_WAIT_FOR_DEVICE_ATTACH state

(F) continue with app1.c file and add another USB MSD Application State :
STATE: APP1_STATE_DEVICE_CONNECTED

Figure 4.22 : add APP1_STATE_DEVICE_CONNECTED state

(G) continue with app1.c file and add another USB MSD Application State :
STATE: APP1_STATE_OPEN_FILE

Figure 4.23 : add APP1_STATE_OPEN_FILE state

4-16
TLS4102

(H) continue with app1.c file and add another USB MSD Application State
STATE: APP1_STATE_READ_FROM_FILE

Figure 4.24 : add APP1_STATE_READ_FROM_FILE state

(I) continue with app1.c file and add another USB MSD Application State
STATE: APP1_STATE_CLOSE_FILE

Figure 4.25 : add APP1_STATE_CLOSE_FILE

4-17
TLS4102

(J) continue with app1.c file and add another USB MSD Application State
STATE: APP1_STATE_IDLE

Figure 4.26 : add APP1_STATE_IDLE state

(K) continue with app1.c file and add another USB MSD Application State
STATE: APP1_STATE_ERROR and (if not yet there) default state

Figure 4.27 : add APP1_STATE_ERROR and default states

(L) Finally, as app1.c need to write on the LCD screen, we need to include access to the fonts by
including the gfx_resources.h header file

Figure 4.28 : add


declaration in app1.c

4-18
TLS4102

(A) Open app.c file and do the following 2 changes (figure 4.29)

Figure 4.29 : add declarations in app.c

(B) Temporary fix


Due to to some issue in Harmony v1.06, it is necessary to manually force the value of TRISB.
Harmony generates the following value : 0xffff
We need to change this value SYS_PORT_B_TRIS in the file system_config.h which is locat-
ed in the Projects window under Header Files > app > system_config > PIC32MZ >

Figure 4.30 : modify SYS_PORT_B_TRIS

As the file system_config.h is automatically regenerated everytime the Gener-


ate button is pressed, the macro SYS_PORT_B_TRIS will go back to 0xffff.
Make sure to modify it back to 0xffc9

(C) Build the project to make sure there is no error at this step :

4-19
TLS4102

1. Connect the USB Pen Drive to your PC.


2. Copy the file “file.txt” from the Lab2b directory to the USB pen drive root level.
C:\microchip\harmony\v1_06\apps\lab2b

The file.txt contains the 12 characters string MPLABHarmony .


If you want to change this string, make sure it is exactly the same length (12 characters)

You can now build, program, and run the application by pressing

Once the application is running you should see the LCD like A] below.

The application is waiting for a USB memory stick insertion.


3. Insert the USB memory stick into the USB A connector located on the PIC32MZ EF starter kit

Once the USB pen drive has been inserted, the message MPLABHarmony (or the one you stored in
the file file.txt), should be displayed on the MEB II glass and is also transmitted on UART TX.

See the next page for the expected results displayed on the PIC32MZ EC Starter Kit.
1. Text should be displayed on MEB II.
2. Text should also be displayed on the PC terminal application (Tera Term)
3. LED continues to blink with status also displayed on the MEB II TFT LCD display.

4-20
TLS4102

A] Display before USB Pen Drive is inserted into PIC32MZ EF Starter Kit

B] Display after USB Pen Drive is inserted into PIC32MZ EF Starter Kit

4-21
TLS4102

Lab 3
Migration in MPLAB Harmony

Purpose
After completing Lab3, you will gain a better understanding on how to use the MPLAB X IDE and
MHC to seamlessly migrate your application across the PIC32 MCU product families.

PIC32MZ with MEB II PIC32MX with MEB I

Procedure
It is unlikely you will have both hardware platforms required for this lab. It is still useful for you to
experience the steps required to migrate a design from one hardware platform to another.
For Lab3, no code development is required. We will take the resultant Lab2b solution, running on the
PIC32MZ MCU and its respective hardware, and seamlessly migrate to the PIC32MX MCU and its
respective hardware. This is basically a two-part process.
All steps must be completed before to build, download and run the application.

Part 1: Create New Configuration


Step 1 – Export Graphics Composer screen design
Step 2 – Create new MPLAB X Configuration, choose Device & Tools and activate configuration
Part 2: Configure PIC32MX and Harmony Components
Step 3 – Select PIC32MX Configuration and Configure BSP
Step 4 – Configure PIC32MX Clocks and Configuration Bits
Step 5 – Imports Graphics Composer screen design
Step 6A – With MHC, Configure PIC32MX UART Driver
Step 6B – With MHC, Configure PMP Driver
Step 7 – With MHC, Configure Graphics Library
Step 8 – With MHC, Configure USB Host MSD Library
Step 9 – With MHC, Generate and Save code

Expected Results
When this lab is complete, you will be able to execute on MEB 1 platform the same operations as the
Lab2b operations done on MEB II

5-1
TLS4102

(A) Export Graphics Composer screen design


1. First, close the Lab2b project and open the Lab3 project :
File > Close Project (Lab2b)
File > Open Project > C:\microchip\harmony\v1_06\apps\Lab3\firmware\Lab3.X
2. Set Lab3 as Main Project to be able to use MHC : Set as Main Project
3. Enable MHC : Tools > Embedded > MPLAB Harmony Configurator

We need to export the MHGC xml file in order to be able to import it in another configuration.
1. Click on the Export button
2. Select MPLAB Harmony Graphics Composer
3. Click on the Export button

Figure 5.1a : export MHGC design

5-2
TLS4102

(B) Export Graphics Composer screen design


Keep the default name ( composer_export.xml ) and make sure to store it in the default folder :
C:\microchip\harmony\v1_06\apps\Lab3\firmware\src\system_config\PIC32MZ

1. Click on the Open button

Figure 5.1b : save composer_export.xml

5-3
TLS4102

(A) Create new MPLAB X Configuration


1. Enable MHC : Tools > Embedded > MPLAB Harmony Configurator
a. Select Configuration Menu.
b. Select Customize.
c. Select Manage Configurations.

Figure 5.2a : create new configuration

d. Select New Configuration.


e. Type new Configuration name à PIC32MX
f. Click OK.

Figure 5.2b : create new configuration

5-4
TLS4102

(B) Choose Device, compiler and tool/starterkit to use (figure 5.3)


Follow the steps as shown:
1. PIC32MX configuration
2. PIC32MX795F512L
3. XC32 v1.40 or more
4. SKDE PIC32 where you see the S/N : BUR…..
5. Apply and OK

Figure 5.3 : select configuration options

[C] Set new “PIC32MX” configuration as active (figure 5.4)

Figure 5.4 : activate PIC32MX configuration

5-5
TLS4102

If you see this message, just click YES (figure 5.5)

Figure 5.5 : save


configuration

If you see this message, just click OK (figure 5.6)

Figure 5.6 : accept new configuration

(A) Using MHC, setup PIC32MX Harmony configuration (figure 5.7)


1. If MHC is open, it will restart when the new configuration becomes active.
2. If MHC is closed, start it manually.
3. Now expand Application Configuration and set at 2 (we use 2 state machines), and then press
ENTER :

Figure 5.7 : setup


PIC32MX configuration

5-6
TLS4102

(B) Configure PIC32MX BSP (figure 5.8)


1. First, expand BSP Configuration tree and
select correct BSP (PIC32MX USB Start-
er Kit 2 w/Multimedia Expansion Board
(MEB))

Figure 5.8 : PIC32MX


BSP selection

(A) Setup PIC32MX Clock (With Harmony Clock Configurator) (figure 5.9a)
1. Enable USB PLL
2. Configure USB PLL divider “/2”
3. Select Primary Oscillator mode to “XT mode”.
4. Select Primary Oscillator w/PLL.
5. Auto-Calculate
6. Keep default 80MHz
7. Press Apply

Figure 5.9a : setup


PIC32MX clock options

5-7
TLS4102

(B) Setup the PIC32MX Configuration Bits (figure 5.9b)

Figure 5.9b : disable the


watchdog

(A) Import Graphics Composer screen design


We need now to import the MHGC xml file in order to be able to use it in the new MX configu-
ration we just created
1. Click on the Import button
2. Select MPLAB Harmony Graphics Composer
3. Click on the Import button

Figure 5.10a: import


MHGC design

5-8
TLS4102

(B) Import Graphics Composer screen design


Navigate to the PIC32MZ folder where we exported the file composer_export.xml
C:\microchip\harmony\v1_06\apps\Lab3\firmware\src\system_config\PIC32MZ
1. Click on the Open button
2. Click on Import button
3. Click on Yes to finish importing process

Figure 5.10b : import composer_export.xml

Figure 5.10c : merge in


PIC32MX configuration

5-9
TLS4102

(A) Configure the UART Driver (figure 5.10)


1. Expand Harmony Framework Configuration tree, select/expand Drivers and locate USART.
2. Set USART Driver as shown (STATIC, Interrupt Mode (disabled),
USART_ID_2, ENABLE RX (disabled) ). (Figure 5.10)

Figure 5.10 : setup


the UART Driver

(B) Configure the PMP Driver (figure 5.11)


Expand Harmony Framework Configuration tree, select/expand Drivers and locate PMP.
Set PMP Driver as shown :
1. Driver implementation : STATIC,
2. Strobe Wait states : PMP_STROBE_WAIT_5
3. Select Read Strobe Enable with Polariy PMP_POLARITY_ACTIVE_LOW
4. Select Write Strobe Enable with Polarity PMP_POLARITY_ACTIVE_LOW

Figure 5.11 : setup


the PMP Driver

5-10
TLS4102

Configure the graphics Library


Expand Harmony Framework Configuration tree, select/expand Graphics Library and config-
ure Graphics Library as shown in (figure 5.12) :

Figure 5.12a : setup the Graphics Library

Figure 5.12b : setup the Graphics Library

5-11
TLS4102

Select and Enable USB Host & MSD Libraries (figure 5.13 & 5.14)

Figure 5.13 : setup the


USB HOST library

Figure 5.14 : setup the


File System library

5-12
TLS4102

Generate and save the configuration as shown (figure 5.15)

Figure 5.15 : Generate and save configuration

It may be needed to close and reopen the modified MPLAB X project to be able to
see the new PIC32MX configuration

5-13
TLS4102

Congratulations! You just finished the new PIC32MX configuration!

ATTENDEE :
As this lab is meant to show the easiness to move an existing application from one PIC32MZ hard-
ware platform to a totally different PIC32MX hardware platform, attendees will most probably not
have this PIC32MX hardware platform on their desk.
You can therefore just build the project to verify that there is no error :

PRESENTER :
The presenter will demonstrate that the application, build and execute the same tasks on the
PIC32MX platform as on the PIC32MZ platform without changing a single line of the applica-
tion SW !!!

PIC32MX platform setup


For the MEB hardware platform based on PIC32MX, ensure that the jumpers on the UART-
to-USB Pictail adapter board have been relocated to the MEB1 position.

You can now build, program, and run the application :

The USB pen drive should be setup like in Lab2b.


When the final application is running and you insert a USB Pen Drive into the PIC32MX Starter
Kit a stored message is read out from the Pen Drive and displayed on the MEB TFT display (which
even has a different size !) and also transmitted on UART TX. (Pay attention that the COM Port
has most probably changed).

See the next page for expected results displayed on the PIC32MX hardware.
Text should be displayed on the MEB display.
Text should also be displayed on terminal application.
LED continues to blink with status also displayed on the MEB TFT LCD display.

5-14
TLS4102

A] Display before USB Pen Drive is inserted into PIC32MX USB Starter Kit II

B] Display after USB Pen Drive is inserted into PIC32MX USB Starter Kit II

5-15
TLS4102

Lab 4
MPLAB Harmony and RTOSes

Purpose
 Overview on how MPLAB Harmony and RTOSes work together in an application
 Gain a brief understanding of how MPLAB Harmony drivers and middleware operate in a multi-
threaded pre-emptive environment
 Brief overview of the Operating System Abstraction Layer (OSAL).
 See the benefits of using an RTOS like sharing resources between tasks

Procedure
1. First, close the Lab3 project and open the Lab4_FreeRTOS project :
File > Close Project (Lab3)
File > Open Project > C:\microchip\harmony\v1_06
\apps\Lab4_FreeRTOS\firmware\Lab4_FreeRTOS.X
2. Set Lab4_FreeRTOS as Main Project to be able to use MHC : Set as Main Project
3. Enable MHC : Tools > Embedded > MPLAB Harmony Configurator

To avoid redoing steps already seen in previous exercises, the Lab4 project already contains the
configuration of the following peripherals / services : Clock, Configuration Bits, BSP, UART, pins
(switches)

We will only configure the RTOS used in this project (FreeRTOS) and add the application code

UART Driver Demo


 Two tasks try to access the same hardware UART peripheral to print out an ASCII string.
 Each task will run and print its own unique string, when its associated pushbutton switch is pressed.
 By connecting a USB cable from the starter kit to a PC, and opening an ASCII terminal emulator
program (TeraTerm Pro, RealTerm, etc.), the user can see the ASCII strings being correctly printed.

Expected Results

 Use SW1 & SW2 on the PIC32MZ EF starter kit


 When this lab is complete, 2 differents tasks send a different character string to the same UART
 Strings don’t get mixed up thanks to binary semaphore mechanism provided by FreeRTOS

6-1
TLS4102

This lab requires many code changes. Each xxx file which needs modifications
exists as xxxx_solution.c/.h in the source/header folder.
Feel free to copy & paste code.

Enable and Configure FreeRTOS


1. Select the MPLAB® Harmony Configurator tab
2. Select the Options tab
3. Expand the Third Party Libraries tree
4. Expand RTOS tree
5. Check the Use RTOS? box
6. Select FreeRTOS_v8.x.x in the Select RTOS pulldown menu
7. Set the Total heap Size to 32768

Figure 6.1 : RTOS configuration

6-2
TLS4102

Project configuration
1. You may want to colapse the Third Party Libraries tree
2. Expand the Device and Configuration tree, expand Project Configuration tree
3. Expand XC32 (Global options) tree, expand xc32-ld tree, expand General tree
4. Set the Heap Size to 32768

Figure 6.3 : Project


Configuration

Generate and save the configuration (figure 6.3)


At this point the project configuration is finished. We need to generate the code before to start add-
ing application code in the following steps

Figure 6.3 : Generate code for the new configuration

6-3
TLS4102

app.h file modification


We need to edit app.h file to add informations about FreeRTOS APIs, macro definitions and data
structures .

(A) Include FreeRTOS related header files (figure 6.4a)


Include FreeRTOS related header files in app.h file
1. Include 2 header files : FreeRTOS.h and semphr.h

Figure 6.4a: add 2 header files

(B) Add tasks related definitions (figure 6.4b)


In app.h file define the various tasks related parameters used in the application code
1. Define the stack needed for each task
2. Define the tasks priority for each task
3. Define the tasks states for each task state machine

Figure 6.4b: add tasks related definitions

6-4
TLS4102

(C) APP_DATA structure definition (figure 6.4c)


In app.h file look for APP_DATA structure and modify it as follows : declare a structure con-
taining handles to the various tasks, semaphores and drivers

Figure 6.4c: APP_DATA


structure definition

(A) UART strings definitions (figure 6.5a)


In the application file app.c , below APP_DATA appData define the 2 strings used in the appli-
cation through pointers : pSHW_TaskString and pSGR_TaskString

Figure 6.5a: UART


strings definitions

(B) Tasks Declarations (figure 6.5b)


In the application file app.c declare the 3 different tasks functions of the application :
LEDblinktask(), Send_HelloWorld_Task(), Send_GoRattlers_Task()

Figure 6.5b: Tasks


declaration

6-5
TLS4102

(C1) Definition of APP_Initialize() (figure 6.5c1)


In the application file app.c, modify the APP_Initialize function which initializes the application
structure elements (appData.xxx), creates one binary semaphore for each UART task (see step 5
(D) for explanations about binary semaphores) and defines the 3 function tasks.

Figure 6.5c1: definition of APP_Initialize() =>

6-6
TLS4102

(C2) Definition of APP_Initialize() (continued) (figure 6.5c2)


Create the task which blinks the LED and the 2 tasks which send strings on the UART.
In case of errors blink the 3 LEDs (BSP_LED_1, BSP_LED_2 & BSP_LED_3) and loop forever

Figure 6.5c2: definition of APP_Initialize()

6-7
TLS4102

(D) Define LEDblinkTask() (figure 6.5d)


This is the heartbeat from FreeRTOS. The LED task is delayed from x ticks, in this case 500ms.
Insert it before APP_Tasks() function definition

Figure 6.5d : define LEDblinktask()

Binary semaphore background material (FreeRTOS)


Function that creates a binary semaphore. Binary semaphores are either available, or not
available, hence binary.

The semaphore is created in the 'empty' state, meaning the semaphore must first be given
before it can be taken (obtained) using the xSemaphoreTake() function.

Binary semaphores and mutexes are very similar but have some subtle differences: Mutexes
include a priority inheritance mechanism, binary semaphores do not. This makes binary se-
maphores the better choice for implementing synchronisation (between tasks or between
tasks and an interrupt), and mutexes the better choice for implementing simple mutual exclu-
sion.

A binary semaphore need not be given back once obtained, so task synchronisation can be
implemented by one task/interrupt continuously 'giving' the semaphore while another conti-
nuously 'takes' the semaphore.

The priority of a task that 'takes' a mutex can potentially be raised if another task of higher
priority attempts to obtain the same mutex. The task that owns the mutex 'inherits' the priority
of the task attempting to 'take' the same mutex. This means the mutex must always be 'given'
back - otherwise the higher priority task will never be able to obtain the mutex, and the lower
priority task will never 'disinherit' the priority.

Both mutex and binary semaphores are assigned to variables of type SemaphoreHandle_t
and can be used in any API function that takes a parameter of this type.

6-8
TLS4102

(E) Definition of Send_HelloWorld_Task() state machine (figure 6.5e)


This state machine takes care of the task sending the string “Hello World”

Figure 6.5e : Definition of Send_HelloWorld_Task() state machine

6-9
TLS4102

(F) Definition of Send_GoRattlers_Task() state machine (figure 6.5f)


This state machine takes care of the task sending the string “GoRattlers”

Figure 6.5f : Definition of Send_GoRattlers_Task() state machine

6-10
TLS4102

(A) system_interrupt.c references(figure 6.6a)


1. Include app.h header file
2. Declare appData as extern

Figure 6.6a : system_interrupt.c


references

(B) Interrupt Handler for the switches (figure 6.6c)


The interrupt handler takes care about the following :
1. Check which switch has been pushed (SW2 or SW3) and give the semaphore to its related task
printing on the UART. This must happen when both the switch is released and there was a
transition on the pin (use PORTB & CNSTATB registers)
2. Clear the Change Notification interrupt flag . To ensure atomicity, make sure to disable and
enable interrupts around this piece of code
3. Restore the context using the portEND_SWITCHING_ISR() macro

Switches SW1 to SW3 are connected to RB12/13/14


respectively on the PIC32MZ EF starter kit (figure
6.6b) . To get interrupts when these switches are used,
these pins need to be used as Change Notification pins.
Additionally these pins were initialized with pull-up
resistors. Whenever both PORTBx and CNSTATBx ( x
being bit 13 or bit14) are true, a switch was released Figure 6.6b : PIC32MZ EF starter
kit user switches schematic

6-11
TLS4102

xSemaphoreGiveFromISR() background material (FreeRTOS)


xSemaphoreGiveFromISR
( SemaphoreHandle_t xSemaphore,
signed BaseType_t *pxHigherPriorityTaskWoken}
Macro to release a semaphore. The semaphore must have previously been created with a
call to xSemaphoreCreateBinary() or xSemaphoreCreateCounting(). This macro can be used
from an ISR.
Parameters :
xSemaphore A handle to the semaphore being released. This is the
handle returned when the semaphore was created.
pxHigherPriorityTaskWoken xSemaphoreGiveFromISR() will set
*pxHigherPriorityTaskWoken to pdTRUE if giving the semaphore caused a task to unblock,
and the unblocked task has a priority higher than the currently running task. If xSemaphore-
GiveFromISR() sets this value to pdTRUE then a context switch should be requested before
the interrupt is exited.
Returns : GiveFromISR() sets this value to pdTRUE then a context switch should be re-
quested before the interrupt is exited.
From FreeRTOS V7.3.0 pxHigherPriorityTaskWoken is optional and can be set to NULL.

Figure 6.6c :
interrupt han-
dler for the
switches

6-12
TLS4102

FreeRTOS application test procedure


1. Connect a mini-B USB cable between the J11 connector (below the PHY daughter PCB) on
the PIC32MZ EF Starter kit & the host PC (figure 6.7a) to add a virtual COM port
2. Connect a USB cable to the PC and launch Tera Term Pro freeware or any other terminal em-
ulator with these settings: 9600 baud, 8, N, 1. ( Setup > Serial port > …)

First do a clean build and you are now able to build, program, run

Figure 6.7a :
Mini-B USB connector
to virtual COM port

3. Try to push simultaneously the switches SW1 and SW2 (figure 6.7b) on the PIC32MX EF
starter kit.
4. You should see 2 strings which never get mixed up even if switches are pushed together thanks
to the usage of the binary semaphore provided by FreeRTOS which gives exclusive access to
the UART resource (figure 6.7c)

Figure 6.7b:
Switches SW1 & SW2 from
PIC32MZ EF starter kit

Figure 6.7c :
Tera Term pro terminal
messages from SW1 & SW2

6-13