Chapter 2 Development of a MATLAB

Chapter 2
Development of a MATLAB-based Graphical User
Interface Environment for PIC Microcontroller
Projects
2.1.
Introduction
Peripheral Interface Controllers (PICs), developed and marketed by Microchip Technology, Inc. [35], are inexpensive microcontroller units that include a central processing unit and
peripherals such as memory, timers, and input/output (I/O) functions on an integrated circuit (IC). There are more than 100 varieties of PIC microcontrollers available, each providing
functionality for different types of applications [36], making PICs one of the most popular
microcontrollers for educational, hobby, and industrial applications. Similar to other microcontrollers, PICs are usually not designed to interface with human beings; instead they are
directly embedded into automated products/processes. Thus, graphical user interface (GUI)
capabilities, which have become a mainstay of many personal computer (PC) applications, are
nonexistent for PICs.
Endowing PIC-based projects with GUI tools can speed the development process in data
driven applications such as feedback control, smart sensors, etc. Microchip Technology’s emulator and debugger products (e.g., MPLAB IDE, MPLAB-ICE) are very helpful in debugging
PIC source code and emulating user-written programs. However, these tools do not provide
data co-processing and advanced data visualization capabilities.
Fortunately, PIC microcontrollers include serial communication functionality to facilitate
data communication with external devices such as analog to digital converters (A2D), 1-wire
sensors, etc. Similarly, MATLAB, a commercially available interactive mathematical programming software, also provides serial data communication functionality on PCs. In addition,
Simulink, MATLAB’s interactive icon-based programming environment, enables users to simulate and analyze dynamic system models. Finally, the Dials and Gauges Blockset of Simulink
7
8
allows users to embed control objects (e.g., sliders, knobs) and display objects (e.g., graphs,
gauges) in Simulink models to develop an interactive GUI environment. In this dissertation,
we exploit the serial communication functionality of MATLAB to enable a PC to communicate
with PIC microcontrollers to transmit control commands and receive sensory data. In addition, we utilize MATLAB, Simulink, and Dials and Gauges Blockset to develop an interactive
GUI environment for PIC projects, allowing enhanced data processing and visualization.
In this dissertation, we use a PIC16F74, 40-pin, 8-bit CMOS FLASH dual inline package IC.
To facilitate serial communication between PIC and PC, we interface a RS232 driver/receiver
with the PIC16F74. The effectiveness of our MATLAB-based GUI environment to interact
with PIC microcontroller projects is demonstrated by using three examples: i) export user
commands from a Simulink GUI to an actuator interfaced to the PIC; ii) import signals from
a sensor interfaced to the PIC into a Simulink GUI; and iii) use Simulink GUI to export user
commands to the PIC and import sensory data from the PIC to control a device and monitor
its status.
2.2.
Hardware Environment
The hardware environment for this dissertation consists of a PIC microcontroller, a PC,
a RS232 driver/receiver, and a DB-9 serial cable. The PIC microcontroller is interfaced with
external devices such as sensors (e.g., photoresistors) and actuators (e.g., servomotors). In
addition, the PIC microcontroller performs embedded computing. The PC is used to write
user specified embedded programs to be executed by the PIC microcontroller. Furthermore,
the PC hosts an interactive GUI for the user to manipulate control variables and visualize
sensory data. The PIC microcontroller and the PC communicate using a serial interface. A
PIC development board (see section 2.2.4) and a light refraction experiment test bed (see
section 2.2.5) are used to illustrate our PIC-based data acquisition and control approach.
2.2.1.
Peripheral Interface Controller
PIC microcontrollers are small, low-cost controllers that include a processor and a variety
of peripherals. PICs are significantly easier to use vis-`
a-vis embedded microprocessors. As an
9
example, users can assign desired functionality (e.g., A2D, universal synchronous/asynchronous
receiver and transmitter (USART)) to I/O pins of PICs. PICs can be operated at various clock
speeds (32 kHz to 20 MHz). PIC’s memory architecture separates its data memory from its
program memory with the program memory available as One-Time Programmable (OTP),
Erasable Programmable Read-Only Memory (EPROM), or FLASH. PICs are programmed in
the PIC assembly language using a 35 single-word instruction set. See [37] for more details on
hardware and software features of PIC microcontrollers.
The user specified embedded PIC program is written on the PC and downloaded from the
PC to the PIC microcontroller using the DB-9 serial cable connection between the PC and
a PIC Development Programmer on which the PIC microcontroller is installed. Commonly
available PIC Development Programmers include PICSTART Plus [38] from Microchip, Inc.,
and PIC-PG2B, a handy, low-cost programmer [39] from Olimex Ltd., among others. In
this dissertation, we use the PICSTART Plus programmer that requires MPLAB Integrated
Development Environment, a free software available on the Microchip website, for programming
PICs.
In this dissertation, we employ a PIC16F74, a 40-pin CMOS FLASH-based, 8-bit, midrange (14-bit instruction word length) microcontroller (see Figure 2.1). PIC16F74 has 4
Kbytes of FLASH program memory and 192 bytes of data memory. Furthermore, it has
33 digital I/O pins organized in 5 groups of I/O ports that can be assigned as 8-bit A2D,
Capture/Compare/PWM (CCP), the 3-wire Serial Peripheral Interface (SPI), the 2-wire InterIntegrated Circuit (I2 C) bus, USART ports, etc. We use an external 20 MHz high-speed crystal
oscillator to supply operating clock cycles. The PIC16F74 can be powered using a wide range
of voltage sources, e.g., 2-volt direct current (VDC) to 5.5VDC, and each of its I/O pin can
sink or source up to 25mA of current. It is ideal not only for laboratory data acquisition (the
application considered in this dissertation), but also for automotive, industrial, and consumer
applications.
10
(a)
(b)
Figure 2.1: (a) PIC16F74 (b) Pin diagram of PIC16F74
2.2.2.
Personal Computer
In this dissertation, an IBM-compatible Pentium 3 PC running Microsoft Windows NT
4.0 operating system is used. As previously mentioned, the PC is used to write, debug, and
download embedded PIC programs. One of the serial ports on the PC is reserved for serial
communication with the PIC microcontroller. MPLAB, MATLAB (version 6.1), Simulink,
and Dials and Gauges Blockset are installed on the PC. Control variables are manipulated via
the PC by interacting with control panels embedded in the Simulink program. In addition,
all experimental data is collected and displayed on the PC in display panels embedded in the
Simulink program.
2.2.3.
RS232 Driver/Receiver
MAX232 (see Figure 2.2) is a 2-channel, RS232 driver and receiver manufactured by Maxim
Integrated Products, Inc. It requires a 5VDC power supply and converts voltage levels between
PC-based logic and PIC microcontroller-based logic. Specifically, whereas the voltage levels
of logic high and logic low for the PC correspond to -12VDC and 12VDC, respectively, like
many other microcontrollers the logic high and low for the PICs correspond to 5VDC and
0VDC, respectively. The MAX232 is used with five 1µF capacitors to adjust the voltage level
differences between the PC-based logic and the PIC-based logic. See [40] for more details of
the MAX232 hardware features.
11
(a)
(b)
Figure 2.2: (a) MAX232 (b) Pin diagram of MAX232
2.2.4.
PIC Development Board
The PIC development board (see Figure 2.3) consists of a sensor (photoresistor), a 3pin header for a servomotor connection, a 20MHz crystal oscillator, a MAX232 with five
1µF capacitors, a PIC16F74 microcontroller, a breadboard, and two DB-9 connectors. The
photoresistor sensor provides light intensity measurement and is interfaced to a pin allocated
as an 8-bit A2D in port A of the PIC16F74 microcontroller. The circuit diagram of Figure 2.4
illustrates how various sensors and actuators of the light refraction experiment test bed (see
section 2.2.5) are interfaced to the PIC microcontroller. The PIC transmits/receives sensory
data to/from the PC via the MAX232. A red reset button is connected to the Master Clear
(MCLR) pin of the microcontroller.
Pentium class PC
Reset button
DB-9 serial cable
PIC
DB-9 connector to
light refraction test bed
Photoresistor
3-pin
servomotor
connector
MAX232
(a)
(b)
Figure 2.3: (a) PC and PIC development board (b) Larger view of the PIC development
board
12
5V
5V
10 kΩ
10 kΩ
1kΩ
Reset button
1
2
Linear
potentiometer
3
Limit switches
4
Photoresistor
15pF
20MHz
39
H-Bridge
38
Laser
34
Servomotor
32
31
11
0.1μF
26
25
14
1μF
1μF
12
13
15pF
H-Bridge
5V
5V
0.1μF
40
RX
TX
5V
1μF
1
3
1μF
16
2
6
1μF
4
5
12
13
RS232 output
11
14
RS232 input
15
MAX232
PIC16F74
Figure 2.4: Circuit diagram of the PIC development board
2.2.5.
Light Refraction Test Bed
The light refraction test bed (see Figure 2.5) is a mechatronics-aided physics experiment
developed under a National Science Foundation (NSF) sponsored Science and Mechatronics
Aided Research for Teachers (SMART) program [41] at Polytechnic Institute of New York
University. This experiment is designed to demonstrate the law of light refraction. It consists
of a light source, a light sensor, a linear potentiometer, two limit switches, a servomotor, a
DC motor, a liquid reservoir, and necessary circuitry. A liquid reservoir on the top of the
test bed can store various liquid media whose index of refraction needs to be determined. For
simplicity, in this dissertation, we use water from a water fountain as the test liquid.
Servomotor
Light source
Reservoir
H-Bridge
Light sensor
DC motor
Limit switches
(a)
Linear
potentiometer
(b)
Figure 2.5: (a) Light refraction experiment test bed (b) Light source mounted on the servomotor
13
On one side of the tank, as shown in Figure 2.5 (b), a laser pointer, used as the light
source, is mounted on the arm of the servomotor that sets the angular position of the light
source to the incidence angle specified by the user. On the other side of the tank, a general
Cadmium Sulfide (CdS) photoresistor, used as the light sensor, is mounted on the wiper of the
linear potentiometer. It monitors the refracted light coming out from the liquid reservoir (see
Figure 2.6). A DC motor drives the light sensor along the linear potentiometer by turning
a motor shaft connected to a brass screw rod thereby transforming rotary motion into linear
motion. Limit switches at each end of the linear potentiometer indicate sensor travel limit.
The photoresistor and the linear potentiometer output analog voltage signals between 0VDC
and 5VDC.
Figure 2.6: Detailed view of the light sensor traveling along the linear potentiometer
2.3.
Software Environment
The software environment for this dissertation consists of the PIC assembly language,
MATLAB, Simulink, and Dials and Gauges Blockset. The PIC assembly language is a primitive programming language consisting of a 35 single-word instruction set. MATLAB is an
interactive technical computing software. Simulink is MATLAB’s model-based, system-level,
visual programming environment that is widely used to simulate and analyze dynamic system
models using icon-based tools. Finally, the Dials and Gauges Blockset of Simulink provides an
ability to embed visual, realistic-looking, virtual instrumentations in Simulink models. In this
dissertation, these software tools are judiciously synthesized to produce an effective, interactive
GUI environment. In the sequel, we summarize key instructions of the PIC assembly language
14
and MATLAB that enable serial communication between PIC microcontroller and MATLAB
GUI running on the PC.
2.3.1.
PIC Assembly Program
As indicated above, the PIC assembly language consists of a 35 single-word instruction set
(see datasheets [42] for details). The PIC data memory is partitioned into several banks (e.g.,
5 banks for PIC16F74) that contain the general-purpose registers and the special-function registers. The special-function registers are used to set up special operations (e.g., A2D, USART,
and PWM) and to watch the status of the special operations (e.g., the availability of transmission or reception of the USART). Below, we review key PIC instructions and special function
registers used for serial communication functionality.
1) Key PIC Instructions
BCF: Bit clear f
Syntax: [label] BCF f, b
BCF literally means that the bth bit in the register ‘f’ is cleared. BCF sets the bth bit in the
register ‘f’ to zero, logic low.
BSF: Bit set f
Syntax: [label] BSF f, b
BSF instruction does the opposite of BCF, i.e., it sets the bth bit in the register ‘f’ to one,
logic high.
MOVLW: Move literal to w
Syntax: [label] MOVLW k
The literal ‘k’ is loaded into the working register. The literal ‘k’ can be expressed in terms of
an 8-bit binary, decimal, or hexadecimal number. For example, b’00101111’ in 8-bit binary is
equivalent to 0x2F in hexadecimal. Note that the prefixes b, 0x, and d declare the data type
to be binary, hexadecimal, and decimal, respectively.
MOVWF: Move w to f
Syntax: [label] MOVWF f
15
MOVWF transfers data from the working register to the specified register ‘f.’ Since the literal ‘k’ cannot be directly assigned into the specified register ‘f,’ the literal ‘k’ is first assigned
to the working register (e.g., MOVLW k) and then moved into the register ‘f’ (e.g., MOVWF f).
BTFSS: Bit test f, skip if set
Syntax: [label] BTFSS f, b
BTFSS checks the bth bit in the specified register ‘f,’ and executes the next instruction if this
bit is zero. Alternatively, if the bit is one, the next instruction is skipped, and the following
instruction is executed.
2) Special Function Registers Used for Serial Communication Functionality
MOVLW d’value’
MOVWF SPBRG
The special function register ‘SPBRG’ contains the user-specified baud rate for serial communication. In particular, the command MOVLW d’129’ places 129 in the working register.
Next, the command MOVWF SPBRG moves the content of the working register to the special
function register ‘SPBRG.’ The placement of ‘value’ 129 in the ‘SPBRG’ register sets the baud
rate to 9,600.
MOVLW b’clock source select bit, 9-bit transmit enable bit, transmit enable bit, usart mode
select bit, unimplemented, high baud rate select bit, transmit shift register status bit, 9th bit of
transmit data’
MOVWF TXSTA
The special function register ‘TXSTA’ contains information for the data-transmit status and
control in an 8-bit binary expression. In particular, the use of commands MOVLW b’00100100’
and MOVWF TXSTA, sets up the ‘TXSTA’ register to enable 8-bit, high speed asynchronous
serial data transmission.
MOVLW b’serial port enable bit, 9-bit receive enable bit, single receive enable bit, continuous
receive enable bit, unimplemented, framing error bit, overrun error bit, 9th bit of received data’
MOVWF RCSTA
The special function register ‘RCSTA’ contains information for the data-receive status and con-
16
trol in an 8-bit binary expression. In particular, the use of commands MOVLW b’10010000’
and MOVWF RCSTA, sets up the ‘RCSTA’ register to enable 8-bit, continuous asynchronous
serial data reception.
2.3.2.
MATLAB Program
MATLAB is a commercially available, widely used, interactive, technical computing software. MATLAB’s versions 6.1 and higher provide serial communication functionality. To
serially communicate with an external device from MATLAB, the following steps need to be
performed. First, create a serial port object to identify the specific serial port of the PC
connected to the external device. In addition, specify how this serial port is to be configured
(i.e., baud rate, number of data bits, etc.). Second, connect the serial port object created
above to the external device. Third, send command signals to the external device and receive
data from the external device. Fourth, disconnect serial communication connection from the
external device and close the serial port object. Finally, release control of the serial port. Next,
we list the key MATLAB instructions used for serial communication. See [6] for further details.
serial (the PC serial port, the baud rate, the number of data bits)
This command is used to create a new serial port object. In addition, it configures the serial
port properties. In this dissertation, we used the COM2 serial port of the PC with 9,600 baud
rate.
fopen (object)
This command opens the serial port object just created and connects the PC to the external
device for actual serial communication.
fread/fwrite (object, size, precision)
The fread command enables the PC to read binary data from the external device. Alternatively,
the fwrite command enables the PC to send control data in binary format to the external device.
fclose (object)
This command closes the serial port object, thereby disconnecting serial communication be-
17
tween MATLAB and the external device.
freeserial (port)
Once MATLAB establishes a data link with the serial port, it assumes complete control of
the serial port. The freeserial command is used, after closing the port object using the fclose
command, to force MATLAB to relinquish control of the serial port. The command takes on
one argument, the port that was used for data communication. This command is executed
from the MATLAB command line after the termination of experiment.
2.3.3.
Simulink
Simulink is MATLAB’s interactive, icon-based programming environment [43]. It enables
users to build block diagrams to simulate and analyze dynamic system models. Designers can
effortlessly transfer paper designs of dynamic systems into Simulink block diagrams. Simulink
block diagrams can be modified as easily as paper models of dynamic systems. In addition,
Simulink allows for detailed monitoring of dynamic system outputs at any point in the block
diagram using various tools (e.g., Scope, Display, etc.). Finally, data processing tasks such as
signal scaling, filtering, etc., can be easily performed in Simulink.
2.3.4.
Dials and Gauges Blockset
The Dials and Gauges Blockset [44] provides enriched views of graphical, 3-D instruments
called virtual instruments. It has various templates that can be customized to create realistic
virtual instruments for electrical, aerospace, automotive, medical, and process control systems.
The virtual instruments created using the Dials and Gauges Blockset dynamically interact with
MATLAB and Simulink, thus providing an interactive interface for users to enter command
inputs and visualize sensory outputs.
2.4.
2.4.1.
Examples of Serial Communication between PIC and PC
Serial Communication from PC to PIC: Servomotor Position Control
This example illustrates one-directional serial communication from the PC to the PIC
microcontroller. In particular, it demonstrates that the user commands from a Simulink block
18
diagram can be exported to an actuator interfaced to the PIC microcontroller. The example
focuses on servomotor position control.
The Simulink block diagram for this example is shown in Figure 2.7. It consists of a dial,
from the Dials and Gauges Blockset, denoted as the servo angle knob. The user interacts with
the dial to enter servomotor position control command. The dial has a range from 0 to 90
degrees with one-degree resolution. The value of the angle commanded by the user is shown in
the middle of the knob. The MATLAB m-function block next to the knob contains a MATLAB
m-file to perform serial communication from the PC to the PIC. The user specified servomotor
position control command is transmitted to the PIC via a serial cable connection between
the PC and the PIC. When the PIC receives the command angle, it assigns the angle to a
variable in the PIC code. Next, the PIC utilizes the command angle to compute, generate,
and apply pulse trains for servomotor position control. In this example, we used a 6VDC
standard servomotor that is interfaced to the 3-pin servomotor connection header on the PIC
development board (see Figure 2.3). The PIC assembly code corresponding to this example is
available in Appendix A.
Table 2.1: M-function for PC to PIC serial communication
%MATLAB function serial out.m for serial communication from PC to PIC
function serial out(angle)
%serial out function defined
ser obj=serial(‘COM2’,‘baudrate’,9600); %create and configure a serial port object
fopen(ser obj);
%connect the serial port object to the device
ServoCommand=round(angle+107.3); %input for servomotor where 107.3 refers to offset
fwrite(ser obj,[ServoCommand],‘async’); %send user command, i.e., dial input, to the PIC
pause(1);
fclose(ser obj);
%disconnect the serial port object from the device
2.4.2.
Serial Communication from PIC to PC: Data Acquisition, Processing, and
Plotting
This example illustrates one-directional serial communication from the PIC microcontroller
to the PC. In particular, it demonstrates that a Simulink block diagram can be designed to
acquire measurement from a sensor that is interfaced to the PIC. The example focuses on
19
Figure 2.7: Simulink block diagram for PC to PIC serial communication
acquiring measurements from a photoresistor that senses light intensity.
Referring to Figure 2.4, a light sensor is constructed by connecting a 10 KΩ resistor and a
photoresistor in a voltage divider circuit. The output of the light sensor varies depending on
the light intensity incident upon the photoresistor; here the light sensor output refers to the
voltage at the junction of the 10KΩ resistor and the photoresistor. This output is connected
to I/O pin 2 of the PIC16F74. The I/O pin 2 is configured as an A2D in the PIC assembly
code. Each time, the PIC assembly code tasks the PIC to measure the light sensor output, the
PIC16F74 converts the analog voltage signal at the voltage divider output into a corresponding
8-bit digital value. Thus, when the photoresistor is placed in dark condition, the 8-bit A2D
returns a value close to 255. Alternatively, when the photoresistor is exposed to bright light,
the A2D returns a value close to 0.
The Simulink block diagram for this example is shown in Figure 2.8, where a MATLAB mfunction is used to acquire the digitized output of the sensor using serial communication. The
Simulink block diagram of Figure 2.8 also processes and plots the sensory data. In particular,
the top scope in Figure 2.8 plots the light intensity measurement (in terms of digitized output
of the voltage divider circuit) versus time, where the measurements are filtered using a low-pass
filter. The middle scope plots the unfiltered light intensity measurement. Finally, the bottom
20
scope plots the light intensity measurement in terms of voltages by processing the 8-bit digital
value of the voltage divider circuit through a gain factor.
Table 2.2: M-function for PIC to PC serial communication
%MATLAB function serial in.m for serial communication from PIC to PC
function v=serial in(dmyin)
%serial in function defined
ser obj=serial(‘COM2’,‘baudrate’,9600);%create and configure a serial port object
ser obj.ReadAsyncMode = ‘manual’; %specify an asynchronous read operation
fopen(ser obj);
%connect the serial port object to the device
LightSensOut=fread(ser obj,1,‘uint8’); %read the light sensor output
fclose(ser obj);
%disconnect the serial port object from the device
v=LightSensOut;
%8-bit representation of the light sensor output
Scopes
Figure 2.8: Simulink block diagram for PIC to PC serial communication
An experiment was conducted in which the light intensity was abruptly altered at several
time instances. The response plots acquired and processed using the Simulink block diagram
of Figure 2.8 are shown in Figure 2.9. The filtered output response in Figure 2.9(b) is much
smoother than the unfiltered response in Figure 2.9(a). Thus, Figure 2.9 demonstrates the
efficacy of signal co-processing using MATLAB and Simulink for PIC-based projects. The PIC
assembly code corresponding to this example is available in Appendix B.
Light sensor O/P (8-bit)
Light sensor O/P (8-bit)
21
Time (Sec)
(a)
Time (Sec)
(b)
Figure 2.9: (a) Unfiltered plot of A2D and (b) Filtered plot of A2D
2.4.3.
Bi-directional Serial Communication between PIC and PC
In this example, the light refraction test bed is used to demonstrate the advantage of exploiting bi-directional serial communication between PIC and MATLAB-based GUI executing
on the PC. A Simulink-based interactive GUI for the light refraction test bed is shown in
Figure 2.10. The user interacts with the dial object to command the angle of incidence of light
source. The MATLAB m-function block next to the knob contains a MATLAB m-file that
transmits the user command input to the PIC serially. The PIC stores the user input in a variable and uses it to compute, generate, and apply pulse trains to control servomotor position.
This positions the light source, mounted on the servomotor arm, at the commanded angle of
incidence. Next, the PIC turns on the light source and performs the following tasks: drive
the light sensor along the linear potentiometer by turning the DC motor, measure the position
of the light sensor along the linear potentiometer and the corresponding output of the light
sensor, and transmit the position and light sensor measurements to the PC. The MATLAB
m-function block shown in Figure 2.10 enables receipt of the position and light sensor measurements from the PIC serially. Simulink blocks following the m-file function block are used
for various data processing tasks, e.g., conversion of position measurement to the refraction
angle and computation of index of light refraction. Finally, a generic numeric LED display,
from the Dials and Gauges Blockset, is used to indicate the calculated value of index of light
22
refraction for the experimental liquid.
Table 2.3: M-function for bi-directional serial communication between PIC and PC
%MATLAB function serial inout.m for bi-directional serial communication bet. PIC & PC
%serial inout function defined
function V=serial inout(angle)
ser obj=serial(‘COM2’,‘baudrate’,9600);%create and configure a serial port object
ser obj.ReadAsyncMode = ‘manual’;
%specify an asynchronous read operation
fopen(ser obj);
%connect the serial port object to the device
ServoCommand =round(angle+107.3); %input for the servomotor with offset of 107.3
fwrite(ser obj,[ServoCommand],‘async’); %send user command, i.e., dial input, to the PIC
LightSensOut =fread(ser obj,1,‘uint8’); %read the light sensor output from the PIC
Position=fread(ser obj,1,‘uint8’)+9;
%read the linear pot. output from the PIC
fclose(ser obj);
%disconnect the serial port object from the device
V=[LightSensOut;Position];
%output in matrix form
Figure 2.10: Simulink block diagram for bi-directional serial communication between PIC
and PC
Figure 2.11 shows the block diagram of index of light refraction subsystem of Figure 2.10.
The block diagram of Figure 2.11 is used to generate a plot of angle of refraction versus the
light sensor output. Figure 2.12 shows the plots of angle of refraction versus the light sensor
output for two commanded values of incidence angle, namely, 40◦ and 20◦. Note that for each
incidence angle, the index of refraction is computed from the angle of refraction corresponding
to the smallest output returned by the light sensor. Thus, the block diagram of Figure 2.11 is
23
also used to calculate the index of light refraction. The MATLAB m-function in this subsystem
monitors and captures the angle data corresponding to the smallest measurement returned by
the light sensor. Note that the light sensor output is smallest when the intensity of refracted
light focused on the light sensor is highest. Next, the angle data is used to compute the
index of light refraction. The PIC assembly code corresponding to this example is available in
Appendix C.
Table 2.4: M-function for calculating the index of light refraction
%MATLAB function PickMin.m for capturing the angle of refraction when max.
%Light is on the light sensor.
function y=PickMin(minangle,minLSO,LSO,angle)
%PickMin function defined
if LSO <= minLSO
%loop for updating the minangle
minangle=angle;
%update minangle wrt minLSO
end
y=minangle;
%angle at the most light intensity
XY Graph block
Figure 2.11: Simulink block diagram for calculating the index of light refraction
2.5.
Conclusion
In this dissertation, we developed and presented MATLAB-based GUIs for PIC microcontroller projects by exploiting Simulink, Dials and Gauges Blockset, and serial communication
capabilities of MATLAB and PIC. Three examples were presented to illustrate the productivity enhancement potential of the MATLAB-based GUI environment when developing PIC
24
(a)
(b)
Figure 2.12: Angle of refraction vs. light sensor output for incidence angle (a) 40◦ and (b)
20◦
microcontroller projects. The GUIs designed using framework of this dissertation allow the
user to: i) vary control commands; ii) acquire sensory data; iii) perform on-line data processing; and iv) visualize data using realistic looking virtual instruments. Note that the framework
of this dissertation allows the use of microcontroller as a low-cost, stand-alone data acquisition
and control board (DACB). Whereas PC-based DACBs typically cost several hundred to over
thousand dollars, a PIC microcontroller costs only a few dollars. Thus, the use of PIC microcontrollers with the proposed MATLAB-based GUI environment provides a low-cost DACB
solution that can be particularly beneficial to educators.
Chapter 3
Development of a MATLAB Data Acquisition and
Control Toolbox for PIC Microcontrollers
3.1.
Introduction
Data acquisition and control boards are essential for interfacing sensors/actuators with
decision making devices such as a PC. Thus, data acquisition and control boards are used in
monitoring/instrumentation applications involving machinery, process, environment, etc., and
in automatic control applications. Even though a variety of data acquisition and control boards
have become widely available in the last 15 years, the systems that target the educational sector
and provide support for icon-based programming environments, such as LabVIEW [5] and
Simulink [43], tend to be quite expensive (over $500 to several thousand dollars). Moreover,
instructional labs generally may not require the intrinsic high-performance features of many
of the commercially available data acquisition and control boards (e.g., high sampling rates,
high resolution analog to digital converters, etc.) for the typical electro-mechanical laboratory
experiments. This dissertation proposes a microcontroller-based data acquisition and control
system that is particularly suitable for educators interested in developing lab experiments that
do not require high-cost, high-performance data acquisition hardware and yet can benefit from
the icon-based programming environment of Simulink.
Several recent papers have focused on interfacing low-cost microcontrollers (such as BASIC Stamp 2 (BS2) and PIC) with icon-based programming environments such as LabVIEW
and Simulink. Specifically, Refs. [45–47] concentrated primarily on endowing microcontrollers
with graphical user interface (GUI) capability by exploiting the GUI tools of LabVIEW and
Simulink. However, the methodology of Refs. [45–47] requires manually programming the
microcontroller for all sensing, control computation, and actuation tasks and for serial communication with the GUI running on the PC. To program a PIC microcontroller or a BS2 microcontroller using PIC assembly programming language or PBASIC programming language,
25
26
respectively, requires knowledge and experience with the syntax of these languages and is often
tedious.
This dissertation proposes a PIC microcontroller-based low-cost data acquisition and control system that exploits MATLAB and Simulink as the key software components for implementing data acquisition and control algorithms using a block-diagram format. Specifically,
the dissertation exploits a newly developed library of PIC functions for Simulink and the serial
communication capability of both the PIC microcontroller and MATLAB to produce a seamless
integration between them. The framework of this dissertation completely obviates the need to
manually program the PIC microcontroller by creating a library of PIC microcontroller functions for Simulink. Specifically, the data acquisition and control toolbox of this dissertation
facilitates: i) automatic generation of proper PIC assembly codes for a variety of sensors and
actuators; ii) automatic programming of the PIC microcontroller; and iii) data communication
between the PIC microcontroller and MATLAB. In an instructional laboratory, this approach
allows instructors and students to focus on hardware-in-the-loop implementation, experimental validation, and industry-style rapid control prototyping. Finally, this dissertation is in the
spirit of Ref. [48], which provided a MATLAB data acquisition and control toolbox for the
BS2 microcontrollers. However, whereas the BS2 microcontroller costs over $45 and includes
only digital input/output (I/O) functionality, thus requiring external analog to digital converters (A2Ds) to interface with analog sensors, the PIC16F74 microcontroller, used in this
dissertation, costs under $5 and includes built-in A2D functionality.
This dissertation is organized as follows. Section 3.2 describes the PIC microcontroller
and the related development hardware. Section 3.3 describes the software environment used
in this dissertation. Section 3.4 gives details concerning the software integration of Simulink
with the PIC microcontroller. Section 3.5 illustrates the functionality and capability of the
data acquisition and control hardware and software of this dissertation by performing position
control of a DC motor. Finally, Section 3.6 provides some concluding remarks.
27
3.2.
Hardware Environment
The main components of the data acquisition and control hardware of this dissertation
are a PIC microcontroller, a PIC-PG2C programmer, and a PIC development board. A DB9 serial cable is used to interface the programmer/development board to a PC which hosts
the MATLAB data acquisition and control toolbox. Specifically, the DB-9 cable allows i)
programming the PIC microcontroller from the PC and ii) data communication between the
PIC and the PC. In this dissertation, an IBM-compatible Pentium 4 PC running Microsoft
Windows XP operating system is used. See Figure 3.1 for a pictorial representation of the
aforementioned hardware environment.
PC
PIC development board
PIC microcontroller
DB-9 serial cable
PIC-PG2C programmer
Figure 3.1: Hardware environment
3.2.1.
Peripheral Interface Controller (PIC)
PIC microcontrollers, developed, manufactured, and marketed by Microchip, Inc. [35], are
small, inexpensive controllers that include a processor and a variety of peripherals such as
memory, timers, and I/O functions on an integrated circuit (IC). PIC microcontrollers are
widely popular among educational, hobby, and industrial users who can select from more than
100 varieties of PICs one that suits their application and functional needs. In contrast to
many other microcontrollers, PICs are quite versatile since their I/O pins can be assigned
desired functionality (e.g., A2D, universal synchronous/asynchronous receiver and transmitter (USART)) under program control. Moreover, using an appropriate crystal oscillator, PIC
microcontrollers can be operated at clock speeds of 32 kHz—20 MHz. The PIC assembly lan-
28
guage, consisting of a 35 single-word instruction set, is used to program PIC microcontrollers.
See Ref. [49] for more details on hardware and software features of PIC microcontrollers.
The data acquisition and control platform of this dissertation uses a PIC16F74 [42], a 40pin CMOS FLASH-based, 8-bit, mid-range (14-bit instruction word length) microcontroller.
Pertinent specifications of PIC16F74 include: 2—5.5 Volt direct current (VDC) voltage input;
25mA current sink/source capability at each I/O pin; 4 Kbytes of FLASH program memory;
192 bytes of data memory; and 33 digital I/O pins organized in 5 ports (A—E) of I/Os that
can be assigned as 8-bit A2Ds, Capture/Compare/PWMs (CCPs), 3-wire Serial Peripheral
Interfaces (SPIs), 2-wire Inter-Integrated Circuit (I2 C) buses, USART ports, etc. In this
dissertation, five of the six I/O pins of port A and three I/O pins of port E are reserved for
eight 8-bit A2Ds, eight I/O pins of port B are reserved for eight digital inputs, two of the
eight I/O pins of port C are reserved for two PWM outputs, and eight I/O pins of port D are
reserved for eight digital outputs. Finally, an external 20 MHz high-speed crystal oscillator is
used to supply operating clock cycles to the PIC.
3.2.2.
PIC-PG2C Programmer
The user specified PIC program, which is created on a PC, is downloaded from the PC to
a PIC microcontroller by serial communication. Serial communication between the PC and
the PIC microcontroller is enabled by using a DB-9 serial connection between the PC and
a PIC development programmer that hosts the PIC microcontroller. Two widely used PIC
development programmers are Microchip’s PICSTART Plus and Olimex’s PIC-PG2C [50]. In
this dissertation, the handy and low-cost PIC-PG2C programmer (see Figure 3.2) is used. In
contrast to other PIC programmers, the PIC-PG2C programmer receives power from the PC’s
serial port thus obviating the need for any additional power supply. Finally, the PIC-PG2C
programmer requires IC-Prog [51], a freely available software, to download PIC HEX code to
the PIC microcontroller. Note that the PIC HEX code is obtained from the PIC assembly
code by using the MPASM assembler [52], also available for free.
29
(a)
(b)
Figure 3.2: (a) PIC-PG2C programmer and a PIC (b) PIC-PG2C programmer with a PIC
mounted
3.2.3.
PIC Development Board
The PIC development board of this dissertation is created on a breadboard and consist of:
i) a PIC16F74 microcontroller; ii) a 20MHz crystal oscillator to supply operating clock cycles
to the PIC microcontroller; iii) the RS232 driver/receiver circuitry for serial data communication with the PC; iv) a DB-9 connector; and v) a breadboard area for custom circuits and
easy connectivity between the PIC microcontroller and sensors/actuators. Note that Maxim’s
MAX232 IC [40] with five 1µF capacitors serves as the RS232 driver/receiver to transform voltage levels between PC-based logic (±12VDC) and the PIC microcontroller-based logic (0VDC
and 5VDC).
3.3.
Software Environment
The software environment for this dissertation consists of MATLAB version 6.5, Simulink
version 5.0, the PIC assembly language, a newly developed Simulink library for the PIC microcontroller, MPASM, and IC-Prog. As previously discussed, the PIC assembly language is
a primitive programming language consisting of an instruction set of 35 single-words. MATLAB is an interactive technical computing software and Simulink is MATLAB’s icon-based
programming environment. The MATLAB toolbox for the PIC microcontroller consists of a
Simulink library of PIC microcontroller functions such that based on the user selected configuration of individual I/O pins of the PIC microcontroller, Simulink automatically produces
30
and downloads the proper PIC assembly code to the microcontroller. Moreover, the MATLAB
toolbox also allows data communication between the PIC microcontroller and MATLAB. Thus,
the MATLAB toolbox for the PIC microcontroller completely obviates the need to manually
program the PIC microcontroller. Note that the MATLAB toolbox automatically executes
the assembler program MPASM and the download program IC-Prog, both of which usually
require command line execution. See Refs. [52, 53] for details on programming the PIC microcontroller in command line via serial communication. The MATLAB toolbox for the PIC
microcontrollers has two main components: i) a Simulink model file named Template.mdl and
ii) a block library named PICLibrary.
3.3.1.
Template.mdl
The Template.mdl model file (see Figure 3.3) is a predesigned Simulink model file which
must be used to design Simulink block diagrams for interaction with the PIC microcontroller.
A function named TotalCompile has been embedded within the callback parameters of the
Template.mdl so that the TotalCompile function executes at the beginning of each Simulink
block diagram cycle, before the block diagram actually runs. Details of various tasks performed
by the TotalCompile function are provided in a later subsection. Finally, note that renaming
the Template.mdl file still preserves the callback property embedded in the file, whereas opening
a new Simulink model file does not.
Template.mdl model properties are modified to call
the TotalCompile function at the beginning of
each Simulink block diagram cycle
Figure 3.3: Template and model properties
31
3.3.2.
PICLibrary
The PICLibrary is a custom library of Simulink blocks (in the form of s-functions) that interface with sensors and actuators connected to the PIC microcontroller. The following blocks
are currently included in the PICLibrary: A2D, PinStateIn, PWM, and PinStateOut. Moreover, the library includes a block labeled IOBlock that is required in all user-designed Simulink
diagrams to enable serial communication between the PIC microcontroller and MATLAB.
Hardware settings and parameter requirements of each block are detailed below.
1) A2D block (see Figure 3.4) configures the analog to digital conversion module of the PIC
microcontroller. Note that five of the six I/O pins of port A and three I/O pins of port E of
the PIC16F74 microcontroller can be configured as eight 8-bit A2Ds. Thus, analog sensors can
be directly interfaced to any of the eight A2D pins and the corresponding pin number can be
passed as the parameter required by the A2D block.
Figure 3.4: A2D block and parameter
2) PinStateIn block (see Figure 3.5) configures the I/O pins of port B of the PIC16F74 microcontroller to serve as digital inputs. Specifically, each of the eight pins of port B can serve as
a digital input by passing the corresponding pin number as a parameter to the PinStateIn block.
3) PWM block (see Figure 3.6) configures PWM modules of the PIC microcontroller. Specifically, two of the eight I/O pins of port C of the PIC16F74 microcontroller can be configured
as PWM outputs. Since the PIC16F74 microcontroller does not include a digital to analog
converter, in this dissertation, we use the PWM outputs to produce the required analog volt-
32
Figure 3.5: PinStateIn block and parameter
age output by varying the duty cycle of the PWM signal. Thus, two analog actuators can be
interfaced to the two I/O pins of port C that produce PWM outputs and the corresponding
pin numbers are passed as the parameter required by the PWM block.
Figure 3.6: PWM block and parameter
4) PinStateOut block (see Figure 3.7) configures the I/O pins of port D of the PIC16F74 microcontroller to serve as digital outputs. Specifically, each of the eight pins of port D can serve as
a digital output by passing the corresponding pin number as a parameter to the PinStateOut
block.
5) IOBlock is necessary for every Simulink block diagram that requires interaction with the
PIC microcontroller. It performs the following tasks: i) initiate serial communication between MATLAB and the PIC microcontroller when the Simulink block diagram is initially
executed; ii) transmit and receive data between MATLAB and the PIC microcontroller while
33
Figure 3.7: PinStateOut block and parameter
the Simulink block diagram is running; and iii) terminate serial communication between MATLAB and the PIC microcontroller when the Simulink block diagram is stopped. The callback
function properties of the IOBlock include start serial and stop serial functions that initiate
and terminate serial communication, respectively. In the Simulink block diagram, the IOBlock
is programmed to have the first priority for execution. This ensures that all sensor and actuator data in MATLAB are first received and sent, respectively, which then is used by the
corresponding sensor and actuator blocks in the Simulink block diagram.
Figure 3.8: IOBlock and parameters
Several Simulink blocks, such as an integrator block, require the knowledge of sampling
period for their proper use in a given Simulink block diagram. In this dissertation, the IOBlock
is used to determine, experimentally, the sampling period of the Simulink block diagram. Here,
34
sampling period is defined as the time required to execute one entire cycle of the Simulink
block. The IOBlock determines the sampling period by averaging the time taken to run a
user-specified number of cycles of the Simulink block diagram. An averaged sampling period
is not expected to provide the exact sampling period for each Simulink block cycle and its use
is not recommended when hard real-time constraints are to be enforced.
3.4.
Integration of Simulink and PIC
When blocks from the PICLibrary are used in the Template.mdl model file, a sequence
of operations specified by the TotalCompile function are performed before the Simulink block
diagram begins to run. The main role of the TotalCompile function is to program the PIC
microcontroller and to facilitate serial communication between MATLAB and the PIC microcontroller. As seen in Figure 3.3, the TotalCompile function is set as a “Simulation start
function” of “Callbacks” option in the “Model properties” of Template.mdl.
The TotalCompile function performs the following sequence of tasks. First, global variables
are declared and used to share data with Simulink blocks of PICLibrary. Second, sensor and
actuator blocks used in the Simulink diagram are matched with the corresponding Simulink
blocks in the PICLibrary. Furthermore, each block is categorized as a sensor or an actuator and
its name is stored in an array of sensor/actuator structures with the specified block properties.
The sensor/actuator array information is also used when data is serially communicated. Third,
using the sensor/actuator block information gathered in the previous step, a PIC assembly
code is generated. This step is facilitated by the fact that for each sensor/actuator block in the
PICLibrary the corresponding PIC assembly code has already been created and saved as an mfile. Fourth, a portion of the IOBlock MATLAB code is generated to allow serial communication
between MATLAB and the PIC microcontroller. This MATLAB code sends and receives the
same amount of data that the PIC microcontroller receives and sends, respectively. Fifth, the
PIC microcontroller is programmed in two steps: i) using the MPASM assembler the PIC
assembly code, generated in step 3 above, is converted to the corresponding PIC HEX code
and ii) using the IC-Prog the PIC HEX code is downloaded to a PIC microcontroller installed
on a PIC-PG2C programmer. Figure 3.9 shows a flow diagram of the three steps involved in
35
programming the PIC microcontroller.
PIC assembly code is
generated by TotalCompile
PIC assembly code is converted
to PIC HEX code by MPASM
PIC HEX code is downloaded
by IC-Prog via the serial port
Figure 3.9: Flow diagram of programming the PIC microcontroller
After the TotalCompile function completes its sequence of tasks, the Simulink block diagram
begins to execute when the user confirms that the PIC microcontroller has been removed from
the PIC-PG2C programmer and properly installed onto the PIC development board. At this
stage, serial communication between the PIC microcontroller and MATLAB also begins. If
Simulink is stopped and needs to be run again, without any changes to the configuration of
the PIC microcontroller I/O pins, then the PIC microcontroller need not be reprogrammed.
Once the Simulink block diagram begins to execute, the PIC and PC exchange sensory
feedback and actuator commands via serial data communication. Specifically, special function
8-bit PIC registers are used for the serial communication of sensor/actuator data [42, 46]. The
IOBlock receives/transmits data from/to the PIC and stores the data in sensor/actuator global
variables.
3.5.
Example—DC Motor Control
To illustrate the functionality and capability of the data acquisition and control hardware
and software of this dissertation, position control of a DC motor is performed. Specifically, a
DC motor test-bed is interfaced with a PIC-based data acquisition and control board and a
control algorithm is implemented using Simulink and the MATLAB toolbox for the PIC microcontroller. The DC motor test-bed, shown in Figure 3.10, consists of an armature controlled
DC motor, instrumented with a continuous rotation potentiometer, and a power module. The
potentiometer output is used to obtain the necessary feedback signals and to provide a real-time
36
display of the angular position of the motor. To control the angular position of the DC motor,
the PIC microcontroller applies a controlled voltage signal produced by a control algorithm
running on Simulink.
Digitized sensor data
from PIC
Analog sensor data
Analog control output
DC motor and power module
Control output
from Simulink
PIC development board
Simulink block diagram
Figure 3.10: Hardware layer schematic
In this dissertation, a proportional-integral-derivative (PID) controller [54] is used for the
angular position control of the DC motor. The functionality of various Simulink blocks used in
Figure 3.10 (see Figure 3.11 for an exploded view) is as follows. The A2D Pot block serves as
an A2D block to convert the analog output of the potentiometer into an 8-bit digital data. The
PID Controller block encapsulates the standard PID control algorithm. The inputs to the PID
Controller block are: i) the desired angular position of the DC motor and ii) the potentiometer
signal (the digitized output of A2D Pot block). The output of the PID Controller block is a
controlled voltage signal to be applied to the motor. In Figure 3.11, the PID Controller block
output is processed by the PWM Motor block which serves as a PWM block. Note that the
power amplifier module of the DC motor shown in Figure 3.10 requires a ±5VDC to drive the
DC motor. Accordingly, the PID control algorithm outputs a ±5VDC control signal. However,
the PIC microcontroller can output only 0—5 VDC using the PWM output. Thus, the ±5VDC
output of the PID controller is appropriately transformed to command the PWM Motor block
with a 0—5 VDC command signal. Finally, by processing the PWM output from the PIC
microcontroller using a simple operational amplifier based circuitry, the 0—5 VDC PWM
output is converted into a ±5VDC signal for input to the power amplifier module.
An analytical model of the DC motor under PID control, yielding a third-order closed-loop
transfer function [54], is used to determine numerical values of the PID controller gains. Specifically, by requiring the closed-loop transfer function to have: i) a pair of complex-conjugate
37
Figure 3.11: Simulink block diagram: Exploded view
poles with a damping ratio and natural frequency of 0.69 and 1.93, respectively, and ii) a third
real pole at -80, the PID control gains are computed to be KP=1.43, KI=1.97, and KD =0.5.
This analog PID controller is implemented using Simulink’s ODE4 (Runge-Kutta) algorithm
with a sampling period of 0.13 second. For the computed gains, the experimental response
exhibits an average 2 percent settling time of 5.9sec and a percentage overshoot of 18.25%.
For comparison, the theoretical values for the 2 percent settling time and the percentage overshoot are 3sec and 14%, respectively. Figure 3.12 shows a sample experimental response of
the DC motor angular position under PID control implemented using the framework of this
dissertation.
Figure 3.12: DC motor angular position tracking response
38
3.6.
Conclusion
This dissertation provided an overview of a low-cost data acquisition and control toolbox
that consists of the newly developed Simulink library for PIC microcontrollers. Serial communication capabilities of the PIC microcontroller and MATLAB allowed programming of the PIC
microcontroller from MATLAB and exchange of sensory data and actuation signals between
the PIC microcontroller and MATLAB. The capabilities of this low-cost data acquisition and
control system were illustrated through a DC motor angular position control experiment.
Download PDF