You are on page 1of 66

Embedded Systems and PIC Lab

66496

Students Manual

Prepared and Collected by:


Dr. Emad Natsheh
General Safety Instructions for the Computer Engineering Labs:
1. Tampering with devices is prohibited. In the case of a device malfunction,
the lab supervisor must be informed immediately.

2. When conducting the lab experiments, the correctness of the wiring and
circuit connections must be verified. The power sources must be properly
turned off. The activation of the power sources must not occur without the
permission of the lab supervisor or the instructor.

3. The setting of the power sources (in terms of utilizing AC or DC) must be
verified.

4. In the event of an evacuation alarm, please stay calm and follow the
instructions of the University general safety committee in this regard.

5. In the event of a fire, the Foam-type Fire Extinguisher is to be used only.


The Powder-type Fire Extinguisher is strictly prohibited due to the damage
it inflicts on the computers.

6. The student must consult the lab supervisor in the case a device stops
working or in the case of an electricity outage.

7. Tampering with the 220V device power lines is prohibited. Do not insert
any object into the openings of the power line adapters or sockets.

2
General Rules and Regulations for the Computer Engineering Labs:
1. Eating, using mobile phone, drinking and smoking are strictly prohibited
in the lab.
2. You must faithfully follow the instructions of the lab supervisor.
3. Students are prohibited from entering the lab premise in the absence of the
lab supervisor or anyone fulfilling that role.
4. It is strictly prohibited to take any lab item or equipment outside the lab
without the permission of the lab supervisor. In the case such permission
exists, the Temporary Loan Form must be filled out duly.
5. The lab time schedule must be observed. It is prohibited to be present in
the lab before or after the designated time slot without prior coordination
and permission.
6. It is prohibited to conduct any experiment or drill in the absence of the lab
supervisor or the instructor.
7. The workbenches and tables must be arranged properly before leaving the
lab.
8. When in the lab, maintain a serious and responsible conduct and refrain
from joking and any irresponsible behavior.
9. Avoid fiddling with devices that you are not familiar with or ones that you
do not know how to operate very well.
10.Relocating lab equipment is prohibited without the lab supervisor
permission.
11.The student must prepare beforehand for any experiment or drill he/she is
going to conduct in the lab.
12.All devices must be turned off as soon as the student is done from using
them.
13.Students are advised to rest frequently while working on computers.
14.The main power safety switch must be turned off when the lab activities
conclude.

3
INTRODUCTION
The PIC32MX Microcontroller Unit (MCU) is a complex system-on-a-chip that is based
on a M4K™ core from MIPS® Technologies. M4K™ is a state-of-the-art 32-bit, low-
power, RISC processor core with the enhanced MIPS32® Release 2 Instruction Set
Architecture. This section provides an overview of the CPU features and system
architecture of the PIC32MX family of microcontrollers.
Key Features
 Up to 1.5 DMIPS/MHz of performance
 Programmable prefetch cache memory to enhance execution from Flash memory
 16-bit Instruction mode (MIPS16e) for compact code
 Vectored interrupt controller with 63 priority levels
 Programmable User and Kernel modes of operation
 Atomic bit manipulations on peripheral registers (Single cycle)
 Multiply-Divide unit with a maximum issue rate of one 32 × 16 multiply per clock
 High speed Microchip ICD port with hardware-based non-intrusive data
monitoring and application data streaming functions
 EJTAG debug port allows extensive third party debug, programming and test tools
support
 Instruction controlled power management modes
 Five stage piplined instruction execution
 Internal Code protection to help protect intellectual property

1.1. PIC32MX Architecture Overview

The PIC32MX family processors are complex systems-on-a-chip that contain many
features. Included in all processors of the PIC32MX family is a high-performance RISC
CPU, which can be programmed in 32-bit and 16-bit modes, and even mixed modes. The
PIC32MX MCU contains a high-performance interrupt controller, DMA controller, USB
controller, in-circuit debugger, high performance switching matrix for high-speed data
accesses to the peripherals, on-chip data RAM memory that holds data and programs. The
unique prefetch cache and prefetch buffer for the Flash memory, which hides the latency
of the flash, gives zero Wait state equivalent performance.
There are two internal buses in the chip to connect all the peripherals. The main peripheral
bus connects most of the peripheral units to the bus matrix through a peripheral bridge.
There is also a high-speed peripheral bridge that connects the interrupt controller DMA
controller, in-circuit debugger, and USB peripherals. The heart of the PIC32MX MCU is
the M4K CPU core. The CPU performs operations under program control. Instructions are
fetched by the CPU, decoded and executed synchronously. Instructions exist in either the

4
Program Flash memory or Data RAM memory. Figure I show the PIC32MX Block
Diagram.
The PIC32MX CPU is based on a load/store architecture and performs most operations on
a set of internal registers. Specific load and store instructions are used to move data between
these internal registers and the outside world.

Figure I - PIC32MX MCU Block Diagram

In this lab, we will use the PIC32MX795F512L (Cerebot MX7cK).

1.2. Cerebot MX7cK Overview

The Cerebot MX7cK is a microcontroller development board based on the Microchip


PIC32MX795F512L, a member of the 32-bit PIC32 microcontroller family. It is
compatible with Digilent’s line of Pmod™ peripheral modules, and is suitable for use with
the Microchip MPLAB IDE tools. The Cerebot MX7cK is also compatible for use with the
chipKIT™ MPIDE development environment. ChipKIT and MPIDE is a PIC32 based

5
system compatible with many existing Arduino™ code examples, reference materials and
other resources.
The Cerebot MX7cK is designed to be easy to use and suitable for use by anyone from
beginners to advanced users for experimenting with embedded control and network
communications application. A built in programming/debugging circuit compatible with
the Microchip MPLAB IDE is provided, so no additional hardware is required for use with
MPLAB. The kit contains everything needed to start developing embedded applications
using either the MPLAB® IDE or the MPIDE.

The Cerebot MX7cK provides 52 I/O pins that support a number of peripheral functions,
such as UART, SPI and I2C™ ports as well as five pulse width modulated outputs and five
external interrupt inputs. Its network and communications features also include a 10/100
Ethernet interface, Full Speed USB 2.0 OTG interface, and dual CAN network interfaces.
Ten of the I/O pins can be used as analog inputs in addition to their use as digital inputs
and outputs. Figure II shows the Cerebot MX7cK Circuit Diagram.
The Cerebot MX7cK can be powered in various ways via USB, or using an external AC-
DC power adapter.

Figure II - Cerebot MX7cK Circuit Diagram

1.3. Functional Description

The Cerebot MX7cK is designed for embedded control and network communications
applications as well as for general microprocessor experimentation. Firmware suitable for

6
many applications can be downloaded to the Cerebot MX7cK’s programmable PIC32
microcontroller.
Features of the Cerebot MX7cK include:

 a PIC32MX795F512L microcontroller
 Support for programming and debugging within the Microchip MPLAB
development environment
 Support for programming within the chipKIT MPIDE development environment
 Six Pmod connectors for Digilent peripheral module boards
 10/100 Ethernet
 USB 2.0 compatible Device, Host, and OTG support
 Two CAN network interfaces
 Three push buttons
 Four LEDs
 Multiple power supply options, including USB powered
 ESD protection and short circuit protection for all I/O pins.

Features of the PIC32MX795F512L include:

 512KB internal program flash memory


 128KB internal SRAM memory
 USB 2.0 compliant full-speed On-The-Go (OTG) controller with dedicated DMA
channel
 10/100 Ethernet controller
 Two CAN network controllers
 Up to four serial peripheral interfaces (SPI)
 Up to six UART serial interfaces
 Up to four I2C serial interfaces
 Five 16-bit timer/counters
 Five timer capture inputs
 Five compare/PWM outputs
 Sixteen 10-bit analog inputs
 Two analog comparators

The Cerebot MX7cK has a number of input/output connection options, and is designed to
work with the Digilent line of Pmod peripheral modules that provide various input and
output functions. In addition to the Pmod connectors, the board provides three push buttons
and four LEDs for user I/O, as well as providing connections for two I2C busses. A serial
EEPROM is provided on one of the I2C busses.

The Cerebot MX7cK features a flexible power supply system with a number of options for
powering the board as well as powering peripheral devices connected to the board. It can
be USB powered via the debug USB port, the USB UART serial port, or the USB device
port. It can also be powered from an external 5V power supply.

7
The Cerebot MX7cK features a flexible power supply system with a number of options for
powering the board as well as powering peripheral devices connected to the board. It can
be USB powered via the debug USB port, the USB UART serial port, or the USB device
port. It can also be powered from an external 5V power supply.

1.4. Programming Tools


The Cerebot MX7cK can be used with either the Microchip MPLAB® development
environment or the chipKIT MPIDE development environment. When used with the
MPLAB® IDE, in-system-programming and debugging of firmware running on the
PIC32MX795 microcontroller is supported using an on-board programming/debugging
circuit licensed from Microchip.

The Cerebot MX7cK is immediately useable with either the MPLAB IDE or the chipKIT
MPIDE. No additional hardware is required to use the board with the Microchip MPLAB
tools

The Microchip MPLAB IDE or the MPLAB X IDE can be used to program and debug
code running on the Cerebot MX7cK board using the built-in programming/debugging
circuit.

When creating a new project, use the “Configure.Select Device…” menu to specify the
PIC32 device being used. Ensure that the device is set to PIC32MX795F512L.

In order to use the on-board programming/debugging circuit it must be selected as the


debugger or programmer within the MPLAB IDE. Use the “Debugger.Select Tool” menu,
or the “Programmer.Select Tool” menu, and select “Licensed Debugger” as the
programmer or debugger.

The licensed debugger interface uses USB connector J15, labeled DEBUG. Connector J15
is a USB micro-B connector located on the left side of the board below the Ethernet RJ45
connector. Use a USB-A to micro-B cable (provided with the board) to connect to an
available USB port on the PC.

When the licensed debugger is selected as the programming or debugging device, the
MPLAB IDE will check the version number of the firmware running on the debugger and
offer to update if it is out of date with the version of MPLAB being used.

The PIC32 in-system programming/debugging interface uses two pins on the


microcontroller. These devices support two alternate pin pairs for this interface:
PGC1/PGD1 or PGC2/PGD2. The PGC2/PGD2 pair is used by default. Due to conflicting
uses of the microcontroller pins, the Cerebot MX7cK is designed to use the PGC1/PGD1
pair of pins. Because of this, it is necessary to select the use of PGC1/PGD1 for the
debugging interface. This is done using configuration variables set using the #pragma

8
config statement. The following statement must be used to configure the microcontroller
for use with the on-board licensed debugger circuit:

#pragma config ICESEL = ICS_PGx1

The MPLAB IDE may report an error indicating that the device is not configured for
debugging until a program containing this statement has been programmed into the board.
The MCLR pin on the PIC32 microcontroller is used by the hardware
programming/debugging interface to reset the processor. This same pin is used by the USB
serial converter to reset the processor when using the MPIDE. It is possible that the reset
function from the USB serial interface can interfere with correct operation of the Microchip
programming and debugging tools. If this happens, jumper JP11 can be used to disconnect
the USB serial converter reset circuit. Remove the shorting block from JP11 to disable the
reset circuit. If the shorting block has been removed, it is necessary to reinstall it on JP11
in order to use the Cerebot MX7cK board with the MPIDE again.

1.5. Board Hardware Description

The following describes the various hardware features of the Cerebot MX7cK board and
the PIC32XM795F512L microcontroller.

1.5.1. Board Power Supply

Switch SW1, in the lower left corner of the board is the power switch. Place this switch in
the ON position to turn on board power and in the OFF position to turn off board power.
The Cerebot MX7cK may be USB powered via either the USB debug port, the USB UART
port, or the USB device port. Alternatively, the board may be powered via dedicated,
“external”, power supply connectors.
Jumper block J3 selects the power source used to provide power to the board. This jumper
block provides the following four positions:

 USB – power is supplied by USB device connector J19. This is used when the
Cerebot MX7cK is being used to implement a USB bus powered device.
 EXT – Power is supplied by one of the external power connectors.
 DBG – Power is supplied by DEBUG USB connector J15.
 UART – Power is supplied by UART USB connector J2.

Place the shorting block in the appropriate position on J3 for the desired power source for
the board.

9
The Cerebot MX7cK is rated for external power from 3.6 to 5.5 volts DC. Using a voltage
outside this range will damage the board and connected devices. For most purposes, when
using external power, a regulated 5V supply should be used. If the board is operated from
an external supply with a voltage less than 5V, some features won’t work correctly.

The PIC32 microcontroller operates at 3.3V. And the I/O pins provide 3.3V logic levels. It
is possible, in some circumstances, to use the Cerebot MX7cK to operate with 5V logic
devices however.

There are two issues to consider when dealing with 5V compatibility for 3.3V logic. The
first is protection of 3.3V inputs from damage caused by 5V signals. The second is whether
the 3.3V output is high enough to be recognized as a logic high value by a 5V input.

The digital only I/O pins on the PIC32 microcontroller are 5V tolerant. It is safe to apply
5V logic signals directly to these pins without risk of damage to the microcontroller.

The analog capable I/O pins on the PIC32 are not 5V tolerant. The absolute maximum
voltage rating for the analog pins is 3.6V. Generally, the analog pins are the pins on I/O
port B, however, there are other non-5V tolerant pins on the device.
Refer to the PIC32MX5XX/6XX/7XX Family Data Sheet for more information about
which pins on the device are 5V tolerant before applying input signals higher than 3.3V to
any pin on the Cerebot MX7cK board.

If a 5V signal is applied to a non-5V tolerant pin, some external means must be used to
limit the applied voltage to 3.6V or less. The Cerebot MX7cK board provides 200 ohm
series resistors between the microcontroller pins and the Pmod connector pins. These
resistors are primarily intended to provide short circuit protection on the outputs, but will
also provide limited protection if a 5V signal is inadvertently applied to a non-5V tolerant
pin.

One technique that can be used to limit an input voltage to a safe level is to use a 200 ohm
series resistor and Shottky diode connected to the 3.3V supply to clamp the voltage.

The minimum output high voltage of the PIC32 microcontroller is rated at 2.4V when
sourcing 12mA of current. When driving a high impedance input (typical of CMOS logic)
the output high voltage will be close to 3.3V. Some 5V devices will recognize this voltage
as a logic high input, and some won’t. Many 5V logic inputs will work reliably with 3.3V
inputs.

If the 3.3V logic output is not sufficient for 5V logic input to be reliably seen as a logic
high input signal, some external means must be used to raise the output level. In some
cases, a pull-up resistor to 5V is sufficient. A pull-up resistor in the range of 2Kohm–

10
10kOhm can be used. This technique should not be used with pins that are not 5V tolerant
on the PIC32 microcontroller.

1.5.2. Pmod™ Connectors

The Cerebot MX7cK has six connectors for connecting Digilent Pmod peripheral modules.
The Pmod connectors, labeled JA–JF, are 2x6 pin, right-angle, female pin header
connectors. Each connector has an associated power select jumper block labeled JPA–JPF.

Digilent Pmods are a line of small peripheral modules that provide various kinds of I/O
interfaces. The Pmod product line includes such things as button, switch and LED modules,
connector modules, LCD displays, high current output drivers, various kinds of RF
interfaces, and many others.
There are two styles of Pmod connector: six-pin and twelve-pin. Both connectors use
standard pin headers with 100mil spaced pins. The six-pin connectors have the pins in a
1x6 configuration, while the twelve-pin connectors use a 2x6 configuration. All of the
Pmod connectors on the Cerebot MX7cK are twelve pin connectors.

Six-pin Pmod connectors provide four I/O signals, ground and a switchable power
connection. The twelve-pin connectors provide eight I/O signals, two power and two
ground pins. The twelve-pin connectors have the signals arranged so that one twelve-pin
connector is equivalent to two of the six-pin connectors. Pins 1–4 and 7–10 are the signal
pins, pins 5 and 11 are the ground pins and pins 6 & 12 are the power supply pins.
The pin numbering that Digilent uses on the twelve-pin Pmod connectors is non-standard.
The upper row of pins are numbered 1–6, left to right (when viewed from the top of the
board), and the lower row of pins are numbered 7–12, left to right. This is in keeping with
the convention that the upper and lower rows of pins can be considered to be two six-pin
connectors stacked. When viewed from the end of the connector, pin 1 is the upper right
pin and pin 7 is immediately below it (closer to the PCB).
Each Pmod connector has an associated power select jumper. These are used to select the
power supply voltage supplied to the power supply pins on the Pmod connector. They are
switchable between either the unregulated power supply, VCC5V0 or the 3.3V main board
supply, VCC3V3. Place the shorting block in the 3V3 position for regulated 3.3V and in
the 5V0 position to use the unregulated supply.

Each signal pin on the Pmod connectors is connected to an input/output pin on the PIC32
microcontroller. Each pin has a 200 ohm series resistor and an ESD protection diode. The
series resistor provides short circuit protection to prevent damaging the I/O block in the
microcontroller if the pin is inadvertently shorted to VDD or GND, or two outputs are
shorted together. The ESD protection diode protects the I/O block from damage due to
electro-static discharge.

11
The 200 ohm resistor in series with each I/O pin limits the amount of current that can be
sourced from the microcontroller pins. There will be a 200mV voltage drop per mA of
current sourced by the pin. This will not be a problem when driving typical, high
impedance, logic inputs, but can be problematic when trying to drive low impedance
inputs. If some cases, it may be necessary to use external buffers when trying to drive low
impedance inputs.
Although ESD protection is provided between the connector pins and the microcontroller
pins, ESD safe handling procedures should be followed when handling the circuit board.
The pins on the microcontroller and other circuits on the board are exposed and can be
damaged through ESD when handling the board.
Digilent Pmod peripheral modules can either be plugged directly into the connectors on
the Cerebot MX7cK or attached via cables. Digilent has a variety of Pmod interconnect
cables available.
See the Pinout Tables in Appendix C, below, for more information about connecting
peripheral modules and other devices to the Cerebot MX7cK. These tables describe the
mapping between pins on the PIC32MX795 microcontroller and the pins on the various
connectors.
The PIC32 microcontroller can source or sink a maximum of 18mA on all digital I/O pins.
However, to keep the output voltage within the specified input/output voltage range (VOL
0.4V, VOH 2.4V) the pin current must be restricted to +7/-12mA. The maximum current
that can be sourced or sunk across all I/O pins simultaneously is +/-200mA. The maximum
voltage that can be applied to any digital I/O pin is 5.5V. The maximum voltage that can
be applied to any analog input capable pin is 3.6V. For more detailed specifications, refer
to the PIC32MX5XX/6XX/7XX Family Data Sheet.

1.5.3. Digital Inputs and Outputs

The Cerebot MX7cK board provides access to 48 of the I/O pins from the PIC32MX795
microcontroller via the Pmod connectors. Four additional I/O pins can be accessed via the
I2C connectors, J7 and J8. Any of the pins on the Pmod or I2C connectors can be
individually accessed for digital input or output. Note that when the I2C signals on J7 or
J8 are being used for I2C communications, they are not available for general purpose I/O.
On PIC32 microcontrollers, the input/output pins are grouped into I/O Ports and are
accessed via peripheral registers in the microcontroller. There are seven I/O Ports
numbered A–G and each is 16 bits wide. Depending on the particular PIC32
microcontroller, some of the I/O Ports are not present, and not all 16 bits are present in all
I/O Ports.
Each I/O Port has four associated registers: TRIS, LAT, PORT, and ODC. The registers
for I/O Port A are named TRISA, LATA, PORTA and ODCA. The registers for the other
I/O Ports are named similarly.

12
The TRIS register is used to set the pin direction. Setting a TRIS bit to 0 makes the pin an
output. Setting the TRIS bit to 1 makes the pin an input.
The LAT register is used to write to the I/O Port. Writing to the LAT register sets any pins
configured as outputs. Reading from the LAT register returns the last value written.
The PORT register is used to read from the I/O Port. Reading from the PORT register
returns the current state of all of the pins in the I/O Port. Writing to the PORT register is
equivalent to writing to the LAT register.

PIC32 microcontrollers allow any pin set as an output to be configured as either a normal
totem-pole output or as an open-drain output. The ODC register is used to control the output
type. Setting an ODC bit to 0 makes the pin a normal output and setting it to 1 makes the
pin an open drain output.

Refer to the PIC32MX5XX/6XX/7XX Family Data Sheet, and the PIC32 Family
Reference Manual, Section 12, IO Ports, for more detailed information about the operation
of the I/O Ports in the microcontroller.

Pmod connector JF, pins 8, 9, and 10 are connected to the signals TCK/RA1, TDI/RA4,
and TDO/RA5 respectively. These microcontroller pins are shared between general
purpose I/O functions and use by the JTAG controller. The JTAG controller is enabled on
reset, so these pins are not available for general purpose I/O until the JTAG controller is
disabled. The following statement can be used to disable the JTAG controller:
DDPCONbits.JTAGEN = 0;

On the Cerebot MX7cK, pin numbers 0-47 are used to access the pins on the Pmod
connectors and pin numbers 55-58 are used for the signal pins on the I2C connectors, J7
and J8. The pin numbers are assigned so that connector JA pin 1 (JA-01) is digital pin 0,
JA pin 2 (JA-02) is digital pin 1, and so on.

Pins 0-7 are on connector JA, pins 8-15 on JB, pins 16-23 on JC, pins 24-31 and so on.
Refer to the tables in Appendix B for detailed information about the pin mapping
between Pmod connector, logical pin number, and PIC32 microcontroller pin number and
pin function.

1.5.4. Push Buttons and LEDs

Cerebot MX7cK board provides three push button switches for user input and four LEDs
for output. The buttons, BTN1 and BTN2 are connected to I/O Port G, bits 6 and 7
respectively. BTN3 is connected to I/O Port A, bit 0. To read the buttons, pins 6 and 7 of
I/O Port G and pin 0 of I/O Port A must be configured as inputs by setting the corresponding
bits in the TRISG and TRISA registers. The button state is then obtained by reading the
PORTG or PORTA registers. When a button is pressed, the corresponding bit will be high

13
(‘1’). The pins used by the buttons are dedicated to this use and do not appear on any
connector.

Button BTN3 is connected to the signal TMS/RA0 on the PIC32 microcontroller. This
microcontroller pin is shared between general purpose I/O functions and use by the JTAG
controller. The JTAG controller is enabled on reset, and so BTN3 is not useable as a button
input until the JTAG controller is disabled. The following statement can be used to disable
the JTAG controller:
DDPCONbits.JTAGEN = 0;

The four LEDs are connected to bits 12-15 of I/O Port G. LED 1 is connected to bit 12,
LED 2 is connected to bit 13, and so on. These four pins are dedicated to use with the LEDs
and do not appear on any connector pin. To use the LEDs, configure the desired bits as
outputs by clearing the corresponding bits in the TRISG register. The state of an LED is
set by writing values to the LATG register. Setting a bit to 1 will illuminate the LED and
setting the bit to 0 will turn it off.

A reset button is at the upper right corner of the board. Pressing this button will reset the
PIC32 microcontroller.

1.5.5. CPU Clock Source

The PIC32 microcontroller supports numerous clock source options for the main processor
operating clock. The Cerebot MX7cK board is designed to operate with either a silicon
resonator from Discera, IC2, for use with the EC oscillator option, or an external crystal,
X1, for use with the XT oscillator option. Standard production boards will have an 8Mhz
Discera silicon resonator loaded and the EC oscillator option should be used. If IC2 is not
loaded, an 8Mhz crystal will be loaded for X1 (on the bottom of the board) and the XT
oscillator option should be used. Oscillator options are selected via the configuration
settings specified using the #pragma config statement. Use #pragma config
POSCMOD=EC to select the EC option and #pragma config POSCMOD=XT to select the
XT option.

Using the internal system clock phase-locked loop (PLL), it is possible to select numerous
multiples or divisions of the 8Mhz oscillator to produce CPU operating frequencies up to
80Mhz. The clock circuit PLL provides an input divider, multiplier, and output divider.
The external clock frequency (8Mhz) is first divided by the input divider value selected.
This is multiplied by the selected multiplier value and then finally divided by the selected
output divider. The result is the system clock, SYSCLK, frequency. The SYSCLK
frequency is used by the CPU, DMA controller, interrupt controller and pre-fetch cache.

14
The operating frequency is selected using the PIC32MX795 configuration variables. These
are set using the #pragma config statement. Use #pragma config FPLLIDIV to set the input
divider, #pragma config FPLLMUL to set the multiplication factor and #pragma config
FPLLODIV to set the output divider. Refer to the PIC32MX5XX/6XX/7XX Family Data
Sheet and the PIC32MX Family Reference Manual, Section 6. Oscillators for information
on how to choose the correct values, as not all combinations of multiplication and division
factors will work.

In addition to configuring the SYSCLK frequency, the peripheral bus clock, PBCLK,
frequency is also configurable. The peripheral bus clock is used for most peripheral
devices, and in particular is the clock used by the timers, and serial controllers (UART,
SPI, I2C). The PBLCK frequency is a division of the SYSCLK frequency selected using
#pragma config FPBDIV. The PBCLK divider can be set to divide by 1, 2, 4, or 8.

The following example will set up the Cerebot MX7cK for operation with a SYSCLK
frequency of 80MHz and a PBCLK frequency of 10MHz:
#pragma config FNOSC = PRIPLL
#pragma config POSCMOD = EC
#pragma config FPLLIDIV = DIV_2
#pragma config FPLLMUL = MUL_20
#pragma config FPLLODIV = DIV_1
#pragma config FPBDIV = DIV_8

Documentation for the PIC32 configuration variables can be found in the PIC32MX
Configuration Settings guide. This is found using the “Help.Topics…” command in the
MPLAB IDE. Also, refer to Appendix C for an example of setting the configuration
variables.

1.5.6. Analog Inputs

The PIC32MX795 microcontroller provides a 10-bit analog to digital (A/D) converter that
provides up to sixteen analog inputs. The Cerebot MX7cK board provides access to 10 of
these inputs via the Pmod connectors. The converted values produced by the A/D converter
will be in the range 0–1023.

For detailed information on the operation and use of the A/D converter, refer to the PIC32
Family Reference Manual, Section 17, 10-bit AD Converter.

15
The following gives the Pmod connector position, digital pin number, and microcontroller
I/O port and bit number for the analog inputs:

 A0 – JA-01, digital pin 0, RB02


 A1 – JA-02, digital pin 1, RB03
 A2 – JA-03, digital pin 2, RB04
 A3 – JA-04, digital pin 3, RB06
 A4 – JA-07, digital pin 4, RB07
 A5 – JA-08, digital pin 5, RB08
 A6 – JA-09, digital pin 6, RB09
 A7 – JA-10, digital pin 7, RB10
 A8 – JC-07, digital pin 20, RB15
 A9 – JC-10, digital pin 23, RB14

1.5.7. A/D Converter Voltage Reference

The PIC32 microcontroller provides two voltage reference inputs to the analog to digital
converter. Vref- is used set the lower reference level and Vref+ is used to set the upper
reference level. These references can be connected to internal references or to external
references using two of the analog input pins.

When the internal references are being used, Vref- is connected to VSS and Vref+ is
connected to VDD. This means that the voltage input range at the analog input pins is 0V–
3.3V. In this case, an input voltage of 0V will convert to ~0, an input voltage of 1.65V will
convert to ~511, and an input voltage of 3.3V will convert to ~1023.

Either one, or both, of the references can be connected to external reference pins. When
this is done, the references can be set to voltages other than 0V and 3.3V.

If, for example, both references were selected to use external references, with 1V applied
to Vref- and 2V applied to Vref+, the input voltage range at the analog input pins would
be from 1V to 2V. An applied voltage of 1V would have a converted value of ~0, 1.5V
would have a converted value of ~511, and 2V would have a converted value of ~1023.
When both external references are being used, Vref+ must have a higher voltage applied
to in than Vref-.

The analog reference input pins appear on Pmod connector JE, pins 9 & 10. Vref- is on pin
JE-09, and Vref+ is on pin JE-10. These pins are not available to be used for digital I/O
when being used as an external reference.

16
Objective
The main objective is to teach students how to design and build embedded systems using
PIC microcontrollers. Also its elaborate students’ capability in terms of interfacing with
microcontrollers.

Outcomes
After the completion of this lab, the student will have
1. The ability to Build PIC32 applications using C language
2. The ability to handle different peripherals using the PIC microcontroller
3. The ability to deal with and develop complex systems, which involves
hardware/software co-design.

Reference materials
Besides what will be explained in the experiments, the student may refer to the datasheets,
books and materials used in the prerequisite course Microcontroller (66426).

Experiments and plan:

Week Experiment
1 Introduction
2 ChipKIT™ Pro and I/O Control
3 &4 Universal Asynchronous Receiver Transmitter
5 Bluetooth Interface
6 Positioning Satellites (GPS)
7 Keypad Handling
8 Timers & Interrupts
9 Controlling a DC Motor
10 Frequency Measurement Using Input Capture
11 Controlling a Stepper Motor
12 Design Challenge #1: Garage Door Control
13-15 Design Challenge #2: Large 4-bit OLED Display

17
Experiment #1
Introduction to MPLAB ® X – Integrated Development
Environment

Objective:
The aim of this tutorial is to teach the students some of the aspects of an important tool that
can assist in software development. Its introduces you to the synthesis and analysis tools
for producing microprocessor C code using the MPLAB ® X integrated development
environment (IDE) on the chipKITTM Pro MX7 processor board.

Overview
The target system for this Lab is the Digilent chipKITTM Pro MX7 processor board.
Conventional IDE systems consist of software that runs on the PC or Linux computer and
special hardware that manages the microcontroller on the target system. A separate PIC
microcontroller on the chipKITTM Pro MX7 processor board provides the special
hardware needed to interface with the PC that is running the MPLAB ® X IDE. The IDE
assists the program developer in converting one or more text files written using C or
assembly language instructions into a file that contains a set of binary instructions that is
programmed into a microprocessor.
The MPLAB ® X IDE does this transformation in four steps. First, the editor is where the
programmer writes his or her C language programs. A project consists of one or more text
files that the compiler converts into one or more object files. The object files are combined
using a linker that generates a single file that the loader then programs into the
microprocessor.
Source files with the “.c” extension contain C statements that define the functionality of
the file such as the interface to an LCD or the implementation of a software time delay.
Files with the “.h” extension are called header files that contain C instructions and
directives that allow the source code to be reused in different application. Generally each
“.c” file has a companion “.h” file that contains function prototypes and definitions.
The MPLAB ® X editor has many features to help you to write C code that the compiler
can convert into an object file. The compiler checks each source file for proper C syntax
and that all references are resolved. Compiler errors are identified with the file name, the
line number in the file where the error was detected, and a description of the error. The link
and load processes will be completed only if the compiler completes its task without
finding any errors. There may be times that the compiler generates warnings. In such cases,
the link and load operations will still be completed. Compiler warnings are generated if the
source code attempts to give the compiler an instruction that is ambiguous or confusing but
the syntax is correct. In these cases, the compiler makes a reasonable but not necessarily

18
correct interpretation of your instruction. Clean code is code that compiles with no errors
or warnings when using the setting for the highest level of error and warning generation.
However, the fundamental skill to learn in this tutorial is how to use the MPLAB IDE to
develop software that runs on the PIC32 processor. The steps in this exercise are designed
to show you how to create a new stand-alone project and how to use the software
instrumentation to verify that the program is executing as designed.

MPLAB ® X IDE Tutorial

Connecting the chipKITTM Pro MX7 Processor Board

Error! Reference source not found.-1 is a picture of the chipKITTM Pro MX7 processor
board. Before connecting the debugging USB cable to the PC, verify that the Board Power
select jumpers shown at the upper left are positioned correctly. As shown, the processor
board is powered using the debugging PC USB connection. The board power switch is
located in the lower left corner. Once the board power is turned on, the RED power
indication LED should be on. It is helpful to connect the processor board with the
debugging USB cable and power it on before launching a new MPLAB ® X project.

Power
Select

Power
LED

Debug USB

Power
Switch

Figure 1-1 chipKITTM Pro MX7 processor board

19
Launching a New MPLAB ® X Project

1. Launch the MPLAB ® X IDE by selecting the MPLAB ® X icon on the PC


desktop. Initially, a window for a blank project page as shown in Figure 1-2 will
appear.

Figure 1-2 MPLAB ® X IDE window

2. Create a new MPLAB ® X project by clicking of the “Create a New Project” link
in the Drive In box shown on the MPLAB ® X Start Page. A new window will be
launched as shown in Figure 1-3. Click on the standalone project.

20
Figure 1-3 creating a new MPLAB ® X project

3. Next, you will need to select the processor that is on the chipKITTM Pro MX7
processor board. This step is divided into two parts for simplicity: Error!
Reference source not found.1-4 shows the selection of the device family as 32-bit
MCUs(PIC32). Error! Reference source not found.1-5 shows that the processor
device we are using is the PIC32MX795F512L. Click on the Next> control to
continue to the next step.

Figure 1-4 selection of the device family

21
Figure 1-5 selection of the processor device

4. After that, we select the debugging tool using the window shown in Error!
Reference source not found.1-6. The debugging tool provided by Digilent for the
chipKITTM Pro MX7 processor board appears under the Other Tools folder. If a
chipKITTM Pro MX7 processor is connected to the PC via the USB cable and the
power to the board is turned on, the board’s serial number will show on the list.
Note: After the project has been built, if the project launched when the PC is
connected to a different chipKITTM Pro MX7 processor board, MPLAB ® X will
prompt you to approve the connection to the new board.

Click on the Next> control to continue to the next step.

Figure 1-6 window that selects the debugging hardware

22
5. Next is the selection of the C compiler to use from the list of C compilers found on
the PC that you are currently working on.
6. The last step in creating a project, allows you to specify where the project will be
stored (Figure 1-7). This example shows that the source files are located in a folder
named C:/code. You will specify a file location of your own choosing. The project
Location is where we will put the five source files for Project 0. Use the default
setting for the remaining options. Click on Finish to complete the process of
creating a project. The MPLAB ® X IDE window should now appear as shown in
Error! Reference source not found.1-8.

Figure 1-6 Project location

Figure1-7 MPLAB ® X screen after creating Project 0

23
Experiment #2
ChipKIT™ Pro and I/O Control

Objective:
The purpose of this experiment is to familiarize the students with the methods of reading
from and writing to the input and output (I/O) pins of the PIC™32 microcontroller.

Equipment List
1. chipKITTM Pro MX7 processor board with USB cable
2. Microchip MPLAB ® X IDE
3. MPLAB ® XC32++ Compiler

Overview
Microprocessor pins are commonly either configured to be a digital input or digital output,
hence are usually referred to as I/O pins. Digital input pins allow microprocessors to
receive binary data from their environment.

The most basic means of communicating to and from a microprocessor is through I/O pins.
On the PIC32 microprocessor, I/O pins are grouped in terms of ports, with 16 pins per port,
and the collection of bits representing the state of the I/O pins of a designated port itself
can be thought of as a word. The pins of each port are identified by a bit position in the
form Rp0 to Rp15, where “p” is a letter that represents the particular I/O port on the
processor and the numerical value (in the range 0 through 15) is the bit position within the
word. The way in which each bit within a word should be valued or interpreted is at the
discretion of the code developer.
With 16 I/O pins available on a PIC32 port, values can be represented ranging from zero
to 65535 (base 10), or, in hexadecimal, zero to 0xFFFF (the leading “0x” indicates a
hexadecimal representation of a number where each digit can have one of 16 values [0
through F] while a leading “0b” will be used to indicate a binary representation where each
digit can only have one of two values [' 0' or '1']). On the PIC32MX7 microcontroller, I/O
ports are labeled A through G. Because digital ports are limited to 16 bits, values ranging
from zero to 65535 can be directly read from or written to external connections. For
example, if RB3 is set high and all other Port B pins are set low, then the processor is
outputting a value of eight (0x0008, or in binary, 0b0000 0000 0000 1000).

24
Input pins can also be used to detect events by sensing switches, button pushes, or some
other device that outputs a binary signal, provided that an appropriate voltage level is
generated by the sensor device. Multiple event type inputs can be connected to a single 16-
bit processor port.

Figure 2-1 shows a simplified block diagram for a PIC32 I/O pin. The PIC32MX795
processor used on the chipKIT Pro MX7 supports 16 pins that can be used as either an
analog input or a digital I/O. By default, when the PIC32 is reset, these pins are set as
analog input. The bits in the AD1PCFG register corresponding to the register and a pin
number must be set to a '1' if the pin is to be used as a digital input or output.

ODCx

1
Write

Read

VDD
0
Peripheral Bus

0
LATx
1

TRISx

PORTx

1
IO Pin
0
ADC ANy

AD1PCFG
Analog Input
Multiplexer
Analog IO
Pins Only

Figure 2-8 Simplified block diagram for a PIC32 I/O pin.

One may also use PORTSetPinsDigitalIn(port, bits); or PORTSetPinsDigitalOut(port,


bits); as an alternative to setting the AD1PCFG register. These are provided by the XC32
peripheral library to set the pin as a digital input or output. For this experiment, only digital
I/O will be used.

LED1 through LED4 are connected to PORTG pins 12 through 15, respectively. BTN1
and BTN2 on the PIC32MX7 are connected to PORTG pins 6 and 7. Although BTN3 is
not used in this experiment, it will be used in future experiments, and it is worth noting that
BTN3 connects to I/O Port A bit 0 and requires disabling the JTAG programmer using the
instruction: DDPCONbits.JTAGEN = 0;.

25
Note:
Each I/O Port has four associated registers: TRIS, LAT, PORT, and ODC. The registers
for I/O Port A are named TRISA, LATA, PORTA and ODCA. The registers for the
other I/O Ports are named similarly.
The TRIS register is used to set the pin direction. Setting a TRIS bit to 0 makes the pin
an output. Setting the TRIS bit to 1 makes the pin an input.
The LAT register is used to write to the I/O Port. Writing to the LAT register sets any
pins configured as outputs. Reading from the LAT register returns the last value written.
The PORT register is used to read from the I/O Port. Reading from the PORT register
returns the current state of all of the pins in the I/O Port. Writing to the PORT register
is equivalent to writing to the LAT register.
PIC32 microcontrollers allow any pin set as an output to be configured as either a normal
totem-pole output or as an open-drain output. The ODC register is used to control the
output type. Setting an ODC bit to 0 makes the pin a normal output and setting it to 1
makes the pin an open drain output.

Experiment
The only hardware required for this experiment is the chipKIT Pro MX7 processor board.
We will be using two of the momentary push buttons as inputs and the four LEDs as
outputs. The goal is to use combinations of buttons that are pressed to control which LED
is on, based on the action described in the following table.
Table 2-1: Truth table for mapping inputs to outputs
Inputs Outputs
BTN1 BTN2 LD1 LD2 LD3 LD4
Off Off Off Off Off Off
On Off On Off Off Off
Off On Off On Off Off
On On Off Off On On

26
Initially, generate a new project. Copy the following three common files found in the
“Code” folder in the Desktop: config_bits.h, pic32mx.h, and pic32mx.c. Add them to the
project directory and add them to the project. Create a new C file called Project1.c and
modify it as shown in the following listing:

#include <plib.h>
#include “config_bits.h”
#include “pic32mx.h”

int main(void)
{
sys_init(); /* See the function pic32mx_Setup() in pic32mx.c
for details of configuration of the processor board */

/* Project initialization code goes here */

while(1)
{
/* Project operational code goes here */
}
return 1; // This line of code will never be executed.
}

The first step for any microprocessor based designed is to configure the microprocessor to
accommodate the hardware platform and the application requirements. For this project,
the board initialization requires only a few program statements. Port G bits 6 and 7 must
be set as digital inputs to allow reading of the pushbuttons BTN1 and BTN2. This can be
accomplished using the following statement:
PORTSetPinsDigitalIn(IOPORT_G, BIT_6 | BIT_7);
This project does not use BTN3 but if an application did require the use of BTN3, the next
two lines of code are needed.
DDPCONbits.JTAGEN = 0; // Disable JTAB programming
PORTSetPinsDigitalIn(IOPORT_A, BIT_0);
Port G bits 12 through 15 must be set as digital outputs to control LED1 through LED4.
Usually, the initial value of the outputs must also be set. This can be accomplished using
the following statements:
PORTSetPinsDigitalOut(IOPORT_G, BIT_12 | BIT_13 | BIT_14 | BIT_15);
PORTClearBits(IOPORT_G, BIT_12 | BIT_13 | BIT_14 | BIT_15);

27
Constants BIT_0 through BIT_15 are defined as constants 0x0001, 0x0002, 0x0004 …
0x8000 in the included file, plib.h. The pic32mx.h file also defines LED1 through LED4
as BIT_12 through BIT_15 as well as defining BTN1 as BIT_6, BTN2 as BIT_7 and BTN3
as BIT_0. It is then possible to use the following lines of code to set the button and LED
I/O if the file pic32mx.h is included in a project:
PORTSetPinsDigitalIn(IOPORT_G, BTN1 | BTN2);
DDPCONbits.JTAGEN = 0; // Disable JTAB programming
PORTSetPinsDigitalIn(IOPORT_A, BTN3);

PORTSetPinsDigitalOut(IOPORT_G, LED1 | LED2 | LED3 | LED4);


PORTClearBits(IOPORT_G, LED1 | LED2 | LED3 | LED4);

After the processor has been initialized, the program must continually read the input to
determine whether a particular button is pressed (logical value of true) or released (logical
value of false), execute logic to determine which of the LEDs to turn on and off, and set
the output pins accordingly. The program maps the two button inputs to one of four LED
outputs using the logic expressed by the truth table shown in Table 1. The LEDs are driven
by the output pins so writing a logical 1 to the LED port will cause the LED to be lit.
The infinite processing is implemented inside the while(1) loop, as illustrated in the flow
diagram shown in Figure 2-2.

Task
Manager
(main)
LE
s D
Hardware
LED On/OFF Code

u
tat O
n/
sS
ButtonsStatus

O
Setup tto
n FF
Bu Co
(sys_init) de

Read button Control


status LEDs
(buttons) Process (led)
Buttons
(map)

BTN1 and BTN2 LED1 – LED4

Figure 2-9 Example data flow diagram

28
Experiment #3
Universal Asynchronous Receiver Transmitter

Objective:
The purpose of this experiment is to learn about asynchronous communications and how
to communicate with a microcontroller using a terminal emulation program to implement
a point-to point-serial link between the chipKIT™Pro MX7 and a PC.

Equipment List
1. chipKITTM Pro MX7 processor board with USB cable
2. Microchip MPLAB ® X IDE
3. MPLAB ® XC32++ Compiler
4. PC-based terminal emulations (HyperTerminal®)

Overview
Asynchronous communications is a serial data protocol that has been in use for many years.
Normally eight bits of data are transmitted at a time. There are other less commonly used
modes that can send 5, 6, or 7 bits of data. Each byte of data is framed by a start bit and a
stop bit (Figure 3-1). A symbol is defined as a start, data, parity, or stop bit. It is common
to define communications speed as bits per second. The bit rate is defined as the inverse of
the period of a unit symbol. Although the common standard bit rates are 50, 75, 110, 134,
150, 200, 300, 600, 1200, 1800, 2400, 4800, 9600, 19200, 38400, 57600, and 115200,
communications are possible at any rate provided that the sender and receiver use the same
rate. For most asynchronous communications, the term “baud” is commonly used
interchangeably with the term “bit rate.”

Figure 3-10 Simple serial communication

The Universal Asynchronous Receiver Transmitter (UART) module is one of the serial I/O
modules available in PIC32MX Family devices. The UART is a full-duplex, asynchronous
communication channel that communicates with peripheral devices and personal
computers through protocols such as RS-232, RS-485, LIN 1.2 and IrDA®.

29
The PIC32MX795 microcontroller can provide up to six UARTs. Due to conflicting uses
of many of the pins used by the UARTs, the Cerebot MX7cK is designed to allow use of
two of them: UART1 and UART2. The UARTs can provide either a 2-wire or a 4-wire
asynchronous serial interface. The 2-wire interface provides receive (RX) and transmit
(TX) pins. The 4-wire interface includes request-to-send (RTS) and clear-to-send (CTS)
in addition to receive and transmit.
UART1 can be accessed from Pmod connector JE and UART2 can be accessed from Pmod
connector JF using the following pins:

 U1CTS JE-01
 U1TX JE-02
 U1RX JE-03
 U1RTS JE-04

 U2CTS JF-01
 U2TX JF-02
 U2RX JF-03
 U2RTS JF-04

UART Programming
The UART peripheral must be initialized to set the communications bit rate, the parity
option, and the number of data bits to send and receive. Additionally, the transmit and
receive have separable enabled control bits. The XC32 peripheral library provides the
UART open function as shown below.

OpenUART1( (UART_EN | UART_BRGH_FOUR | UART_NO_PAR_8BIT),


(UART_RX_ENABLE | UART_TX_ENABLE) , brg );

The UART_EN bit sets the transmit and receive I/O pins for their alternate function to
support the UART communications. The parameter, UART_BRGH_FOUR, specifies that
the reconstruction clock rate as four times the serial port bit rate. The reconstruction clock
is used to set the sample points in the middle of the symbol. Hence the third parameter in
the OpenUART function, brg, is determined by dividing the peripheral bus clock by four
times the desired bit rate.
The UART_NO_PAR_8BIT option specifies both the data size and no parity bit for error
detection. To use even parity error detection, substitute UART_EVEN_PAR_8BIT or, for
odd parity, use UART_ODD_PAR_8BIT into this parameter field.

30
Appendix C contains the code for UART operations. UART1 is initialized by calling the
function, initialize_uart1(int bit_rate, int parity) from the users application. The parity
parameter can be specified as NO_PARITY, EVEN_PARITY, or ODD_PARITY.

Experiment
The hardware configuration for experiment 3 is shown in Figure 3-2.
This experiment will require you to input text data from the serial port that will turn one of
the LEDs (1-4) on. The text from the serial port will be echoed to the HyperTerminal.

1. Initially, generate a new project. Copy the following three common files found in
the “Code” folder in the Desktop: config_bits.h, pic32mx.h, com.h, and pic32mx.c.
Add them to the project directory and add them to the project
2. Communications will use the PC terminal emulation program for a data rate of
57.6k, no parity, 8 data bits and one stop bit.
3. Modify the com.c file to include two addition function one for sending text and the
other for Receiving.
 void SendDataBuffer(const char *buffer, UINT32 size)
 UINT32 GetDataBuffer(char *buffer, UINT32 max_size)
4. Write a C program and call it Ex3.c. This program will contain the function main
and process the serial text. Put the following tasks inside the while(1) loop:
 Wait for line of text using the “GetDataBuffer” function
 Echo the string to the HyperTerminal
 Turn one of the light on (e.g. if the text is LED1 them led 1 is on, if the text
is LED2 then led 2 is on.

Hint: The following function may help you during the implementation
 UARTReceivedDataIsAvailable Function
 UARTGetDataByte Function
 UARTTransmissionHasCompleted Function
 UARTSendDataByte Function
 UARTTransmitterIsReady Function

31
Experiment #4
Bluetooth Interface

Objective:
The purpose of this experiment is to familiarize the students with the Bluetooth interface
(PmodBT2) and how to communicate it with the microcontroller.

Equipment List
1. chipKITTM Pro MX7 processor board with USB cable
2. PmodBT2 - Bluetooth Interface
3. Microchip MPLAB ® X IDE
4. MPLAB ® XC32++ Compiler
5. PC-based terminal emulations (HyperTerminal®)

Overview
The PmodBT2 is a powerful peripheral module employing the Roving Networks® RN-42
to create a fully integrated Bluetooth interface.
The PmodBT2 uses a standard 12-pin connection and communicates via UART (See
Figure 4-1). There is a secondary SPI header on the board for updating the RN-42 firmware
if needed.

Figure 4-11 PmodBT2 block diagram

32
By default, the UART interface uses a baud rate of 115.2 kbps, 8 data bits, no parity, and
a single stop bit. The startup baud rate may be customized to predefined rates or set to a
specific user customized baud rate. Predefined baud rates range from 1200 to 921k.

The Bluetooth module operates in two modes: data mode (default) and command mode.
While in data mode, the module operates as a data pipe. When the module receives data, it
strips the Bluetooth headers and trailers and passes the user data to the UART port. When
data is written to the UART port, the module constructs the Bluetooth packet and sends it
out over the Bluetooth wireless connection. Thus, the entire process of sending/receiving
data to the host is transparent to the end microprocessor. See Figure 4-2.
In order to enter the command mode, the PmodBT2 must receive “$$$” to which it will
respond “CMD”. When in command mode, the module will respond to a large number of
commands allowing the user to customizing the module for specific applications. In order
to exit command mode, send “---<cr>” (three minus signs in a row and where <cr> stands
for the carriage return character) to which the device will respond “END”.

Figure 4-12 DATA & COMMAND MODES

Demo:
a) Connect Pmod BT2 via UART2 (JF).
b) Connect the chipKITTM Pro MX7 processor to the PC via the USB cable.
c) Install on your mobile BlueTerm app.
d) From BlueTerm app click on connect device and then select RNBT - 61E5.
e) Send “$$$” via the mobile
f) Try some command such as D, GB, GR (refer to the Bluetooth Data Module
Command Reference & Advanced Information User’s Guide for more information).

33
Experiment
This experiment will require you to implement a chat system between the mobile and the
HyperTerminal.
1. Initially, generate a new project. Copy the following three common files found
in the “Code” folder in the Desktop: config_bits.h, pic32mx.h, com.h, com.c,
and pic32mx.c. Add them to the project directory and add them to the project
2. Write a simple code to send your full name via the Bluetooth interface
a. Connect the Pmod BT2 to UART2
b. Configures the UART module at a 115.2 k data rate with 8 bits of data,
no parity, and one stop bit.
3. Modify your code to implement a chat system between the mobile and the
HyperTerminal.
a. For mobile configures the UART module at a 115.2 k data rate with
8 bits of data, no parity, and one stop bit.
b. For HyperTerminal configures the UART module at a 57.6 k data rate
with 8 bits of data, no parity, and one stop bit.

Hint:
The following function may help you during the implementation

 putsUART1
 putcUART1

34
Experiment #5
Keypad Handling

Objective:
In this experiment you have to write a program to handle the alphanumeric keypad that is
available in the design center.

Equipment List
1. chipKITTM Pro MX7 processor board with USB cable
2. PmodKYPD - 16-Button Keypad
3. Microchip MPLAB ® X IDE
4. MPLAB ® XC32++ Compiler
5. PC-based terminal emulations (HyperTerminal®)

Overview
The PmodKYPD is an array of buttons used for input. The PmodKYPD uses a standard 12-
pin Pmod header that indicates which row and which column has been pressed in the array
of buttons (see Table 5-1).
Table 5-1: Connector J1 – Column/Row Indicators

The PmodKYPD is set up as a matrix (see figure 5-1) in which each row of buttons from
left to right are tied to a row pin, and each column from top to bottom is tied to a column
pin. This gives the user four row pins and four column pins to address the button push.

35
To read a button’s state, the column pin in which the button resides must be pulled low.
This enables all of the buttons in that column.

Figure 5-1 PmodKYPD schematics.

When a button in that column is pushed, the corresponding row pin will read logic low.

All of the buttons can be read by walking a logic 0 through each column pin (keeping the
other pins at logic high) and reading the row pins. This will read the state of each button.

Experiment
This experiment will require you to implement a code to detect keystrokes from a keypad
(keypad interface program).
1. Initially, generate a new project. Copy the following three common files found
in the “Code” folder in the Desktop: config_bits.h, pic32mx.h, com.h, com.c,
and pic32mx.c. Add them to the project directory and add them to the project
2. Write a C program to do the following
a. Keep checking the keypad. If any key is pressed, your program should
determine the scanning code for this key.
b. Each time a key is pressed on the keypad, the program should display
the key to the Hyper Terminal
i. Do not forget to use software debouncing. (The available keys have a
contact bounce <12ms)

36
Experiment #6
Positioning Satellites

Objective:
The PmodGPS can add satellite positioning accuracy to any embedded system. The
purpose of this experiment is to familiarize the students with the GPS Receiver Peripheral
Module (PmodGPS).

Equipment List
1. chipKITTM Pro MX7 processor board with USB cable
2. Microchip MPLAB ® X IDE
3. MPLAB ® XC32++ Compiler
4. PmodGPS

Overview
The Global Positioning System (GPS) is a space-based satellite navigation system that
provides location and time information in all weather conditions.
There are three parts to a GPS system: a constellation of between 24 and 32 solar-powered
satellites orbiting the earth in orbits at an altitude of approximately 20000 kilometers, a
master control station and four control and monitoring stations (on Hawaii, Ascension
Islands, Diego Garcia and Kawajale) and GPS receivers.
Each of the satellites is in an orbit that allows a receiver to detect at least four of the
operational satellites. The satellites send out microwave signals to a receiver where the
built-in computer uses these signals to work out your precise distance from each of the four
satellites and then triangulates your exact position on the planet to the nearest few meters
based on these distances. Hence, the process of measuring the distance from satellite to
GPS receiver is based on timed signals.
GPS satellites synchronize operations so that these repeating signals are transmitted at the
same instant. The signals, moving at the speed of light, arrive at a GPS receiver at slightly
different times because some satellites are further away than others. The distance to the
GPS satellites can be determined by estimating the amount of time it takes for their signals
to reach the receiver. When the receiver estimates the distance to at least four GPS
satellites, it can calculate its position in three dimensions.
In fact, signals from just three satellites are needed to carry out this trilateration process;
the calculation of your position on earth based on your distance from three satellites. The

37
signal from the fourth satellite is redundant and is used to confirm the results of the initial
calculation.

PmodGPS: Functional Description & Interface


As illustrated in table 6-1, the PmodGPS uses a standard 6-pin connector and
communicates via a 2-wire Universal Asynchronous Receiver/Transmitter (UART.) The
interface operates at a default baud rate of 9.6 kBd, 8 data bits, no parity, and with single
stop bits. However, users can change the baud rate to predefined values that range from 4.8
kBd to 115.2 kBd.

The PmodGPS also has a 2-pin connector for control of the NRST pin to the module and
the Radio Technical Commission for Maritime services, or RTCM pin for Differential
Global Positioning System (DGPS) data using RTCM protocols.

Table 6-1- Interface Connector Signal Descriptions

The 3DF pin on J1 indicates the status of the user’s positional fix. When the module has a
constant fix (2D or 3D) this pin stays low, if the module is unable to get a fix then the pin
will toggle every second. (See figure 6-1) LD1 also follows this same behavior pattern in
order to give the user a visual representation.

Figure 6-13- 3DF Pin output without a fix

38
GPS - NMEA sentence information
The PmodGPS uses sentences based on National Marine Electronics Association (NMEA)
protocols for data output. Once the module connects to at least four satellites, it sends
several messages containing GPS data to the microcontroller.
Each NMEA message begins with a ($) dollar sign. The next five characters are the talker
ID and the arrival alarm. The PmodGPS talker ID is “GP” and the arrival alarm is the
specific sentence output descriptor. Individual comma separated data fields follow these
five characters. After the data fields there is an asterisk followed by a checksum. Each
sentence should end with <CR><LF>.
The most important NMEA sentences include the GGA which provides the current Fix
data, and the GSA which provides the Satellite status data1.
 $GPGGA - Global Positioning System Fix Data

$GPGGA,064951.000,2307.1256,N,12016.4438,E,1,8,0.95,39.9,M,17.8,M,,*65

Where:
$GPGGA Message ID
064951.000 UTC Time (hhmmss.sss)
2307.1256 Latitude (ddmm.mmmm)
N N/S indicator
12016.4438 Longitude (dddmm.mmmm)
E E/W indicator
1 Position Fix Indicator
8 Satellites used
0.95 Horizontal Dilution of Precision (HDOP)
39.9 MSL Altitude
M Units
17.8 Geoidal Separation
M Units
Age of Diff. Corr.
*65 Checksum

 $GPGSV - Satellites in view

$GPGSV,3,1,12,29,36,029,42,21,46,314,43, 26,44,020,43,15,21,321,39*7D
1
Other sentences may repeat some of the same information but will also supply new data, such as: RMC,
VTG, MSS …etc. (For more information see NMEA Reference Manual).

39
$GPGSV,3,2,12,22,28,259,16,27,13,107,,09,11,130,,16,09,288,25*79
$GPGSV,3,3,12,30,08,210,33,06,08,320,22,25,02,188,26,14,01,203,21*7B

Where:

$GPGSV Message ID
3 Number of Messages
1 Message Number
12 Satellites in View
29 Satellite ID (CH1)
36 Elevation (CH1)
029 Azimuth (CH1)
42 SNR (C/No)

….

15 Satellite ID CH(4)
21 Elevation (CH4)
321 Azimuth (CH4)
39 SNR (C/No)
*7D Checksum

Project Tasks
Once the module is connected to JF and we got a fix position (PF is 0), several messages
containing GPS data will be sent to the microcontroller. The goal here is to filter these
messages into data field so that they can be accessed individually.
Hence, we need to implement a C code to filter the received message and display them into
the HyperTerminal.

Note:
 The navigation through the messages data field will be done using a button (BTN1).
 For the communication configures the UARTs module at a 9.6 kBd, 8 data bits, no
parity, and with single stop bits.

Note: There are three common formats2:


 Degrees, Minutes and Seconds (DD° MM' SS.S")
This is the most common format used to mark maps.
 Degrees and Decimal Minutes
 Decimal Degrees

2
http://www.sunearthtools.com/dp/tools/conversion.php

40
Experiment #7
Timers & Interrupts

Objective:
The purpose of this experiment is to understand the operation of PIC™32 timers so that
they can be used to implement a synchronized multi-rate periodic control system by
polling the timer interrupt flag. Also to explore detecting events using interrupts.

Equipment List
1. chipKITTM Pro MX7 processor board with USB cable
2. Microchip MPLAB ® X IDE
3. MPLAB ® XC32++ Compiler

Overview

 PIC32 Timers
All timers have a period register that is used to set the timer’s maximum count. The period
registers are declared as PR1 for Timer 1, PR2 for Timer 2, and so on. Whenever the time
count reaches the value stored in the period register, a timer interrupt flag is set and the
timer register is reset to zero. Once the timer interrupt flag is set, it will remain set until a
software instruction clears the flag.
Timers are initialized using the OpenTimer function that requires two arguments: the
configuration argument and the initial PR value. For example, initializing Timer 1 to use
the peripheral bus clock, a prescale value of 8, and an initial period of 1000 requires the
following assignment:
OpenTimer1((T1_ON | T1_SOURCE_INT | T1_IDLE_CON | T1_PS_1_8), 999);

The timer interrupt flag is polled using the macro statement, “mTxGetIntFlag();,” and
can be cleared using the macro, mTxClearFlag(). Both macros are defined by the
peripheral library.
The PR register for the timers can be changed within the software at any time by simply
using the assignments PRx = ###; or WritePeriodx( ###);, where x is the timer number
and ### is the value to be set into the PR register.

41
There are two arguments required for the OpenTimer1 function, the configuration bits, and
the value to be programmed into the PR1 register. Among other options, the configuration
bits turn on Timer 1, set the prescale value, and set Timer 1 to use the peripheral clock for
the input to the prescale divider, and sets the prescale value.
Figure 7-1 shows the relationship of the timing in the interrupt flag to the CPU crystal
frequency. Timers 2 through 5 are similar to Timer 1, with the differences being the timer
prescale options and the period register.

Figure 7-14 Figure. 1. Divider chain from the CPU crystal (oscillator) to the Timer 1 interrupt flag.

As figure 7-1 illustrates, the Timer 1 clock frequency is determined from the crystal
frequency on the chipKIT Pro MX7 board (XTAL), the PLL input divider (FPLLIDIV),
the PLL multiplier (FPLLMUL), the PLL output divider (FPLLODIV), the peripheral bus
clock divider (FPBDIV), and the Timer prescale (TCKPS). This frequency is computed
using Equation 1. The values of XTAL, FPLLMUL, FPLLDIV, FPLLODIV, and FPBDIV
are set in the common config_bits.h header file.
T1CLK=XTAL∗FPLLMUL/(FPLLIDIV∗FPLLODIV∗FPBDIV∗TCKPS) (1)
The period that sets the Timer 1 terminal count is determined by the value set into the PR1
register plus 1. The Timer 1 counter register increments each Timer 1 clock period as
determined by Equation 1 for T1CLK. Each Timer 1 count is compared to the value of the
PR1 register. When the PR1 register equals the Timer 1 count register, the timer has
reached its terminal count and initiates two actions: the Timer 1 register is reset to zero,
and secondly, the Timer 1 Interrupt Flag (T1IF) bit is set in the Interrupt Flag Status register
(IFS0).

 PIC32 Interrupts
An interrupt is a signal triggered by an event. The computer suspends what would normally
be the next instruction of a task in one part of a program and begins executing code to
complete an entirely different task.

There are four essential code elements required for a program to process interrupts using
C—the declaration of the functions that will be used to service the interrupts, the code to
initialize the resources that generate interrupts, the ISR code that will be executed in
response to an interrupt and the instructions that enable interrupts in a global sense. There
must be an ISR to handle any and all enable interrupts that includes an instruction to clear
the specific interrupt flag. Failing to clear the interrupt will cause the processor to
repeatedly execute the ISR, thus preventing the processor from executing any other
application code.

42
Functions that have been declared as an ISR cannot be called by any other C function.
There are two ways that the ISR code will be executed: either in response to the event that
sets the interrupt flag through hardware or by setting the corresponding bit in the interrupt
flag register using a software instruction. A function that is declared as an ISR cannot have
any variables passed to it (no argument list) and must return a void data type.

Normally, the code to initialize the resources that will generate the interrupt is executed
only once for a given application. In this project, two different interrupts will be generated:
Timer 1 interrupt and an I/O pin change notice interrupt. The programming requirements
for each of these two interrupts are discussed below. The two statements in example1 apply
to all interrupts and should be executed only once after all interrupts have been initialized.
In this instance, the program is using multi-vectored interrupts. Selected segments of the
code used in an application can be protected from disruption by any and all interrupts by
bracketing the code segment with the instructions INTEnalbeInterrupts(); and
INTDisableInterrupts();.

Example 1. Global Enabling of Global Interrupts

// Enable multi vectored interrupts


INTConfigureSystem(INT_SYSTEM_CONFIG_MULT_VECTOR); //done only once
INTEnableInterrupts(); //use as needed

a) Timer Interrupts
In order to set up a timer to generate interrupts, you must first initialize the timer. This is
accomplished using the OpenTimer1 instruction shown in Example 2. The next three
macro functions enable Timer 1 interrupts. The first macro instruction sets the Timer 1
interrupt priority level to 2, the second sets the Timer 1 sub priority level to 0, and the third
enables Timer 1 interrupts.

Example 2. Initializing Timer 1 Interrupts

#define T1_INTR_RATE 10000


void timer1_interrupt_initialize(void)
{
//configure Timer 1 using internal clock, 1:1 prescale,
PR1 = T1_TICK -1
OpenTimer1( (T1_ON | T1_SOURCE_INT | T1_PS_1_1), (T1_INTR_RATE - 1));
// set up the timer interrupt with a priority of 2, sub priority 0
mT1SetIntPriority(2); // Group priority range: 1 to 7
mT1SetIntSubPriority(0); // Subgroup priority range: 0 to 3
mT1IntEnable(1); // Enable T1 interrupts
// Global interrupts must enabled to complete the initialization.

43
Timer 1 interrupts can be disabled at any point in the application software by using the
instruction mT1IntEnable(0);.

Example 3 code shows how to both declare a function to be an ISR and the general format
of an ISR function. For this example, the parameter “ipl2” sets the Timer 1 interrupt level
to 2. This method of declaring an ISR eliminates the requirement of a function prototype.

Example 3 – Timer 1 ISR at interrupt level 2

void __ISR( _TIMER_1_VECTOR, ipl2) T1Interrupt(void)


{

/* User generated code to service the interrupt is inserted here


*/

mT1ClearIntFlag(); // Macro function to clear the interrupt flag

b) Change Notice Interrupts


Change notice (CN) interrupts are generated on selected enabled digital I/O pins whenever
the voltage of the pin changes, causing the processor to read a logic value that is different
from the previous reading of the PORT register. Pins designated as CN interrupt pins are
shown in Table 7-1. Only BTN1 and BTN2 on the chipKITTM Pro MX7 processor board
have the capability to generate CN interrupts. The I/O pin associated with BTN3 cannot
generate a CN interrupt.

Table 7-I. I/O pins with CN interrupt capability


CN x Port CN x Port
CN0 RC13 CN10 RG8
CN1 RC14 CN11 RG9
CN2 RB0 CN12 RB15
CN3 RB1 CN13 RD4
CN4 RB2 CN14 RD5
CN5 RB3 CN15 RD6
CN6 RB4 CN16 RD7
CN7 RB5 CN17 RF4
CN8 RG6 – BTN1 CN18 RF5
CN9 RG7 – BTN2 CN19-CN21 NA

CN interrupts can be disabled to protect segments of code using mCNIntEnable(0); to


disable the interrupts and using mCNIntEnable(1); to enable them again . Example 4
shows how to setup change notice interrupts using peripheral library code macros. In this
code, CN interrupts are turned on for CN8 and CN9, which correspond to BTN1 (RG6)
and BTN2 (RG7). The last parameter with value zero directs that internal pull-up resistors

44
be disabled, because these pins have external pull-up resistors on the chipKITTM Pro MX7
processor board. The code in example 4 enable CN interrupts at priority level 1 and sub
priority level zero.

Example 4. Initializing CHANGE NOTICE Interrupts

void cn_interrupt_initialize(void) {

// Enable CN for BTN1 and BTN2


mCNOpen((CN_ON|CN_FRZ_OFF),(CN8_ENABLE|CN9_ENABLE), 0);
ConfigIntCN(CHANGE_INT_ON | CHANGE_INT_PRI_1);

// Global interrupts must enabled to complete the initialization.


}

A single interrupt vector is used for all CN interrupts. The interrupt does not tell you if the
pin went high or low; only that the condition on one of the selected pins has changed. The
ISR code must return a type void and have no parameters passed to it. The CN interrupt
flag must be cleared prior to exiting the ISR using the instructions mCNClearIntFlag();.

Example 5. Change Notice Interrupt Service Routine

void __ISR(__CHANGE_NOTICE_VECTOR, ipl1) CNIntHandler(void)


{
/* User ISR code inserted here */

/* Required to clear the interrupt flag in the ISR */


mCNClearIntFlag(); // Macro function
asm ("nop"); // Recommended in some PIC32 literature
}

Project Task
This project implements a system that runs entirely using foreground processes. The
Timer 1 is used to set the interrupt flag once each millisecond. The PIC32 change notice
interrupt generates an interrupt when a button is pressed or released.
As specified in Table 7-2, we will use two buttons (BTN1 & BTN2). If BTN1 is selected
then the LED will flash as a counter from 0 to 15. But if BTN2 is selected the LED will
flash on and off. (Note: you need to use a delay between each toggle).

Table 7- 2. Button-controlled
Button State
BTN1 Counter
BTN2 Flashing

45
The project consists of writing a program that meets the specifications listed below:
1. Functionality for main function.
 Calls system_init function (see step 2).
 Continuously executes the while(1); statement.
2. Create a system_init function
 Initialize the processor board using the function PIC32_Setup();
 Initialize Timer 1 to generate an interrupt once each ms . Set the group
priority for level 2 and the subgroup level for 0.
 Initialize the PIC32MX7 system for change notice detection. Set change
notice interrupts to detect activity on BTN1 andBTN2 only, the group
priority level 1 and the subgroup level 0.
 Set the system for multiple vectored interrupts.
3. Detect button uses the change-notice interrupt implementation.

4. Create a delay function using Timer 1

46
Experiment #8
Controlling a DC Motor

Objective:
The purpose of this experiment is to learn how to generate a proportional output using the
output compare resource on the PIC32MX processor so that you can implement digital-to-
analog conversion with pulse width modulation (PWM). The proportional output will be
used to control the speed of a DC motor.

Equipment List
1. chipKITTM Pro MX7 processor board with USB cable
2. Microchip MPLAB ® X IDE
3. MPLAB ® XC32++ Compiler
4. Digilent DC Motor
5. Digilent PmodDHB1™

Overview
The information Digital I/O works well for generating and detecting discrete events. But
the real world is continuous; thus, for microprocessors to have value, they need to have the
capability to input and output analog signals. A digital-to-analog converter (DAC) converts
a digital, or binary, value to an analog voltage. An analog-to-digital converter (ADC)
converts a voltage in a specified range to a binary value that represents the magnitude of
the signal.

 Pulse Width Modulation


There are many different ways to control the speed of motors but one very simple and easy
way is to use Pulse Width Modulation. As its name suggests, pulse width modulation speed
control works by driving the motor with a series of “ON-OFF” pulses and varying the duty
cycle, the fraction of time that the output voltage is “ON” compared to when it is “OFF”,
of the pulses while keeping the frequency constant. The power applied to the motor can be
controlled by varying the width of these applied pulses and thereby varying the average
DC voltage applied to the motors terminals. By changing or modulating the timing of these
pulses the speed of the motor can be controlled, i.e., the longer the pulse is “ON”, the faster
the motor will rotate and likewise, the shorter the pulse is “ON” the slower the motor will
rotate.

47
In other words, the wider the pulse width, the more average voltage applied to the motor
terminals, the stronger the magnetic flux inside the armature windings and the faster the
motor will rotate and this is shown below.

Figure 8-15 Pulse Width Modulated Waveform

The DC motor driver circuit provided by the PmodDHB1 allows control of the motor
speed by connecting the Output Enable pin to the PIC32 PWM output as well as motor
direction control by connection to another PIC32 I/O pin.

The PWM pulse-width is controlled by the PIC32MX processor output compare (OC)
module. For this experiment, we will use Timer 2 to generate the PWM cycle frequency.
The DC motor is connected to JD on the chipKITTM Pro MX7 processor board. This
connection provides access to output compare channel 2 (OC2) that we will use to
generate the PWM output.
There are two key parameters that must be specified. The PWM_ CYCLE_ FREQUENCY
is the inverse of the PWM cycle period. The value written to the Timer 2 period register
value, PR2, determines the PWM_CYCLE_FREQUENCY as shown in Eq. (1) and (2).
PWM_CYCLE_COUNT = PBCLK / (T2_PRESCALE * PWM_CYCLE_FREQUENCY) (1)

PR2_VALUE = PWM_CYCLE_COUNT – 1 (2)

The second parameter is PWM_DUTY_CYCLE that is a value between 0% and 100%


multiplied by the Timer 2 period register, PR2, plus 1 as expressed by Eq. (3). The
PWM_DUTY_CYCLE value is written to the output compare register, OC2RS and will
take effect the next time the Timer 2 resets to zero. The output will be constantly high if
the value written to the OC2RS register is greater than the value in the PR2 register.
OC2RS_VALUE = (PWM_DUTY_CYCLE * (PR2 + 1) / 100) - 1 (3)

For example, to generate a 30% PWM duty cycle output when the Timer 2 period register,
PR2, is set to 999, then the value 299 must be written to the OC2RS register.
Appendix D provides the pin connections between the Pmod DHB1 and the chipKITTM
Pro MX7 processor board. The EN (enable) pin is the PWM input to the Pmod DHB1
motor driver circuit. Whenever the EN pin is high, power is applied to the motor. The
DIR pin controls the direction of the motor and will be set to zero for this experiment.

48
 Programming the Timer Output Compare for PWM Operation
The PWM output using OC2 can be set up and controlled using four XC32 peripheral
library functions. The process is defined by the following steps:

 mOCxClearIntFlag(); // Clear output compare interrupt flag.

 OpenTimer2(Set_up_bits, PR2_value); where (PR2_value + 1) is the period


register value computed for the PWM cycle frequency. Initialize Timer 2 to
generate an interrupt at the rate of the PWM cycle. In the Timer 2 ISR, toggle the
LED1 bit for timing instrumentation.

 OpenOCx (OC_configure_bits, nOCxRS, nOCxR); where nOCxRS is the initial


value written to the OCxRS register and nOCxR is the initial value written to the
OCxR register. “x” designates the specific OC register being configured in the
range between 1 through 5.
o OC_configure_bits (bits are inclusive):
OC_ON // Enables the Output compare processor resource
OC_TIMER_MODE16 // Timer uses 16 bit mode
OC_TIMER2_SRC // Selects Timer 2 as input timer

o nOC2RS—this is a constant or a variable that specifies the initial PWM


compare value. This is set to the initial PWM duty cycle setting.
o nOC2R—this is a constant or a variable that specifies the next PWM compare
value. This is set to the same value as nOC2RS.
o The range of values for nOC2RS and nOC2R is 0 to PR2-1. PR2 is specified in
step 2. If these parameters are set to a value equal to or greater than the PRx,
the PWM output will be set to a constant high.

 After initialization, the last function, “SetDCOC2PWM(nOC2RS)”, can be used


to change the PWM duty cycle at any time while code is executing. The value of
nOC2RS is in the range of zero to PR2-1. PR2 was specified in step 2.

49
Project Tasks
The objective of this experiment is to implement an open-loop motor speed control. For
this experiment, the motor speed control will be set

 First, only to start and stop the DC motor (ON 5%, OFF 95%).
 Then, to the four fixed PWM duty cycle values shown in Table 8-1.

These duty cycle values are selected using the chipKITTM Pro MX7 processor board
BTN1 and BTN2 pushbuttons. Specifically, the project tasks are as follows:
 Set the PWM output as a function of the states of buttons BTN1 and BTN2, as
specified in Table 8-1.

 Detect button uses the change-notice interrupt similar to the experiment 6


implementation. The CN interrupt is to use a 20 ms software delay for switch
debouncing.

 The following are the required functions and descriptions of operations:


a) “Main”.
 Calls application initialization.
 Configure chipKITTM Pro MX7 processor board BTN1 and
BTN2 as inputs.

 Configure Timer 2 to generate an interrupt each millisecond.

 Configure the PWM output channel as follows:


o Use output compare 2 (OC2).
o Uses Timer 2 for the time base for the output
compare.
o PWM cycle frequency of 1000 Hz.

 Initialize a CN interrupt for button status detection at priority


1 and the sub priority level 0.

 Executes a while(1); loop that does nothing.

b) Button Detect ISR (refer to Experiment 7).


 Sets LED2 on entry and clears LED2 on exit.
 Removes button contact bounce with 20ms software delay.
 Reads button state.
 Decodes buttons and sets PWM in accordance with Table 8-1.
 Sets the motor PWM.
 Clears CN interrupt flag.

50
c) Timer2 ISR.
 Toggles LED1.
 Clears T2 interrupt flag.

Table 8-1. Button controlled PWM.


Tasks BTN1 BTN2 PWM
1 ON OFF Stop -- 5%
OFF ON Start -- 95%

2 OFF OFF 40%


ON OFF 65%
OFF ON 80%
ON ON 95%

51
Experiment #9
Frequency Measurement Using Input Capture

Objective:
The purpose of this experiment is to use the PIC32 input capture to measure frequency.
Using such a frequency measurement will allow us to determine the speed of a DC motor.

Equipment List
1. chipKITTM Pro MX7 processor board with USB cable
2. Microchip MPLAB ® X IDE
3. MPLAB ® XC32++ Compiler
4. PC-based terminal emulations (HyperTerminal®)
5. Digilent DC Motor
6. Digilent PmodDHB1™

Overview
In the previous experiment (Controlling a DC Motor) we implemented open loop speed
control of a DC motor. This control approach uses the assumption that the speed of the
motor is proportional to the applied voltage. This experiment is designed to test the linearity
of open loop speed control by providing a tachometer to measure the rotor shaft speed.
Considering that the motor speed is controlled by the average applied voltage, the
tachometer represents a voltage to frequency converter. The DC motor used on the Digilent
chipKitTM Pro MX7 processor board has two Hall Effect sensors3 that provide a pulse each
time the DC motor shaft makes a complete revolution.
The speed of the motor will be measured by determining the frequency of the digital pulse
wave generated by the Hall Effect sensor.

Frequency Measurement
There are two methods of measuring the frequency of the tachometer. The number of pulses
can be counted per unit time or the inverse of the period between two successive pulse
transitions can be computed. Measuring frequency by counting pulses over short intervals

3
A Hall Effect sensor is a transducer that varies its output voltage in response to a magnetic field.

52
is more accurate for signals when the frequency of the signal being measured is high
relative to the observation interval. This results in many hundreds or even thousands of
cycles being counted during the measurement interval thus providing a high frequency
measurement resolution.
Measuring the period is generally more accurate for relatively low frequency signals. The
high resolution is provided by the number of timer counts between input signal transitions.
The measurement period now depends of the frequency of the input signal and, for very
low frequency signals, may result in excessively long delays between measurement
updates.
For this experiment, you will measure the speed of the motor rotor shaft by computing the
period between two successive pulses of the motor tachometer by capturing a timer count
at each transition. In order to achieve the measurement with relatively good accuracy, the
period must be measured with a high resolution. This requires that the timer be counting at
a much higher rate than the period of the of the tachometer signal. The accuracy of the
frequency is preserved by inverting the period using floating point variables or fixed point
math divide algorithms.
The speed of the motor is proportional to the frequency of the signal generated by the motor
tachometer as expressed by Eq.1. The motor that we are using has a reduction gear with a
ratio of 53:1. Using a 10V motor supply, the maximum motor speed will be approximately
525 revolutions per second (RPS) or 594 RPM on the output of the gear head. Due to
motor power limitations and gear head friction, the minimum motor speed is approximately
79.5 RPS which is equivalent to 90 RPM as measured on the gear-head output shaft.

RPS = ((SAMPLES per HZ) * SAMPLES) / Time accumulator (1)

Timer Setup
For this experiment, we will use two PIC32 timers: one for generating the PWM output
that controls the motor speed (Timer 2), and one that will be used to capture the time when
the tachometer signal transitions from low to high or high to low (Timer 3). The reason for
using two timers is that the period register of the two timers are set to different values in
order to achieve different design objectives. The period register of the timer used for
generating the PWM signal is set to give a particular PWM cycle frequency. The period
register of the timer used for measuring the period of the tachometer signal is set to the
maximum value to allow the period measurement of an input signal over a wider range of
frequencies. The lower the frequency on the input signal, the more timer counts that will
be measured. The period measurement will be incorrect if the timer resets after reaching
the terminal count more than once between input signal transitions. Hence, the period
register for the timer that is used for timer capture will be set to its maximum value, 65536.

53
Timer 3 will be used exclusively for a 16 bit input timer capture. Configure Timer 3 to use
the PBCLK and a pre-scale value of 256. Set Timer 3 PR3 register to 0xFFFF for maximum
interval.
OpenTimer3(T3_ON | T3_PS_1_256 | T3_SOURCE_INT, 0xFFFF);

Timer Capture Peripheral


The input capture module is used to capture a timer value from one of two selectable time
bases upon an event on an input pin. Common applications of the input capture peripheral
are for tachometers and frequency meters. This experiment measures the speed of the DC
motor rotation by measuring the period of a rectangular wave produced one by the Hall
Effect devices installed in the DC motor. Since the Hall Effect outputs do not produce a
perfect square wave, the period of the signal will be determined by the time between two
successive signal rising edges.
The PIC32 uses up to 5 dedicated pins (IC1 through IC5) to trigger a timer capture
operation.
Interrupts can be generated after 1, 2, 3 or 4 capture events. A four-deep first-in first-out
(FIFO) buffer allows the captured times associated with the succession of events. A capture
event is defined by the writing of a timer value into the FIFO. As events are recorded into
the FIFO buffer, a counter records the number of entrees. The number of capture events
required to set an IC interrupt flag that triggers an interrupt event is set by the Open Capture
configuration. When all of the events have been read from the FIFO buffer, the capture
count is cleared. Input capture interrupts persist so long as the condition that caused them
persists. In addition, the interrupt will occur again immediately if the condition is not
cleared by reading all of the captured events out of the FIFO buffer. It is highly
recommended that the interrupt capture flag be reset at the conclusion of the input capture
ISR.
 The following steps will allow the input capture to be setup to use Timer 3 and
generate an interrupt when the timer value is captured by a rising edge of the IC5
input pin.

1. Set motor Hall Effect output SB (RD12 - IC5) as input.

2. Clear pending input capture interrupts


a. mIC5ClearIntFlag();

3. Use input capture channel 5 for the following options. An interrupt


will be generated on each positive transition of the input signal.

void OpenCapture5(c1 | c2 | c3 | c4 | c5 | c6 | c7);


a. c1 = IC_ON // Enable input capture
b. c2 = IC_CAP_16BIT // Capture a 16 bit clock
c. c3 = IC_IDLE_STOP // Stop input capture during debug

54
d. c4 = IC_FEDGE_FALL // Initial capture on negative
transition
e. c5 = IC_TIMER3_SRC //Use Timer 3 as time to capture
f. c6 = IC_INT_1CAPTURE // Generate interrupt on each
capture
g. c7 = IC_EVERY_EDGE // Capture time on every edge

4. Configure the Input Capture interrupt as follows


a. ConfigIntCapture5(ic1 | ic2 | ic3);
i. ic1 = IC_INT_ON // Enable input capture interrupt
ii. ic2 = IC_INT_PRIOR_3 // Set priority for level 3
iii. ic3 = IC_INT_SUB_PRIOR_0 // Set sub priority for
level 0

Project Tasks
The objective for this experiment is to implement a motor speed tachometer by measuring
the frequency of the motor shaft sensor.

1. Develop code that generates the PWM signal as illustrated in table 9-1
 Initialized the PWM duty cycle to 33%

2. Develop code that detects button operations


 Set LED1 at the start of a CN ISR and clear LED1 at the end of the CN
ISR

3. Develop code that sets up Timer 3 for timer capture


 Toggle LED2 each input capture interrupt

4. Write and verify the C code to complete the button control and to display the
motor speed measurement (RPS) on the screen.

Table 9-1. Motor Tachometer frequency for button controlled PWM duty cycle

BTN2 BTN1 PWM RPS


OFF OFF 33%
OFF ON 65%
ON OFF 80%
ON ON 95%

55
Experiment #10
Controlling a Stepper Motor

Objective:
The purpose of this experiment is to analyze the direct driving of the stepper motor using
the Cerebot MX7cK processor board.

Equipment List
1. chipKITTM Pro MX7 processor board with USB cable
2. Microchip MPLAB ® X IDE
3. MPLAB ® XC32++ Compiler
4. PmodSTEP™
5. Stepper Motor (5V-12V, 25 Ω, unipolar or bi-polar)

Overview
The stepper motor consists of two sets of field windings positioned around a permanent
magnet rotor, as illustrated in Figure 10-1.

Figure 10-1. Photograph field coils and rotor of a stepper motor

The combinations of voltages applied to the four control terminals of the field windings
control the magnitude and direction of the current through the windings, as illustrated in
Figure 10-2. The current through the windings create an electromagnet. The motor shaft
rotates to a position that minimizes the reluctance path between the field winding
electromagnet’s north and south poles of the rotor.

56
Field Winding
Voltage
Terminals Field Windings
Field Winding
Current

Field Winding
Schematic Permanent
Magnet Rotor

Figure 10- 2- Bipolar Stepper motor diagram

Considering the combinations of voltages on the winding terminals as possible control


states, there are only eight states that produce current in the field windings, as shown in
Table 10-1 below. In order to move the rotator shaft from one stable position to the
physically adjacent stable position, the control voltages must switch to one of four out of
the eight possible combinations of voltages. The action of moving from one stable position
to an adjacent stable position is referred to as either a full-step or a half-step. Half-step
increments are half the angular rotation of full-steps. Repeating a sequence of full- or half-
step movements at a uniform rate will cause the rotator shaft to appear to rotate at a constant
speed in discrete steps.

Table 10-1. Stepper motor control codes.


Step Control Winding Voltage
Step Hex Code “1a” “1b” “2a” “2b”
Name
S0_5 0x0A H L H L
S1 0x08 H L L L
S1_5 0x09 H L L H
S2 0x01 L L L H
S2_5 0x05 L H L H
S3 0x04 L H L L
S3_5 0x06 L H H L
S0 0x02 L L H L

The stepper motors used in this experiment are designed to require 100 full steps for the
rotor shaft to complete one full revolution, or 3.6 degrees per step. 200 half-steps are
required to make one revolution, or 1.8 degrees per half-step.

57
The PmodSTEP driver module was designed to use I/O PORT B pins 7 through 10 that are
assigned designations SM1 through SM4 to control the voltages on the four stepper motor
field windings. (See Appendix E for PmodSTEP connection details.)

Project Task
Write a program to control the direction and step-mode of a stepper motor as shown in
Table 10-2.

Table 10-2 - Stepper motor control table


Inputs Control Modes
BTN2 BTN1 DIRECTION STEP MODE
Off Off CW FS
Off On CW HS
On Off CCW HS
On On CCW FS

58
Design Challenge #1
Garage Door Control

Objective:
In this experiment you need to create an embedded design for a garage door control using
the Cerebot MX7cK processor board.
Functional Specifications:

1. All buttons function as momentary contact push buttons.


1. BTN1 – Up
2. BTN2 – Down
3. BTN1 and BTN2 simultaneously pressed – SAFETY BEAM (LED1)
4. BTN3 – OPERATE BUTTON
2. LED Assignments
1. LEDA – Motor running up – door is opening
2. LEDB – Motor running down – door is closing
3. LEDC – Door is fully open
4. LEDD – Door is fully closed
3. If the door is closed (LEDD is on), pressing the button (BTN1) causes the door to
begin opening causing LEDA to turn on and LEDD to turn off
4. If the door reaches the top while opening, the motor will stop (LEDA off) and door
fully open indication, LEDC, is turned on.
5. If the door is open (LEDC on), pressing the button (BTN2) causes the door to begin
closing causing LEDB to turn on and LEDC to turn off.
6. If the door reaches the bottom while closing, the motor will stop causing LEDD to
turn on and LEDB to turn off.
7. If the electric eye detects that the light beam has been interrupted (LED1) while the
door is closing (LEDB on) the door will reverse direction and begin opening by
turning LEDA on.
8. If the light beam is interrupted (LED1) while the door is opening then the door
continues opening.
9. Pressing the button (BTN3) while the door is opening causes the door to stop
(LEDA and LEDB off). Pressing the button again (BTN3) causes the door to begin
closing (LEDB on).
10. Pressing the button (BTN3) while the door is closing causes the door to stop (LEDA
and LEDB off). Pressing the button again (BTN3) causes the door to begin opening
(LEDA on).
11. 50ms switch contact debouncing is required for all inputs.

59
Design Challenge #2
Large 4-bit OLED Display

Objective:
This assignment is the embedded design for a parallel controlled, 4-bit gray scale OLED
display using the chipKIT™Pro MX7 processor board.

Operations Requirements:
 The program should be able to write a character or a text in any location on the
screen.
 Set the character cursor position to the specified location
 Gets the current cursor position.
 Writes the desired character to the display buffer
 Write the desired null terminated character string to the display buffer

 The program should be able to display a shape on the screen.


 Draw a shape (rectangle/ Circle/Square…etc.) bounded
 Fill a shape bounded
 Put the specified bitmap into the display
 Hint: you may use the Fast LCD program

60
Appendix A: Connector Descriptions and Jumper Settings

Label Function

JA-JF Pmod Connectors


These connectors provide access to the I/O pins on the PIC32MX795
microcontroller. Digilent Pmod peripheral modules can be attached to
these connectors. These connectors can be used for general access to
I/O pins on the PIC32MX795 microcontroller.

JPA – JPF Pmod header power select


Any of the Pmod connectors can provide either regulated or
unregulated power. To use regulated power, place the jumper block
over the center pin and the pin marked 3V3. To use unregulated power,
place the jumper block over the center pin and the pin marked 5V0.

J1 USB Serial converter auxiliary signals


This connector can be used to access the auxiliary RS232 handshaking
signals not used on the Cerebot MX4cK board.

J2 USB Serial converter (UART) connector


This USB micro-AB connector is used to connect the FT232R serial
converter to a USB port on the user PC.

J3 Power supply source select


This jumper is used to select the source of main board power.
Place the shorting block in the, “USB” position to have the board
powered from the USB device connector, J19.
Place the shorting block in the, “EXT” position to have the board
powered from one of the external power connectors, J17 or J18.
Place the shorting block in the, “DBG” position to have the board
powered from the debug USB connector, J15.
Place the shorting block in the “UART” position to have the board
powered from the USB serial converter connector, J2

J7 I2C1 daisy chain connector


This connector provides access to the I2C signals, power and ground
for I2C1.

J8 I2C2 daisy chain connector


This connector provides access to the I2C signals, power and ground
for I2C2.

J9 CAN #1 Connector
This connector is used to access the signals for CAN #1.

61
CAN #2 Connector
J10 This connector is used to access the signals for CAN #2.

J11 Ethernet Connector


This connector provides access to the 10/100 Ethernet port.

J12-J14 Do Not Use.

J15 Debug USB Connector


This connector is used to connect the on-board programming and debug
circuit to the PC for use with the MPLAB IDE.

J17 External Power Connector


This is a 2.5mm x 5.5mm, center positive, coax power connector used
to provide external power to the board. The optional Digilent 5V
Switching Power Supply is connected here.

J18 External Power Connector


This is a screw terminal connector used to provide external power to
the board. Be sure to observe proper polarity (marked near the
connector) when providing power via this connector, or damage to the
board and/or connected devices may result.

J19 USB Device / OTG Connector


This is a USB micro-AB connector. It is used when using the
PIC32MX795 microcontroller to implement a USB device or OTG
Host/Device.

J20 USB Host Connector


This is a standard sized USB type A connector. This connector is used
to connect USB devices to the board when using the PIC32MX795
microcontroller to implement an embedded USB host.

JP1 & JP2 CAN or Pmod Select


These jumpers select microcontroller signals RF12 and RF13 for use
with CAN #1 or Pmod connector JF. Place these jumpers in the CAN
position to use CAN #1. Place the jumpers in the PMOD position to use
then with Pmod connector JF.

JP3 & JP4 Pull-up enable for I2C1


These two jumpers are used to enable/disable the pull-up resistors on
I2C1. Insert shorting blocks on these two jumpers to enable the pull-up
resistors. Remove the shorting blocks to disable the pull-up resistors.

62
Only a single device on the I2C bus should have the pull-up resistors
enabled.

JP5 CAN #1 Termination


This jumper is used to enable/disable the 120 ohm termination resistor
for CAN #1. Insert the shorting block to enable the termination resistor,
remove it to disable the termination resistor.

JP6 CAN #1 5V0 Enable


This jumper is used to enable/disable providing 5V to the CAN #1
connector. Insert the shorting block to connect the board 5V0 supply to
pins 9 & 10 of CAN #1 connector. Remove the shorting block to
disconnect the 5V0 supply.

JP7 CAN #2 Termination


This jumper is used to enable/disable the 120 ohm termination resistor
for CAN #2. Insert the shorting block to enable the termination resistor,
remove it to disable the termination resistor.

JP8 CAN #1 5V0 Enable


This jumper is used to enable/disable providing 5V to the CAN #1
connector. Insert the shorting block to connect the board 5V0 supply to
pins 9 & 10 of CAN #1 connector. Remove the shorting block to
disconnect the 5V0 supply.

JP9 Do Not Use

JP10 USB host power select


This jumper is used to select which host connector is powered when
host power is enabled. Place the shorting block in the “MICRO”
position to supply power to the USB micro-AB OTG Connector, J19.
Place the shorting block in the “A” position to supply power to the USB
type A Host Connector, J20.

JP11 USB Serial converter reset disconnect


This is used to connect/disconnect the USB serial converter reset circuit
from the PIC32 MCLR pin. The shorting block must be in place on this
jumper when using the chipKIT MPIDE development tools. Remove
the shorting block if the USB serial converter is interfering with proper
operation of the licensed debugger circuit.

JP17 Do Not Use

63
Appendix B: Example of Configuration Values

The following example illustrates setting the configuration values in the PIC32
microcontroller on the Cerebot MX7cK. The microcontroller configuration should be done
in a single source file in the project, and is typically done in the ‘main’ project source file.
This example sets all configuration values to valid values for the Cerebot MX7cK board.
It sets the system clock for processor operation at 80Mhz, and the peripheral bus at 10Mhz.

/* ------------------------------------------------------------ */
/* PIC32 Configuration Settings */
/* ------------------------------------------------------------ */
/* Oscillator Settings
*/
#pragma config FNOSC = PRIPLL // Oscillator selection
#pragma config POSCMOD = EC // Primary oscillator mode
#pragma config FPLLIDIV = DIV_2 // PLL input divider
#pragma config FPLLMUL = MUL_20 // PLL multiplier
#pragma config FPLLODIV = DIV_1 // PLL output divider
#pragma config FPBDIV = DIV_8 // Peripheral bus clock divider
#pragma config FSOSCEN = OFF // Secondary oscillator enable
/* Clock control settings
*/
#pragma config IESO = OFF // Internal/external clock switchover
#pragma config FCKSM = CSDCMD // Clock switching (CSx)/Clock monitor (CMx)
#pragma config OSCIOFNC = OFF // Clock output on OSCO pin enable
/* USB Settings
*/
#pragma config UPLLEN = ON // USB PLL enable
#pragma config UPLLIDIV = DIV_2 // USB PLL input divider
#pragma config FVBUSONIO = OFF // VBUS pin control
#pragma config FUSBIDIO = OFF // USBID pin control
/* Other Peripheral Device settings
*/
#pragma config FWDTEN = OFF // Watchdog timer enable
#pragma config WDTPS = PS1024 // Watchdog timer post-scaler
#pragma config FSRSSEL = PRIORITY_7 // SRS interrupt priority
#pragma config FCANIO = OFF // Standard/alternate CAN pin select
#pragma config FETHIO = ON // Standard/alternate ETH pin select
#pragma config FMIIEN = OFF // MII/RMII select (OFF=RMII)
/* Code Protection settings
*/
#pragma config CP = OFF // Code protection
#pragma config BWP = OFF // Boot flash write protect
#pragma config PWP = OFF // Program flash write protect
/* Debug settings
*/
#pragma config ICESEL = ICS_PGx1 // ICE pin selection

64
Appendix C: PIC – UART C Code

/* File name: comm.c*/


#include <plib.h>
#include "comm.h"
#include "pic32mx.h" // has info regarding the PB clock

void initialize_uart1(unsigned int bit_rate, int parity)


{
unsigned int brg;

brg = (unsigned short)(( (float)FPB / ( (float)4 * (float) bit_rate))-


(float)0.5); // provides rounding for greatest accuracy
switch(parity)
{
case NO_PARITY:
OpenUART1( (UART_EN | UART_BRGH_FOUR | UART_NO_PAR_8BIT),
(UART_RX_ENABLE | UART_TX_ENABLE) , brg );
break;
case ODD_PARITY:
OpenUART1( (UART_EN | UART_BRGH_FOUR | UART_ODD_PAR_8BIT),
(UART_RX_ENABLE | UART_TX_ENABLE) , BRG );
break;
case EVEN_PARITY:
OpenUART1( (UART_EN | UART_BRGH_FOUR | UART_EVEN_PAR_8BIT),
(UART_RX_ENABLE | UART_TX_ENABLE) , BRG );
break;
}
}
Appendix D: Motor Controller Wiring Diagram

Figure D1. Motor connection diagram

65
Appendix E: PmodSTEP

LEDD
LEDC
LEDB
LEDA

Stepper Motor
Bipolar
Cerebot
JA

GND
SM3 / LEDG
SM4 / LEDH

SM1 / LEDE
SM2 / LEDF

Figure E16- PmodSTEP parts layout.

Table E1- LED - Pmod Port JA Pin and PIC32MX7 I/O Port B Assignments

LED JA Pin # PIC32MX7 Port B Pin #


LED A 1 RB2
LED B 2 RB3
LED C 3 RB4
LED D 4 RB6
LED E / SM1 7 RB7 (winding 2b)
LED F / SM2 8 RB8 (winding 2a)
LED G / SM3 9 RB9 (winding 1b)
LED H / SM4 10 RB10 (winding 1a)

66

You might also like