### Advanced Microcontrollers: Using chipKIT Pro MX7

• Project 0: MPLAB® X Integrated Development Environment

#### Using chipKIT™ Pro and M...

This project introduces you to the synthesis and analysis tools for producing microprocessor C code using the MPLAB® X integrated development environment (IDE) on the chipKIT™ Pro MX7 processor board.

• Project 1: chipKIT™ Pro and I/O Control

#### Digital Input and Output

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

• Project 2: chipKIT™ Pro and Delays

#### Software Timing Delays

The purpose of this project is to investigate methods of creating software time delays to pace processor operations.

• Project 3: Using chipKIT™ Pro with Stepper Motors

#### Software-Based Finite St...

The purpose of this project is to investigate the application of software-based state machines to controlling the speed, direction of rotation, and operational mode of stepper motors.

• Project 4: Using chipKIT™ Pro with Stepper Motors

#### PIC™32 Timers

The purpose of this project 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.

• Project 5: chipKIT™ Pro and Interrupts

#### Process Speed Controls U...

Explore detecting events using interrupts or by using preemption that implements a nested interrupt management scheme.

• Project 6: Using chipKIT™ Pro to Control LCDs

#### Handshaking and LCD Cont...

Investigate concepts involving parallel communications and handshaking.

• Project 7: chipKIT™ Pro and Serial Communication

#### Asynchronous Serial Comm...

Learn about asynchronous communications and 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.

• Project 8: chipKIT™ Pro and Serial Communications

#### Synchronous I2C Serial C...

Investigate concepts involving synchronous communications using a basic master-slave multi-drop network communications and use the I2C protocol to communicate with the 24LC256 I2C™ CMOS Serial EEPROM.

• Project 8a: chipKIT™ Pro and Serial Communications

#### Synchronous SPI Serial C...

Investigate synchronous communications with the SPI master-slave serial bus

• Project 9: Controlling a DC Motor

#### PWM Using Timer Compare

Generate a proportional output using the output compare resource on the PIC®32MX processor to implement digital-to-analog conversion with pulse width modulation (PWM), thus controlling the speed of a...

• Project 10: Using chipKIT™ Pro and DC Motors

#### Frequency Measurement Us...

Use the PIC™ 32 input capture to measure frequency to determine the speed of a DC motor.

Project 0: MPLAB® X Integrated Development Environment

#### Using chipKIT™ Pro and MPLAB X

This project introduces you to the synthesis and analysis tools for producing microprocessor C code using the MPLAB® X integrated development environment (IDE) on the chipKIT™ Pro MX7 processor board.

11.3K
×
Project 1: chipKIT™ Pro and I/O Control

#### Digital Input and Output

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

8.74K
×
Project 2: chipKIT™ Pro and Delays

#### Software Timing Delays

The purpose of this project is to investigate methods of creating software time delays to pace processor operations.

6.36K
×
Project 3: Using chipKIT™ Pro with Stepper Motors

#### Software-Based Finite State Machines

The purpose of this project is to investigate the application of software-based state machines to controlling the speed, direction of rotation, and operational mode of stepper motors.

6.30K
×
Project 4: Using chipKIT™ Pro with Stepper Motors

#### PIC™32 Timers

The purpose of this project 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.

5.23K
×
Project 5: chipKIT™ Pro and Interrupts

#### Process Speed Controls Using Interrupts

Explore detecting events using interrupts or by using preemption that implements a nested interrupt management scheme.

7.87K
×
Project 6: Using chipKIT™ Pro to Control LCDs

#### Handshaking and LCD Control

Investigate concepts involving parallel communications and handshaking.

7.52K
×
Project 7: chipKIT™ Pro and Serial Communication

#### Asynchronous Serial Communications

Learn about asynchronous communications and 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.

7.17K
×
Project 8: chipKIT™ Pro and Serial Communications

#### Synchronous I2C Serial Communications

Investigate concepts involving synchronous communications using a basic master-slave multi-drop network communications and use the I2C protocol to communicate with the 24LC256 I2C™ CMOS Serial EEPROM.

7.59K
×
Project 8a: chipKIT™ Pro and Serial Communications

#### Synchronous SPI Serial Communications

Investigate synchronous communications with the SPI master-slave serial bus

5.56K
×
Project 9: Controlling a DC Motor

#### PWM Using Timer Compare

Generate a proportional output using the output compare resource on the PIC®32MX processor to implement digital-to-analog conversion with pulse width modulation (PWM), thus controlling the speed of a DC motor.

10.2K
×
Project 10: Using chipKIT™ Pro and DC Motors

#### Frequency Measurement Using Input Capture

Use the PIC™ 32 input capture to measure frequency to determine the speed of a DC motor.

7.30K
×

# Using MPLAB® X Integrated Development Environment and chipKIT™Pro

## Introduction

The purpose of this project is to learn how to generate a proportional output using the output compare resource on the PIC™32MX 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.

## Inventory:

Qty Description
1 Digilent chipKit™ Pro MX7 processor board with USB cable
1 Digilent PmodCLP™ Parallel Character LCD
1 Digilent PmodHB5™
1 Digilent DC Motor
1 Oscilloscope / Logic analyzer (Digilent Analog Discovery™)
1 MPLAB® XC32 Compiler (documentation support)

## Fundamentals of Digital-to-Analog (D2A) Conversion

The informational 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. Project 9 investigates one method in which a microprocessor can generate a varying amplitude signal. Project 10 investigates a method for sensing a time-varying signal. 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.

There are several different technologies used to implement DACs. To say that a continuous time-varying signal can be generated from a sequence of binary values is an overstatement. In reality, the DAC can only output discrete voltage levels over a limited range of voltages. Three parameters define a DAC’s operating characteristics: the resolution, the dynamic range, and the DAC order. The DAC resolution is defined as the change in output level for a change in the least significant bit of the binary input. The dynamic range of the DAC is defined by the maximum output level minus the minimum output level. Bipolar DACs can output both positive and negative voltages. Unipolar DACs output either positive or negative voltages. The order of a DAC is defined by the log base 2 of the number of discrete values that the DAC can output. For example, a 10-bit DAC can output 1024 discrete values.

The DAC performance is measured with the following parameters: conversion speed, differential nonlinearity, integral nonlinearity, total harmonic distortion plus noise, zero offset, monotonicity, and missing codes. A thorough discussion on DAC performance is beyond the scope of this project, but better performance obviously comes at a higher cost.

#### PWM as an D2A Converter

In communications theory, modulation is used to translate the frequency spectrum of information signals to a frequency spectrum center around a higher, fixed frequency. The purpose of modulation is to allow multiple information signals to be simultaneously communicated through a single medium such as wire, fiber optic cable, or through the air as electromagnetic or acoustic waves using frequency division multiplexing. When discussing modulation, two terms frequently arise: the information or modulating signal and the carrier signal. The carrier is a constant higher frequency that is modulated or modified by the information or modulating signal. After transmission, the information signal must be recovered or extracted from the carrier signal using a demodulator.

#### PMW Modulation

Pulse-width modulation (PWM) (also referred to as pulse duration modulation, or PDM) is commonly used as a method of generating a signal with a microprocessor for two reasons—the PWM signal is easily generated using processor timers and digital comparators, and the PWM signal easily demodulated with little or no external circuitry. Readers who are unfamiliar with PWM concepts should look at one of the many web-based tutorials. The bottom trace in Fig. 1 is an example of a PWM signal, showing that it is a constant period rectangular wave that has varying high and low periods. The inverse of the constant PWM period is called the PWM cycle frequency, or the carrier frequency. The PWM duty cycle is the ratio of high output to total PWM period and is expressed as a percentage. Thus, a 50% PWM duty cycle results in a square wave.

If the modulating signal is a constant, the demodulated PWM signal is a DC level. When working with bipolar modulating signals, the signal level must be offset so that the zero level generates a PWM output with a 50% duty cycle. The offset must be removed by the demodulator circuit to recover the bipolar signal. Demodulation circuits are discussed in paragraphs below.

As illustrated in Fig. 1, the PWM carrier frequency signal is modulated by changing the duty cycle of the carrier rectangular wave in proportion to the amplitude to the information signal. The top trace in Fig. 1 shows the information, or modulating sine wave, and the sawtooth wave used by the modulator. When the modulating signal has amplitude that is higher than the sawtooth signal, the PWM signal is high, as shown in the bottom trace of Fig. 1. Conversely, the PWM output is low whenever the sawtooth signal is higher than the information signal.

Microprocessors can generate a PWM output signal using a counter and a digital comparator. The counter synthesizes the sawtooth wave and a data stream synthesizes the modulating wave. Many microprocessors, including the PIC32, contain dedicated hardware that can generate a PWM output with minimum software support.

As described above, PWM is a modulation scheme where the information signal is used to modulate a carrier signal. The result of modulation translates or shifts the information signal frequency spectrum to a spectrum that centered on the PWM cycle frequency. The PWM signal has multiple frequency components. Spectral analysis reveals that the PWM signal has the spectrum of the original information signal as well as frequency components at the carrier frequency and harmonics of the carrier signal. The bottom trace in Fig. 2 shows the frequency spectrum of a PWM signal with a 1 KHz PWM cycle (carrier) frequency and modulated at 65% PWM duty cycle. The amplitude of each of the frequency spikes is a function of the percent duty cycle. The signal at 0 Hz is the spectrum of the information signal. It is recovered by low pass filtering of the PWM signal to remove the carrier frequency at 1 KHz and the harmonics of carrier signal. One can observe the reduced amplitude spikes of the harmonics at multiples of 1 KHz. The harmonics are the frequency components that are needed to generate the square waves of the PWM signal and are not needed to demodulate the PWM signal.

#### PWM Demodulation and Motor Speed Control

Demodulation is the processes that separates the information signal from carrier signal and returns the signal to its original format. For PWM, the demodulator is an integrator implemented with a low pass filter. If we are reconstructing a bipolar signal, then a circuit must be added to remove the DC bias or to use a series capacitor to block the DC offset component of the signal.

The information signal used to modulate the PWM rectangular wave for this project is a DC signal of different levels. Figure 3 shows the block diagram of a circuit that can be used to demodulate the microprocessor’s PWM output to control the speed of a DC motor that will rotate in one direction only. Since the PWM signal has only two states, on and off, the output power can be amplified with a single transistor.

The speed of a DC motor is related to the applied voltage. The higher the applied voltage, the faster the motor turns. The relationship between applied voltage and motor speed is not linear. The average voltage applied to a DC motor can be controlled using a PWM signal. The DC motor driver circuit provided by the PmodHB5 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 circuit shown in Fig. 4 is one means of implementing bipolar control where the PWM signal contains the signal magnitude and a separate binary signal indicates the sign on the magnitude. For this project, the PWM output will be used to power a DC motor, as shown in the project 9 Parts Configuration link towards the right. The PmodHB5 H-bridge driver shown in the block diagram serves as the power amplifier. There is no need for a low-pass filter because the DC motor will respond only to the modulation signal and reject the carrier frequency signal and its harmonics.

For the circuit in Fig. 4, power amplifier #1 outputs a high voltage level and amplifier #2 outputs a low voltage level when the enable pin is set high and the direction control pin is also high. When the direction pin is set low and the output enable pin is set high, the power amplifier #1 outputs a low voltage level and amplifier #2 outputs a low voltage level. A voltage difference across the terminals of the DC motor causes the motor to turn. Reversing the direction of current flow through the motor causes the motor to reverse its direction of rotation. Whenever the enable pin is low, the outputs from the power amplifiers are in a high impedance state.

#### PWM with Timer Output Compare

The PWM pulse-width is controlled by the PIC32MX processor output compare (OC) module. The reader may wish to review the web PIC32 PWM example as a starting point for this design. Even though there are five PWM outputs available, we are constrained to using either Timer 2 or Timer 3 to generate the PWM cycle frequency. For Project 9, we will use Timer 2. The DC motor is connected to JD on the chipKIT™Pro MX7 processor board. This connection provides access to output compare channel 3 (OC3) that we will use to generate the PWM output. Although the complete programming details to set up a PWM output are provided below, 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 Equations (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 Equation 3. The PWM DUTY CYCLE value is written to the output compare register, OC3RS, 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 OC3RS register is greater than the value in the PR2 register.

 $\begin{array}{l}OC3RS\_VALUE = (PWM DUTY CYCLE * (PR2 + 1)/100) \\\end{array}$ (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 OC3RS register. Note that Eq. (3) uses only integers in the math equation resulting in faster processor computation. Integer math always truncates the fractional portion of the result of a divide operation. To preserve resolution, multiply operations should be completed prior to divide operations. Use parentheses to dictate the order of evaluation of operations. (Note: PR2, OC3R, and OC3RS are PIC32 registers and should never be declared as a variable or a constant.)

The resolution of the PWM output compared to the resolution of an equivalent digital-to-analog converter (DAC) is the inverse of the timer PWM_CYCLE_COUNT. The resolution relates to the smallest increment that the output voltage can be changed. For example, if PR2 is set to 999, then the resolution of the PWM output is one part in (PR2 + 1) or 1000. This is equivalent to a N-bit DAC where N = log2( PWM_CYCLE_COUNT) rounded up to the nearest integer. Consequently, for our example, one part in 1000 results in N being equal to 10.

For a given timer input clock frequency, the higher the PWM cycle frequency, the lower the DAC resolution. Consider the case where the desired a PWM cycle frequency is 20 KHz when the PBCLK is 10 MHz and the Timer 2 prescale is set to one. The PWM_CYCLE_COUNT value equals (10E6 / 20E3), resulting in PR2 being set to the value of 499. A PWM_CYCLE_COUNT of 500 is approximately equivalent to a 9-bit DAC (29 = 512).

The Parts Configuration page shows a block diagram of the equipment used in Project 9. The Motor Controller Wiring Diagram link provides the pin connections between the Pmod HB5 and the chipKIT™Pro MX7 processor board. The EN (enable) pin is the PWM input to the Pmod HB5 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 project. The SA and SB pins should be set as inputs, but they will not be used until Project 10.

#### Programming the Timer Output Compare for PWM Operation

Figure 16.1 of the PIC32 Family Hardware Reference Manual shows the block diagram of the compare output module. This diagram shows that the timer count value is compared with the output compare register. This reference describes multiple modes of the operation output compare module. Readers should read section 16.3.3 of this reference manual. We will not be using the fault protection capability in this project.

The PWM output using OC3 can be set up and controlled using four XC32 peripheral library functions. The process is defined by the following steps:

1. mOC3ClearIntFlag(); // Clear output compare interrupt flag.

2. OpenTimer2(Set_up_bits, PR2_value); where (PR2_value is one less than the value computed for the PWM cycle frequency. Initialize Timer 2 to generate an interrupt at the rate of the PWM cycle using the programming concepts provided in Project 5. In the Timer 2 ISR, toggle the LEDA bit for timing instrumentation.

3. 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. Refer to the Section 13 of the C32 Peripheral Library Guide for option details.
• 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
• nOC3RS—This is a constant or a variable that specifies the initial PWM compare value. This is set to the initial PWM duty cycle setting.
• nOC3R—This is a constant or a variable that specifies the next PWM compare value. This is set to the same value as nOC3RS.
• The range of values for nOC3RS and nOC3R is 0 to PR2+1. PR2 is the Timer 2 period register value that is specified in step 2. If values for nOC3RS and nOC3R are set to a value equal to or greater than the PR2, the PWM output will be set to a constant high.
4. After initialization, the last function, “SetDCOC3PWM(nOC3RS)”, can be used to change the PWM duty cycle at any time while code is executing. The value of nOC3RS is in the range of zero to PR2-1. PR2 was specified in step 2. Note: The OC output is set high continuously if the nOC3RS is set to a value equal to the PR2 and less than 65535.

For this project, the DC motor driver module is connected to chipKIT™Pro MX7 processor board PmoD jack, JD. JD pin 7 is connected to the PIC32 (PORTD) RD1 I/O pin and controls the HB5 PMod DIR signal that sets the direction that the motor rotates. RD1 should be configured as a digital output and set to output a low level. When the Output Compare module is enabled, it is set OC3 (Port D pin 2) the I/O pin direction as an output. The Output Compare module returns the I/O pin control back to the appropriate pin LAT and TRIS control bits when it is disabled. The PWM output is on JD pin 8 that is connected to the PIC32 Output Compare 3 (OC3). Hence, we will use the instruction “OpenOC3(OC_configure_bits, nOC3RS, nOC3R);” to initialize the PWM.

JD pins 9 and 10 are the tachometer inputs. Although these pins will not be used until Project 10, RD3 and RD12 should be initialized as digital inputs.

The objective of this project is to implement an open-loop motor speed control. Open loop control is analogous to you driving your car down the highway with the accelerator at a fixed position. The car speed will vary depending on the grade of the highway. Similarly, the speed of a DC motor is a function of the DC voltage and the mechanical load. The motor speed will decrease as the mechanical load increases, if the applied voltage remains fixed. For this project, the motor speed control will be set to the four fixed PWM duty cycle values shown in Table 1. These duty cycle values are selected using the chipKIT™Pro MX7 processor board BTN1 and BTN2 pushbuttons. The percentage PWM duty cycle will be displayed on line 1 of the LCD. Specifically, the project tasks are as follows:

1. Write and verify the C code to complete the button control and LCD display design specified below.
2. Capture the four logic analyzer screen captures for the PWM for the four settings specified in Table 1.
3. Capture the LEDA, LEDB, and PWM EN signals to demonstrate that the PWM output and Timer 2 interrupts continue to function while the CN interrupt is being served.

Table 1. Button-controlled PWM.

BTN2 BTN1 PWM
OFF OFF 40%
OFF ON 65%
ON OFF 80%
ON ON 95%

## Project Specifications

1. Setup the hardware as shown in Fig. 1 of the Project 9 Parts Configurations page.
• Be careful to observe the polarity of the 10V power connection to the Pmod HB5 motor driver circuit as shown in Fig. 1 of PModHB5 Half H-Bridge Drive page.
• Attach the DC motor pictured in Fig. 1 of the Geared DC Motor page to the Pmod HB5 motor driver.
• Connect the PmodCLP to the chipKIT™Pro MX7 processor board JC and JD. (Refer to Project 6.)
• Adjust the motor power supply for 10VDC.
2. Set the PWM output as a function of the states of buttons BTN1 and BTN2, as specified in Table 1.

3. Detect button uses the change-notice interrupt similar to the Project 5 implementation. The CN interrupt is to use a 20 ms software delay for switch debouncing.

4. Toggle LEDA in the Timer 2 ISR at the rate of 500 Hz to indicate that the PWM cycle period is 1ms.

5. Writes the PWM percent duty cycle to line 1 of the LCD whenever the buttons change the PWM duty cycle, as per Table 1.

6. The following are the required functions and descriptions of operations:
• “Main”.
• Calls application initialization.
1. Configure chipKIT™Pro MX7 processor board BTN1 and BTN2 as inputs.
2. Configure PmodSTEP LEDA through LEDD as outputs.
3. Configure Timer 2 to generate an interrupt each millisecond.
4. Configure the PWM output channel as follows:
• Use output compare 3 (OC3).
• Uses Timer 2 for the time base for the output compare.
• PWM cycle frequency of 100 Hz.
5. Initialize a CN interrupt for button status detection at priority 1 and the sub priority level 0.
6. LCD initialization with a function added to position the LCD cursor at any position. (Refer to Project 6.)
• Executes a while(1); loop that does nothing.
• Button Detect ISR (refer to Project 5).
• Sets LEDB on entry and clears LEDB on exit.
• Removes button contact bounce with 20 ms software delay.
• Decodes buttons and sets PWM in accordance with Table 1.
• Sets the motor PWM.
• Updates only line 1 of the LCD reporting the percent PWM duty cylce using the format: PWM = ##%.
• Clears CN interrupt flag.
• Timer2 ISR.
• Toggles LEDA.
• Clears T2 interrupt flag.

## Project Testing

As shown in the connection diagram of the Motor Controller Wiring page, the PWM output on the OC3 output pin is connected to the motor enable (EN) pin. After developing a program that meets the project specifications, connect the logic probe to the EN pin (JD pin 8). As shown in Fig. 5, verify the PWM output for the four settings listed in Table 1. Also, verify that the PWM cycle time is 1 ms by connecting a logic probe to the LEDA output pin. Connect LEDB pin to the second logic analyzer probe to observe the operation of the PWM when a button is pressed to change the motor speed, as shown in Fig. 5.

## Try It on Your Own!

1. The resolution of the PWM is roughly equivalent to how many bit D to A converters?

• The resolution of the PWM is roughly equivalent to how many bit D to A converters?
2. How can you prove that the PWM continues to run while the button-detect ISR is running?

• ANSWER: The test point at LEDA is toggled on each occurrence of the Timer 2 interrupt. It continues to toggle while the LEDB is on that indicates that a CN interrupt is in progress. If interrupt nesting is not enabled, the LEDA would stop toggling while LEDB is high.
3. How does the speed of the processor affect the accuracy of the PWM signal?

• ANSWER: Since the PWM signal is generated in hardware, the code has little or no effect on the PWM timing.
4. What is the computational limitation when using PWM?

• ANSWER: The new PWM value must be computed in time that is less than the PWM cycle period.
5. What is the purpose of having dual output compare control registers ( OCxRM and OCxRS)?

• ANSWER: The double buffering ensures that the PWM is not adjusted in the middle of the period, thereby avoiding glitches.