1. Data Acquisition System and Light Weight Process Control
By
Charlie Weld
This Report is submitted in partial fulfilment of the requirements of the Honours Degree in Electrical
and Electronic Engineering (DT021) of the Dublin Institute of Technology
May 31st
2011
Supervisor: Dr. David Dorran
School of Electrical Engineering Systems School of Electronic & Communications Engineering
2. i
Declaration
I certify that this thesis, which I submit in partial fulfilment of the requirements of the Honours
Degree in Electrical and Electronic Engineering (DT021) of the Dublin Institute of Technology, is a
product of my own work and that any content included that relates to the work of other individuals,
published or otherwise, are acknowledged though appropriate referencing.
Signed:
Date:
3. ii
Acknowledgements
I would like to thank my supervisor Dr. David Dorran for his support and guidance throughout this
project. I am grateful to the Dublin Institute of Technology for making this thesis possible. Finally I
would like to thank my friends and family.
4. iii
Abstract
This project is an embedded systems development project and aims to refine and further develop an
existing system. The existing system was designed to implement data acquisition and signal
processing which could be carried out by students studying signal processing in Dublin Institute of
Technology College. The data acquisition system consists of inexpensive hardware that is capable of
signal processing and analysis. The system was programmed using the MPLAB IDE and the Matlab
software packages. The software development for the system was implemented without fully
reviewing the hardware with the result that the system is not fully utilizing the hardware. The
current project aims to improve and further develop the data acquisition system to increase the
efficiency of the hardware and increase the functionality of the system by implementing digital
control. The current project reviewed both the hardware and software components of the data
acquisition system and improved the systems efficiency and overall software structure. The
improved software structure will benefit students making further developments to the system.
Digital control was implemented on the system and will provide students with a light weight and
portable digital controller.
5. iv
Table of Contents
Declaration...............................................................................................................................................i
Acknowledgements................................................................................................................................. ii
Abstract.................................................................................................................................................. iii
1 Introduction .........................................................................................................................................1
1.1 Project Background.................................................................................................................1
1.2 Need for the Current Project ..................................................................................................1
1.3 Project Results ........................................................................................................................2
1.4 Overview of Report Chapters..................................................................................................2
1.4.1 Review Chapter...............................................................................................................2
1.4.2 Implementation Chapter.................................................................................................3
1.4.3 Conclusion Chapter.........................................................................................................3
2 Review of Existing System...............................................................................................................3
2.1 DAQ Functions Review............................................................................................................5
2.1.1 Sampling Analogue Signals..............................................................................................6
2.1.2 Sampling Timer ...............................................................................................................6
2.1.3 Transmitting Data to Matlab...........................................................................................7
2.1.4 Receiving Data from Matlab ...........................................................................................7
2.1.5 Writing Data to Memory.................................................................................................9
2.1.6 Sending Data to the DAC.................................................................................................9
2.2 DAQ Extra Functionality..........................................................................................................9
2.2.1 Digital Control ...............................................................................................................10
2.2.2 Higher Resolution..........................................................................................................10
2.3 Matlab Functionality Review ................................................................................................11
2.3.1 User Interface................................................................................................................13
2.3.2 Sending Data to the DAQ..............................................................................................13
2.3.3 Sampling and Plotting Data...........................................................................................14
2.4 Additions to Matlab Program ...............................................................................................15
2.4.1 Higher Resolution Signals..............................................................................................15
2.4.2 Graphical User Interface ...............................................................................................15
2.5 Review Conclusions...............................................................................................................15
2.5.1 DAQ Functionality.........................................................................................................16
2.5.2 Extra Functionality on DAQ...........................................................................................16
2.5.3 Matlab Functionality.....................................................................................................17
6. v
3 Implementation ............................................................................................................................18
3.1 Project Hardware and Software............................................................................................19
3.1.1 Hardware.......................................................................................................................19
3.1.2 Software........................................................................................................................20
3.2 Initial Setup and Testing........................................................................................................21
3.2.1 Hardware Setup ............................................................................................................21
3.2.2 Software Setup..............................................................................................................22
3.3 Implementation of DAQ Program.........................................................................................23
3.3.1 Sampling Analogue Signals............................................................................................25
3.3.2 Transmitting Data to Matlab.........................................................................................25
3.3.3 Receiving Data from Matlab .........................................................................................25
3.3.4 Writing Data to Memory...............................................................................................28
3.3.5 Writing Data to DAC......................................................................................................30
3.4 Additionally functionality for DAQ........................................................................................30
3.4.1 PID Digital Control.........................................................................................................30
3.4.2 Sending IEEE Floating Point Values to the DAQ............................................................32
3.5 Implementation of Matlab Program.....................................................................................33
3.5.1 Handling User Input Arguments....................................................................................33
3.5.2 Configuring the Data Acquisition Board with Basic Parameters...................................34
3.5.3 Sampling and Plotting ...................................................................................................35
3.6 Matlab additionally functionality..........................................................................................36
3.6.1 Improved Resolution.....................................................................................................37
3.6.2 Adding an Analogue Channel........................................................................................37
3.7 Testing & Validation..............................................................................................................37
3.7.1 Backwards Compatibility...............................................................................................38
3.7.2 Function of Improved System.......................................................................................38
3.7.3 Digital Control Tests......................................................................................................38
3.8 Summary of Implementation Chapter..................................................................................41
3.8.1 Implementation of the DAQ software ..........................................................................41
3.8.2 Additional Functionality for DAQ..................................................................................42
3.8.3 Implementation of the Matlab Suggestions .................................................................43
3.8.4 Matlab Addition Functionality ......................................................................................44
4 Conclusions & Future Work ..........................................................................................................44
4.1 Summary of Project ..............................................................................................................44
7. vi
4.2 Critical Analysis of Methodology ..........................................................................................45
4.3 Future Work..........................................................................................................................46
4.3.1 Future Work on Interface .............................................................................................46
4.3.2 Future Work on Extra Functionality..............................................................................46
4.3.3 Refinements..................................................................................................................46
4.4 Final Conclusions...................................................................................................................47
References ..............................................................................................................................................1
Appendix B. Matlab Program Code.....................................................................................................2
Appendix C DAQ Program Code and Libraries ...................................................................................3
8. 1
1 Introduction
This project is focused on the development of an embedded system which will serve as an
educational tool for students studying at DIT College. The original system was aimed at students
studying signal processing but with the implementation of this project control students can benefit
from the data acquisition system as well.
This chapter will introduce the background of the project and outline the main reasons why it was
carried out. Section 1.1 will give an overview of the background of the project; section 1.2 will
outline the main reasons why the system needed to be upgraded. The results of the project will be
briefly discussed in section 1.3 and finally section 1.4 with give and overview of the rest of the
report.
1.1 Project Background
The original project was developed to give students an easy way to carry out signal processing
techniques. The college provides data acquisition systems in some of the computers in the college.
These systems are fixed to the computers and are also very expensive. Due to their price they
cannot be distributed among the computers in the college. The solution to this problem was to build
a light weight data acquisition system that was portable. This was implemented using an inexpensive
microcontroller that was able to communicate with a PC through a serial connection. The hardware
was mounted on a Printed Circuit Board (PCB). The software used to program the microcontroller
was written in C language. Matlab was used to configure the microcontroller with some basic
information such as the sampling rate and the number of samples to capture. Matlab could then be
used to plot the data and carry out signal processing.
1.2 Need for the Current Project
Since the data acquisition system was put together very quickly the programming was poorly
structured and commented which made it difficult to understand. It is important to provide a well-
structured and properly commented program when it is to be used by students. If the program is
well written and well explained it can give students a better understanding of how the system works.
Therefore it would be beneficial to improve the quality of the programs associated with the data
acquisition system.
The second reason the current project was carried out was to provide extra functionality. This
functionality would be in the form of digital control. This will help students get a better
9. 2
understanding of control systems. The controller would also be portable meaning students can use it
with many of the process simulators in the college.
1.3 Project Results
The current was implemented successfully to provide the student with well-structured and
commented program code both in C language on the microprocessor and in Matlab language for the
interface program. This section took up more time than was originally expected but during this time
addition features were implemented that benefit students or even other users of the data
acquisition system. These features include higher resolution numbers used in the system, an extra
analogue channel can be used for sampling signals, increased the amount of storage memory
available for data and implemented priority interrupts. These features will allow students capture
and analyse signals more accurately and store more data on the system.
The control aspect of the project was implemented throughout the second half of the project when
the program code had been properly structured. During this phase of the project the code was still
been developed but was more focused on bringing the system together to produce the finished
product. The control implementation is in the form of a Proportional, Integral and Derivative (PID)
algorithm. This was selected because control engineering in the College is generally concerned with
PID control. Although the PID control algorithm is treated as a pluggable module and can easily be
removed or modified to implement a different control algorithm.
1.4 Overview of Report Chapters
The following report will be split into a review chapter, implementation chapter and a conclusion
chapter. This section will outline the content contained in each chapter.
1.4.1 Review Chapter
The review chapter will focus on the existing data acquisition system and suggest ways to improve it.
These suggestions will be reviewed and implemented if they are useful to the system.
The chapter will be broken into the review and then a conclusion of the review. The review will
examine the software on the microprocessor and suggest possible improvements. The Matlab
software will also be examined to determine how the implementation should be handled.
The review conclusion will summarise the main points made in the review and conclude on the
general direction the project implementation will take.
10. 3
1.4.2 Implementation Chapter
This chapter will follow the same general layout as the review section; it will discuss how the project
plans were implemented and discuss the various problems that were encountered and how these
problems were handled. The final section will discuss the tests performed to ensure the project
meets the goals outlined.
1.4.3 Conclusion Chapter
This chapter will summarise the project, analyse the methodology used throughout the project and
finally outline future improvements that could be made to the project.
2 Review of Existing System
This chapter will review the Data Acquisition Board (DAQ) prior to commencing the project. The aim
will be to examine the hardware and software in the project to determine how it can be improved
and further developed. The devices that are programmed are the DAQ microcontroller and Matlab
on the communicating PC. This chapter will review the microcontroller software first and then the
Matlab software program. The objective of this chapter is to determine firstly any problems with the
software functions, then any weaknesses in the program code structure and commenting. Finally
suggestions to improve system functionality will be discussed. These suggestions will include the
necessary functionality such as digital control and optional functionality that could improve the
system.
The figure 2-1 is shown below and gives an overview of the data acquisition system.
11. 4
Figure 2-1: Overview of Data Acquisition System
Data Acquisition System Microcontroller
Sample Analogue
Signals and
Converter to
Digital Value
Convert Digital
Value to Analogue
Signal
Matlab
User Input
Plot Sampled Data
12. 5
2.1 DAQ Functions Review
This section will outline the main functionality of the DAQ, any problems with its functions and
finally suggest ways to improve upon them. The main functions outlined in this section are:
1. Sampling Analogue Signals
2. Transmitting Samples to Matlab
3. Receiving Data from Matlab
4. Writing Data to Memory
5. Sending Data to the DAC
Figure 2-2 below shows a flow chart of the DAQ functions
Figure 2-2: DAQ Functional Flow Chart
Main
Timer 0
Overflow?
Sample Analogue
Channel
Send Sample to
Matlab
Read Data from
Flash
Send Data to DAC
ADC
Transmit Register
Flash Memory
DAC
Yes
No
Jump To
ISR
Voltage Signal
IN
To Matlab
Voltage Signal
OUT
Return From ISR
13. 6
2.1.1 Sampling Analogue Signals
The first step in a data acquisition system is to sample analogue signals and convert them to digital
values. There are two important functions used to capture an analogue signal; the first is an
Analogue to Digital Converter (ADC) which will carry out the task of converting the signal voltage to a
digital representation. The second is a sampling timer that will capture the analogue signal at the
right period in time.
Analogue to Digital Converter on the DAQ
The ADC implementation on the DAQ is working but the acquisition time given in the function is very
large which seriously reduces the maximum sampling rate. The acquisition time is the period the
ADC module will wait before the conversion begins.
ADC Suggestions
The ADC module allows for a programmed acquisition time. This should be implemented to improve
the sampling rate.
2.1.2 Sampling Timer
On many microcontrollers the sampling rate is implemented with interrupts.
Note on Interrupts:
Interrupts in programming are a method of allowing high priority services to be run regardless of
where the current program is. For example consider plugging in a USB stick to most computers. After
a second or two a file manager (Windows Explorer, Mac Finder, etc.) will open with the contents of
the USB stick. This is an interrupt where the file manager has stopped the users from what they were
doing to show them something else. In programming interrupts are the same context; they stop the
current process to carry out another process which is given a high priority. The service that the
interrupt carries out is called the Interrupt Sub-Routine (ISR).This ISR will be used to sample an
analogue signal and then transmit it to Matlab.
Timer Interrupt
A timer is used to implement a fixed sample period with the intention of setting up an accurate
sampling rate which is very important in data acquisition systems. The timer uses a 16-bit integer
value which is incremented on every fourth clock cycle (Fosc / 4). When the timer reaches it
maximum value (2^16 = 65,535) it will overflow to zero on the next increment. When the timer
overflows the interrupt is called and the analogue signal is sampled. Before leaving the ISR the timer
must be reset to the appropriate value to achieve the correct sample period. This method will give
14. 7
an accurate sample period once the execution time of the code does not deviate. While this
deviation might be small in comparison to the total execution time of the ISR, it would be more
accurate to have the timer separate from the ISR execution time.
Timer Interrupt Suggestions
To improve the sampling rate accuracy the compare module could be used on the microcontroller.
This is a module that holds a 16-bit value and compares it against a timer value. The timer will start
incrementing from zero and will stop when it reaches the same value as the compare module. When
the values are equal the timer is reset to zero, an Analogue to Digital conversion is started and an
interrupt can be called. The importance of this method is that the timer starts again immediately
after being reset. This provides a very accurate sampling period and thus a very accurate sampling
rate.
2.1.3 Transmitting Data to Matlab
When an analogue conversion has been completed it is sent to Matlab to store and plot it. This
allows users to plot the sampled data and since it is stored it can be modified. The hardware module
that sends the data from the DAQ to Matlab is a Universal Synchronous Asynchronous Transmitter
Receiver (USART). It is configured in asynchronous mode because sending and receiving data are
treated as separate events in this system. The USART can send a single byte at a time which means
the data must be formatted into 8-bits.
Sending data to the USART is simple in the microcontroller, the USART uses a transmit register to
store the data byte and send it via serial communications. On every sample interval the analogue
signal is sampled by the ADC and then stored in the transmit register which sends it to Matlab. There
are no problems with the implementation of data transmission on the original DAQ.
2.1.4 Receiving Data from Matlab
When the data acquisition system is properly configured data is sent and received from Matlab to
the DAQ. This means that users only deal with the Matlab side of the system and pass configuration
parameters and data to Matlab which in turn will send this data to the DAQ. The DAQ will receive
the data and use it in two ways. The first is the configuration parameters sent from Matlab which are
specified by the user, these include sampling rate, number of samples to capture and other options
that the DAQ uses to properly operate. The DAQ also receives raw data which will be stored in
memory on the microcontroller and will then be sent to the Digital to Analogue Converter (DAC) to
output a voltage signal from the system. When the DAQ has received the data it will continue
normal operation until the user decides to download different settings or data.
15. 8
Transmitting data via the USART is a straight forward process; the same is not true for the USART
receiver. The USART receiver can only buffer two bytes at a time before the first byte must be
serviced. If the third byte arrives at the USART before the first byte is serviced an error will occur and
the USART will stop receiving data. This is called an overrun error and it can be detected by a flag in
the USARTs status register.
Download Interrupt
The previous ISR was used to carrying the main function of the system which is to sample analogue
signals and output data to the DAC. To configure how the acquisition system should behave an
interface in the form of Matlab is used. This means users do not have to reprogram the
microcontroller every time a different operation is required. To communicate between Matlab and
the Data Acquisition Board (DAQ) serial communications are used. To transmit data to Matlab the
USART transmitter is used and the data bytes are simply stored in Matlabs buffer for plotting.
However, receiving data is more complex and requires more attention to ensure that errors do not
occur during reception.
USART Reception ISR:
The reception of a data byte from Matlab causes an interrupt to occur. The microcontroller jumps to
the USART reception ISR to service the data byte. The microcontroller then returns to the main code
and continues with its previous operation. This is repeated for every data byte that is received by the
USART. There are numerous problems with this approach to capturing the data transmitted from
Matlab. Jumping to and from the ISR for every byte of data is not very intelligent because the data
bytes are coming in one stream. This means that Matlab sends the data to the DAQ until all the
necessary data is sent, at this point the DAQ should resume in whichever mode of operation the user
selected. The other problem with this approach is that for every configuration parameter (sampling
rate, number of samples and user options) a separate ‘if’ statement is required and this can get very
messy and difficult to understand. Especially since the current project seeks to extra functionality
which will no doubt lead to more parameters that are needed to configure the DAQ.
USART Reception ISR Suggestions:
Considering the problems outlined in the previous section the first improvement should be to
capture all the data transmitted in one ISR. That is to jump to the ISR service all the data bytes and
then return to the main program and resume operation. This will save time jumping to and from the
ISR which will lead to faster download rates and a better user experience because of it. This also
could be captured by a function outside of the ISR. The benefit of this is for the programmer and
16. 9
future developers. By putting the download in a separate function the main script is reduced leaving
troubleshooting the main program an easier task.
To address the number of different configuration parameters an array could be used to capture all of
them and then use a separate function to initialise each one after the download has completed. This
allows more modular code which is very important if other programmers will be maintaining or
developing the code further.
2.1.5 Writing Data to Memory
When the DAQ downloads data from Matlab it will store this data in memory on the microcontroller.
The microcontroller uses flash memory and has up to 64KB of available flash memory.
Current Memory Function
On the original project software there was a limitation on the amount of flash memory that could be
used to store data. This limitation was about 4KB including the actual program code. The problem
occurs when writing to a memory address above 0x4000h (h is for hexadecimal).
Memory Function Suggestions
The following suggestions are actions to solve the problem as opposed to actual solutions. The first
suggestions would be to review the function documentation for writing data to flash memory. If that
does not work the datasheet discusses flash memory in detail and even goes through the steps
needed to write data to flash memory. This should provide information on the problem above.
2.1.6 Sending Data to the DAC
The last step in the DAQ system is to send out an analogue signal using the DAC. This signal could be
a modified version of the signal that was sampled by the ADC, or could be a user created signal.
After a review of the DAC function there are no obvious changes that would increase its functionality
or its efficiency. A problem might be detected during the implementation phase of the project which
would be discussed in the implementation section regarding the DAC.
2.2 DAQ Extra Functionality
Improving the existing system is a large part of the current project. To take the project further than
this is to add extra functionality and user friendless. Adding functionality should not compromise the
usability of the original system. The main expansion is to add control functionality by implementing a
digital Proportional, Integral and Derivative (PID) algorithm. This would allow the Data Acquisition
System (DAQ) to act as a digital controller. Due to the relatively low performance of the
microcontroller it will not be able to control process with very low time constants. The DAQ is
17. 10
designed as an educational tool and as such is not required to be an extreme system. The
microcontroller will comfortable be able to carry out control tests in the college to demonstrate to
students the different aspects of control.
2.2.1 Digital Control
As mentioned in the introduction above the main functionality to add is digital control. To achieve in
the original system the following changes must be made:
1. Add a PID algorithm that can be called when control mode is selected
2. A function that will update the error signal
3. A Matlab function to plot the process variable and the set point value
4. Different methods of changing the set point value
5. A method of downloading and storing the P, I and D parameters
The PID algorithm can vary in complexity and once the system is configured properly the algorithm
can be easily changed. The PID function will take the error value and return the output that is
required to correct the plant. In this way the PID function can be treated as a pluggable module
which can be switched out for a different control algorithm.
The function to update the error will essentially subtract the value read from the Analogue to Digital
Converter (ADC) from the set point value.
The plot the progress and status of the control system the plant output variable and the set point
variable need to be plotted in Matlab. It could also be possible to include a real time plot of the two
variables, this will allow users to change the set point and view the resulting plant response.
The set point value is the reference signal the process should follow. For example if the controller
was controlling the temperature in a room the set point would be the value set at the thermostat.
This is the desired value of the room temperature. The control set point could be implemented a
number of different ways for example:
1. An analogue value that was outside the controller
2. A signal could be downloaded to act as the set point
3. A set point value that change after a specified number of sample intervals
2.2.2 Higher Resolution
The original project uses a single byte to store a single value, this limit a value to 256 different levels
which is a low resolution. The Analogue to Digital Converter (ADC) has a resolution of ten bits (2^10
= 1024 levels). This is four times the resolution of a single byte, and it would benefit students to have
18. 11
higher resolution numbers. This would allow students to capture signals more accurately and
therefore signal analysing will be more accurate. The down side is speed since it will take twice as
long to transfer each value through the system. Although this will not affect the speed of the ADC
since it uses two 8-bit registers to store its resultant sampled value. The speed hit will be mainly
seen when transferring data to Matlab. The USART is only an 8-bit device therefore two values will
be needed to plot a single value in Matlab. To support the inclusion of a higher resolution is the
resolution of the Digital to Analogue Converter (DAC) which uses 12-bits of resolution. This will
higher resolution signals (4096 levels) to be sent to the DAC.
2.3 Matlab Functionality Review
The Matlab program is used to send configuration parameters and data to the DAQ. Matlab will also
capture the sampled data from the DAQ and plot this data. The review of the existing Matlab
program will be carried out on the essential functions that it carries out. Matlab firstly is used to take
the user input arguments, write the configuration parameters to the DAQ and finally receive the
sample data and plot it. The following sections will be used to review the existing system and
suggests changes that should be made to improve the structure, readability and if possibly efficiency
of the program.
The following flow diagram shows the overall
19. 12
Figure 2-3: Matlab Functional Flow Chart
User Input Arguments, Options and Data
Process User Input to Select DAQ
Mode and Options
Check for Available Serial Ports and
Open the First one Available
Configuration Settings and DATA for
the DAQ
Send Configuration Parameters and
DATA to DAQ
DAQ
Receive Data Samples from DAQ DAQ
Store Samples in Variable
“Sampled_Data”
Plot Sampled Data On Each Loop
20. 13
2.3.1 User Interface
This is the first section of the program and is responsible for taking the user input arguments and
options and with this information selecting the correct mode of operation and setting the necessary
options to allow the rest of the program carry out the requested user operation. The existing system
deals with the user input arguments and options in a satisfactory and easy to understand way.
However, to allow for control parameters to be entered by the user this section must be modified.
Suggestions for Improvement:
A suitable method of accept control parameters could be implemented by storing the parameters in
an array that could be passed to the download section of the program. Another modification that
should be considered is to separate the user interface from the rest of the program. This could be
done by placing it in separate function.
2.3.2 Sending Data to the DAQ
Matlab is used as the interface to the DAQ and as such needs to be capable of communicating the
user specific settings such as the sampling rate to use. Matlab sends data as unsigned integers to the
DAQ using a virtual serial port object that transfers data via a USB cable. Matlab will send both
configuration parameters and raw data to the DAQ. This section will review the necessary functions
needed to send data to the DAQ.
Constructing a Serial Port Object
The communication standard used between Matlab and the microcontroller is RS232 serial
communications. In Microsoft operating systems a serial port is labelled ‘COMN’ where N is the
number of the port (e.g. COM1, COM2, COM3, etc.). In the existing program the available serial port
is found by first checking an arbitrary port number (e.g. COM1000). This check returns a list of
available serial ports which are then probed to check if one could be used. This was a very long
winded approach to finding an available serial port object and a waste of programming time.
Although it is a reliable method of finding available serial ports and should not be disregarded unless
a better solution is found.
Suggestions for a Better Check for Available Serial Ports
There are two approaches that could be used to improve the program regarding serial port
detection:
1. Separate the current code into its own function that will return a serial port object
2. Research the Matlab documentation to find a simpler and more efficient solution
21. 14
Configuring Data to Send to the DAQ
This section configures the parameters sent to the DAQ such as the sampling timer and the number
of samples to send. These are both 16-bit numbers and must be separated into two 8-bit numbers
before they can be sent to the DAQ. In the existing program this section is integrated into the data
sending section which could make it more difficult to understand especially if more parameters were
been sent to the DAQ.
Suggestions for Improvement
The data configuration and data sending should be separated for two reasons:
1. It is easier to identify which parameters are being sent to the DAQ and how they are
configured
2. Sending the data to the DAQ in a single section will speed up the data transfer and thus
reduce the downtime of the DAQ.
Writing Data to DAC
This is one of well-structured sections of the Matlab program. It is laid out to write data to the
acquisition board sixty four bytes at a time, and then write any bytes that are left over. The main
issue with this piece of code is that it is difficult to understand at first and could be improved by
commenting.
Suggestions for Improvement
This section could be improved with the use of comments, but there is no functionally problem with
the code.
2.3.3 Sampling and Plotting Data
This is one of the biggest sections of code in the Matlab program and by far the most difficult to
follow. It is an important section and is used to capture the data sampled by the ADC of the
acquisition system. The captured data is read from the Matlab buffer and plotted each time it is read
from the buffer. When the serial port object is created it uses a structure to hold its important
settings such as baud rate, input buffer size, output buffer size, bytes available, etc. The bytes
available parameter is used in the existing program to determine how many samples have been
captured up to that point. These samples are then read and plotted. The data bytes are removed
from the buffer when they are read. This approach to plotting the samples tends to be very
unsmooth because the data is plotted in large parts of the signal.
22. 15
Improvement to Sampling and Plotting Section of Matlab
It would be much clearer to separate the two functions into different sections although this might
very inefficient because sampling and plotting happen in the same loop. The data is sampled and
then plotted immediately and the loop continues this way.
A method of improving the smoothness of the plotting could be implemented to provide the user
with a more graphical pleasing view of the sampled data.
2.4 Additions to Matlab Program
The Matlab functional review in the last section discussed the problems with the current system and
provided suggestions to improve them. This section will outline some of the extra functionality that
could be added to the Matlab program. The first addition that will be outlined is the use of two byte
values in the program to allow a higher resolution and more accurate signals. A Graphical User
Interface (GUI) could be added to improve the user experience with the system.
2.4.1 Higher Resolution Signals
The existing system uses 8-bit values to represent the sampled signals; this limits the resolution of
the sampled signals to 20mV which is an acceptable resolution. Considering that the ADC has a
potential resolution of 10-bits (5mV) if would be useful to allow users capture higher resolution
signals for a more accurate signal analyses. The download of this is that the maximum sampling rate
will be reduced but it offers more functionality to the system.
2.4.2 Graphical User Interface
Once the system is in place and the main objective is completed and fully operational it would be a
nice feature to add a Graphical User Interface (GUI) to the Matlab script. This would allow users to
easily change configuration parameters without the need to learn the layout of the command line
function. However, this could be more difficult and time consuming that expected as a short review
of a Matlab GUI tutorial proved that it is a complicated process and can be very time consuming. [1]
The implementation of a GUI will be decided on near the end of the project.
2.5 Review Conclusions
This section will outline the main points of the review chapter. The section will follow the layout of
the review chapter to summarise the main faults of the original system and the suggestions
proposed to resolve these faults.
23. 16
2.5.1 DAQ Functionality
The following section will outline the problems with the DAQ functionality and give the suggestions
to improve upon them.
Sampling Analogue Signals
ADC needs to be re-written to improve sampling rate
Sampling period is not accurate and requires a fixed timer
Transmitting Data to Matlab
Transmitting data is handled efficiently
Could be structured better
Receiving Data from Matlab
Reception of data is handled poorly due to interrupt sub routine
Interrupt function is structured poorly and is difficult to understand
The ISR needs to be separated into its own function
Writing Data to Memory
The total memory space on the microcontroller is 64KB and only 4KB of this can be utilised on the
existing system.
The problem needs to be investigated by first referring to the datasheet section “Writing to Flash
Memory” and failing this to research the issue on the internet.
Sending Data to the DAC
The functionality of the DAC is acceptable and does need does functionality improvements. The
function needs to be modified to deal with 12-bit numbers.
2.5.2 Extra Functionality on DAQ
This section will summarise the extra functions that will be added to the DAQ. The first is digital
control and the second is a higher resolution values in the DAQ.
Digital Control
To implement digital control on the DAQ a PID algorithm will be used. The algorithm will be based on
positional PID control; this type of control is based on the actual error value and it calculates the
output needed to correct the plant. In contrast another form of PID is called vector control which
uses the change in the error value to determine the corrective action required.
The following conditions will be implemented to allow the DAQ operate as a digital controller:
24. 17
Set point value that can be changed by software or externally through the ADC
Second ADC channel to read the output of the process
Error function to calculate the difference between the set point and the process output
Higher Resolution Samples
The existing data acquisition system samples analogue signals and converts them to 8-bit numbers,
this only provides a range of 0 – 255 for each value. This could be improved by using two bytes for
each value, this would allow the system to utilize the ADCs full resolution of 10-bits (0 – 1023).
2.5.3 Matlab Functionality
This section will summarise the review of Matlabs functionality on the existing system. Matlab is
used as the interface to the data acquisition system and is also used to analyse the data sampled
from the ADC. Matlabs functions are divided into:
Take user inputs and select the DAQ operating modes and options
Configure the user settings and data before writing them to the DAQ
Take the sampled data from the DAQ and store it in memory and plot this data
User Interface
The user interface accepts arguments and options used to select the correct mode of operation. The
user interface contains a section that configures parameters and options that are used by the system
to function properly.
This section needs to be commented better to help other programmers understand what it is doing.
The section will also be modified to deal with the configuration parameters needed for the DAQ to
carry out its control operation.
Sending Data to the DAQ
This section of the program involves the following functions:
Create and Open a Connection to the DAQ
Configure the parameters and data that will be sent to the DAQ
Send the configuration parameters and the data to the DAQ
Opening a connection to communicate with the DAQ is implemented by using a very long winded
and difficult to understand. This needs to be addressed by investigating the way Matlab handles
serial port objects.
25. 18
The existing system configures and sends the parameters used by the DAQ before sending the actual
data to the DAQ. This could be improved by separating the configuration section and the sending
section. This would make it more obvious what configuration parameters are used by the DAQ. Also
sending all the information to the DAQ in one section means that it is not waiting for configuration
to finish before receiving the rest of the data.
Sampling and Plotting Data from DAQ
This section of the Matlab program stores the sampling signal from the ADC and plots it to allow the
users to view the signal. The section implements storing data and plotting and these to functions are
very much implemented together.
The improvements suggestion to this section will be to use better comments and try to section it as
much as possible to help others understand what is happening. To allow this section sample and plot
higher resolution numbers it will have to be modified to read two values from the DAQ, convert the
two values into a single 16-bit number and then plot this on a graph that is updated after every
sample.
3 Implementation
The review section has outlined the requirements of this project in terms of the modifications that
are needed to the base of the project. Then the additions that are needed to meet the objective of
this project. The main aim of the improvement portion of the project is to producing program code
that is well structured, appropriately commented and as modular as possible. In this context
modular program code means that each function the code carries should be in isolation from the
rest of the code. This provides a flow diagram of the program where each function has one input and
one output. This approach is intended to make this Data Acquisition Board (DAQ) as easy to modify
as possible. This will be applied to both the Matlab portion of the project and the microcontroller
programming.
The second aspect of the project is improved functionality through extra operating modes such as
control mode. Higher resolutions to give users a greater range of uses for the DAQ and possible a
Graphical User Interface (GUI) to improve the ease of use of the system
The following section will follow closely the structure of the review section. This will provide a link
between the work that was expected to be carried and the actual work that was done during the
project duration.
26. 19
3.1 Project Hardware and Software
Since this project was started by a previous program developer there will be a learning curve
required before the current project can start improving upon the existing one. This will consist of the
hardware and software setup and then continue with some basic software testing. The initial part of
the project will focus mainly on programming the microcontroller since that is the component that
actually carries out the task of sampling analogue signals and sending data to the Digital to Analogue
Converter (DAC). When the project moves onto sending the sampled signal to Matlab, programming
at this end will commence.
3.1.1 Hardware
The hardware setup was minimal because it was already soldered together onto a Printed Circuit
Board (PCB) with the appropriate terminals, indicator LEDs and properly fused. This hardware setup
section will give an overview of the hardware used and outline the most relevant features used for
this project.
The project will use the following hardware:
Table 1: Project Hardware Overview
Hardware Main Features Manufacture Comment
PIC18F4620 MCU 8-Bit Architecture
64KB Flash Memory
8MHz Clock
Microchip Technology
Inc.
Main Microcontroller
UB232R USB to
Serial Converter
USB 2.0 Compliant FTDI Ltd Serial Communications
Device
MCP4921/4922
DAC
12-Bit Resolution
SPI Interface
Microchip Technology
Inc.
Outputting Analogue
Signals
Pickit 2
Programmer /
Debugger
Byte Writes
Debugging
Microchip Technology
Inc.
Main Debugger /
Programming used
PIC18F4620
The microcontroller is the main hardware component of the project and includes many of the
features used in the project. These include:
1. Analogue to Digital Converter (ADC)
27. 20
The ADC has 10-bits of resolution and thirteen input channels that can be used to sample a signal.
The ADC samples an analogue channel for a given acquisition time and then converts the voltage
sampled and stores the result in two 8-bit registers.
2. Universal Synchronous Asynchronous Transmitter Receiver (USART)
The USART is used for serial communications and can transfer and receive data in 8-bit bytes. It is an
important component of the project and is used extensively for transmitting and receiving data from
Matlab.
3. Flash Memory
The microcontroller houses 64KB of flash memory which is used primarily for storing the program
but also allows data to be stored. This will be used to store data before sending it to the DAC.
UB232R USB to Serial Converter
This is a very important device and will be used to communicate between Matlab and the
microcontroller using the RS232 serial communications standard. The device does not need to be
configured and therefore will not be a major part of the project. It is only mentioned to outline the
method of communication between the microcontroller and Matlab. This device allows users to
both power and exchange data using a USB cable which is convenient and transportable.
Digital to Analogue Converter (DAC):
This device is used throughout the project to send digital signals to a 0 – 5v range at the output of
the DAC. The DAC is a standalone device and communication is via SPI to the microcontroller. The
DAC supports up to 12-bits of resolution.
Pickit 2 Debugger / Programming
This device is used to write the program memory onto the microcontroller. It can write single bytes
to flash memory unlike internal flash writing which must write 64 bytes at a time. It is also used for
debugging the program and allows up to three hardware breakpoints. This device was used
extensively throughout the program and provided a very useful debugging tool which generally
allowed for quick troubleshooting.
3.1.2 Software
There are three software packages used throughout this project:
1. MPLAB IDE v8.36 from Microchip
2. MPLAB C18 C Compiler LITE version 3.36
28. 21
3. Matlab version 7.11.0.584 (R2010b)
4. Notepad++
MPLAB IDE
This software package is developed by Microchip to be used with their range of microcontrollers and
their Pickit programmers. It is a development environment for the microcontroller. This software
was used throughout this project for C programming and interface with the Pickit 2. The Pickit 2 is
also very useful for viewing register contents and flash memory. This allows an easier way of verify
writes to flash memory.
C Compiler
Microchip provides users with a LITE version of their C compiler for their range of 8-bit
microcontrollers. This was compiler used throughout the project. Even though it was a LITE version
there were no limitations meet while using it.
Matlab
This program was used for communication with the Data Acquisition Board (DAQ), storing the
sampled data and plotting this data.
Notepad++
This program is a text editor that was developed for C++ language programming (hence the name).
At the start of the project it was not used since the C programming could be done through MPLAB. It
was discovered by coincidence while research C related functions. It was tested and proved to be
very useful for C programming. This was used as the main development tool and then tested
through MPLAB. Notepad++ allows C code to be developed easily and very neatly.
3.2 Initial Setup and Testing
The previous section discussed the hardware and software that was used throughout this project.
This section will discuss the setup of the hardware and software. Once the hardware and software
are setup basic programming can begin.
3.2.1 Hardware Setup
The hardware is setup as follows:
1. The Pickit is connected to the Data Acquisition Board (DAQ)
2. The USB cable is plugged into the Pickit 2 and then into a PC USB port
3. Another USB cable is connected from the PC to the USB to Serial Converter
29. 22
The Pickit 2 will be used for programming the DAQ and the other USB cable will be for
communication with Matlab. There are four connectors on the DAQ; power, ground, ADC in and DAC
out. To provide an analogue signal into the ADC the power and ground connectors where connected
across a potentiometer which provided between zero and five volts at the ADC input.
3.2.2 Software Setup
The following steps were taken before programming the DAQ could begin.
1. Open MPLAB and select from the taskbar Project > Project Wizard
2. Select Device “PIC18F4620”
3. Select the MPLAB C18 Compiler
4. Choose where to save the project and name it
5. Click finish to open the project
6. Include the “p18f4620.h”
7. Include the “p18f4620.lkr”
The header file and linker script are found in the compilers install directory. For this project this was
C:/MCC18/h for header file and C:/MCC18/lkr for the linker script.
Once the project is setup the source code can opened to start programming. However, there are a
few compiler specific options that need to be specified before beginning C programming.
Compiler Specific Instructions
The following two lines of code are used to configure the internal clock and the watchdog timer.
#pragma config OSC = INTIO67
#pragma config WDT = OFF
The first line tells the compiler that the oscillator to use is the internal oscillator.
The second line is used to disable the Watchdog timer.
After these lines the C coding can begin. The next section will discuss some of the basic programs
used as an introduction into programming the microcontroller.
Testing Basic Programs
The basic programming script for the microcontroller is the variable initialization section, function
initialisation section and then the main function. For the microcontroller it is necessary to include a
while loop that continuously loops. This is to keep the microcontroller going through the code. The
30. 23
first program was to light the indicator LEDs on the Data Acquisition Board (DAQ). There are two
LEDs on the DAQ; red and yellow which are used to indicate the status of the DAQ. The first program
was to light the red LED wait a delay, then light the yellow LED wait a delay and loop around again.
This provided a basic understanding of the microcontroller programming. The learning curve for this
project came in the form of understanding how the microcontroller and its peripheral devices
worked and their registers. The actual programming was not a problem in most cases because a
good level of C programming was achieved before doing this project.
3.3 Implementation of DAQ Program
The previous section outlined the hardware and software used in the project as well as getting
started with the project. The following section will be split into three parts; improvements and
additions made to the microcontroller, improvements and additions made in Matlab and adding
control functionality to the system.
The first part will discuss the improvements made to the microcontroller program code. The
problems faced will also be discussed and how these problems were overcome. The main
improvement is the reception of data from Matlab and in this part there were many problems that
slowed down the project progress. These will be discussed in detail.
The second part of this section will discuss the improvements made to the Matlab program, such as
the division of the functions and adding support for sampling and plotting two byte words.
The third section will be a smaller section because most of the work had been done at this stage. The
foundation for the control functionality had been implemented. This section will discuss the
algorithm used for control and also discuss how parameters are downloaded from Matlab.
The improved program code for the DAQ is shown in Appendix C.
The following flow chart shows the main function and how the operation modes are selected.
31. 24
Figure 3-1: Flow Chart for DAQ Timer ISR
Timer Interrupt Called
Capture Mode
Only Selected?
Capture and Signal
Generation Mode
Selected?
Control Mode is
Assumed
See Section 3.4.1 for
Control Flow Chart
No
Sample and Convert
Voltage on ADC
Channel
Send Sampled Value
to Matlab Buffer
Return from
Interrupt
Voltage Signal
To Matlab Buffer
Sample and Convert
Voltage on ADC
Channel
Voltage Signal
Yes Yes
Send Sampled Value
to Matlab Buffer
To Matlab Buffer
Read Data Value
from Flash Memory
Convert Digital Value
Read from Memory to
Voltage Level
Return from
Interrupt
No
Data Value from
Flash Memory
Voltage Level at DAC
Output
32. 25
3.3.1 Sampling Analogue Signals
The improvements to the signal sampling functionality are in the form of increased speed an extra
analogue channel and the use of priority interrupts. This section will follow the review section where
the implementation of the ADC improvements will be discussed first and then the sampling timer.
ADC Implementation
The changes to the ADC have increased its maximum sampling rate and added an extra channel that
can be sampled. The original ADC function used a very large acquisition time which has been
reduced using the programmed acquisition time that is available on the ADC. The extra channel has
been added to provide an analogue set point value in control mode but it can also be used by the
other two modes of operation.
Sampling Timer
The sampling timer has been completely changed before timer 0 was used to set a sampling rate.
When a timer interrupt occurred the main ISR was executed and just before returning from the ISR
the timer was reset and started counting again when the interrupt was finished. This meant that the
accuracy of the sample period depended on a fixed ISR time which was unrealistic when using the
ADC and the USART peripheral modules in ISR.
To improve this situation the Capture/Compare/PWM (CCP) module was used to setup an accurate
sample period. The compare mode of the CCP module constantly compares a user set value against
the current timer value. When the timer reaches the value stored in the CCP module register the
timer is reset to zero, an interrupt is called and an analogue to digital conversion starts
automatically. This is called a Trigger a Special Event. The result is a sample period that is
independent from the interrupt program code which ensures an accurate sampling rate. The
maximum sampling rate is dependent on the ISR execution time and care must be taken not to have
a sample period less than this execution time.
3.3.2 Transmitting Data to Matlab
Transmitting the sampled signal to Matlab is still implemented by the USART transmit register, to
improvements to the USART transmit are a higher baud rate and less overhead waiting from the
USART transmit register to empty. The baud rate was increased from 25Kbps to 115Kbps.
3.3.3 Receiving Data from Matlab
This is one of the main areas that have been improved in this project. A separate function was
developed to handle downloading data from Matlab and storing this in the DAQ memory.
33. 26
Download Interrupt
The original interrupt to download data from Matlab serviced a byte for every Interrupt Sub-Routine
(ISR) request. This meant that for thousand bytes of data the ISR was called one thousand times to
service the data properly. The disadvantage of course is its poor efficiency, difficulty to follow for
other programmers and lack of intelligence. The advantage of this method is that the number of
bytes to download does not have to be identified since it will stop receiving data when Matlab stops
sending it.
To improve upon this the general idea was to go to the interrupt, stay there until all the data has
been received and then return to the main program. There were two stages to implementing this;
the first was to stay in the ISR until all the data was received and the second was to future improve
upon this by calling a separate function to deal with downloading the data. The reasons for putting
the download program into a separate function are as follows
Reduce the size of the ISR to allow developers focus on the main code
Downloading data is a function on its own and as such should be placed in a separate
function
The latter point might seem like a waste of time but it is one of the goals of this project and indeed
most programs to treat functions as a block function. The downloading of the Matlab data is a block
function because it is called to download the data from Matlab and write this data into flash
memory. Other functions can access the data from flash memory without having any contact with
the download function.
Problems with Download ISR
To understand the main problem with the download ISR consider the following structure of the
function.
1. When byte is received by the DAQ jump to ISR and go to download function
2. The first few bytes of data are the configuration parameters which are placed in an array
3. When all the configuration parameters are downloaded they are written to flash memory
4. Then the data is expected and is stored in 64 byte arrays
5. When the array is full of data it is written to flash memory
6. When all the data has been downloaded the function returns control to the interrupt
7. The configuration parameters are updated with the ones downloaded.
8. Control is passed back to the main program
34. 27
The steps above show that the function expects the configuration parameters first and then the
data. Both of these are in a loop which will not exit until they have received the number of bytes
that were specified at the start of the download. This is a well-structured function and it is a big
improvement on the previous download method. A very useful feature is placing all the
configuration parameters into one array. This saves having to assign each to a variable during
download. Then after the download has completed a separate function is used in the main script to
update the variables from the configuration array.
The main problem is that if the right number of bytes are not sent received by the DAQ the
download function will be suck in one of the loops and will not exit until its download counter is
equal the download size specified during the beginning of transmission. However, this problem
could be solved by error checking, retransmission mechanisms such as in Transmission Control
Protocol (TCP). This is completely unnecessary in this project for the following reasons:
1. Communication is via a single channel USB so no other traffic will be present
2. Continuous testing has not resulted in this problem
The other main problem encountered is with the buffer on the DAQ; it can only hold two bytes at a
time. If a third byte arrives at the DAQ receive pin an overrun error will occur and no more data can
be received until this error is reset. The primary reason that this happens is because the DAQ takes
up to 6ms to write a 64 byte block to memory. Matlab is still sending data and it is not read fast
enough. This is resolved by putting a short delay (4 – 6ms) after Matlab has transferred each 64 byte
block of data.
Main Problem with Downloading
The previous short section outlined the two main problems while downloading data to the DAQ. The
biggest problem encountered throughout the whole project was with the reception of data. This
problem is discussed in the following section.
The situation where the problem occurred was while downloading data from Matlab. The interrupts
where set up, the ISR passed control to the download function to receive the configuration
parameters and then the data. However, while downloading the program would get stuck in either
the configuration parameter loop or the data download loop.
35. 28
3.3.4 Writing Data to Memory
Writing downloaded data to flash memory is an important part of the acquisition system and allows
users to create signals and send them to the DAC output as a voltage signal. This is allowed by using
flash memory on the microcontroller. The microcontroller can store up to 64KB of data including the
program instructions. The limitation on the original system was 4KB which is a small percentage of
the available. The follow sections outline the problem that causes this as well as the steps taken to
find the problem and fix it.
Flash Memory Limit Problem
The flash memory starts at the address 0x0000h (h stands for hexadecimal which is generally used as
the address system in microcontrollers) and continues until 0xFFFFh this is 0 – 65,535 in decimal or
216
in binary. To write to flash memory a function is used that takes the start address in hexadecimal,
the number of 64 byte blocks to write and the starting address of the data in RAM (this is a pointer
to the start address). The function will then write the data into flash memory. The starting address
must be higher than the last address used by program code. Generally a sustainable gap would be
used to allow for future code expansion. The write operation could not write data to an address
above 0x3FFFh. When attempting to write to address above this the program would behave
erratically.
Flash Memory Limit Suggestions
The suggestions to this problem were either to start writing a new function immediately or else
examine the current function and try to find reasons why it might not be working.
The latter approach was taken and after much time reading the function documentation no
solutions would be found. The function was well documented. The next step was then to read the
data section on flash memory. Still after reading the datasheet and comparing the steps to write
data to flash memory to the ones in the function there were no obvious reason why it was not
working properly.
While reading through the datasheet for further ideas, a section in the end of the datasheet describe
the way the flash memory was organized into five blocks. Each block can be given different access
rights. This lead to the idea that only the first block could be written too and that the other blocks
were write protected. However, the datasheet did not give any explanation of how to do this. This
lead to some time searching the internet as many people use microcontrollers similar to the one
used in this project for hobby projects and maybe someone had come across this problem. This also
was unsuccessful.
36. 29
Since researching the problem was unsuccessful the next step was to write a new function to write
data to flash memory. The plan was to follow the step by step guide in the datasheet and by
understanding exactly what each line of the function does the problem will become clear. This
turned out to be successful.
Flash Memory Limit Solution
While the problem caused a considerable inconvenient to the project progress the solution was very
simple. Before writing the data to memory the function must load the starting address of the first 64
byte block of data. Since data can only be written in 64 byte blocks the starting address must be
aligned to a 64 byte boundary. This is done by dividing the start address by 64; if the answer is not
an integer number then the address is not aligned. The result is multiplied by 64 to calculate the
aligned address. The remainder will be disregarded because the address is an integer. The following
is the original code.
startaddr =(unsigned long) ((unsigned char)(startaddr / 0x40)) *0x40; //Calculate starting address
of the block
This could be more clearly written as:
unsigned char temp;
temp = startaddr / 64;
startaddr = temp * 64;
The variable ‘temp’ is and unsigned character (8-bits which holds 0 – 255).
For example take the start address 0x4000h which is 16,384 in decimal.
temp = 16,384 / 64 = 256 The problem here is the variable ‘temp’ is only 8-bits long and its
maximum value is 255.
The variable in this case takes the value zero this 256 in binary is (0001 0000 0000) i.e. last 8-bits are
zero.
The solution to this problem was to change unsigned char to an unsigned int. Simple but it was not
obvious until the function was fully understood.
37. 30
3.3.5 Writing Data to DAC
This function was working properly on the original system so there was no need to change it. It was
improved to be easier to understand and also to deal with 12-bit values.
3.4 Additionally functionality for DAQ
The implementation of the project started with basic programming and then developed step by step
from lighting the LEDs, using the ADC, DAC, transmitting data to Matlab up to the final step of
implementing digital control algorithms. The original project program code was not used but rather
was followed in general and modifications were made where necessary. New code was written at
each stage, tested and then structured and properly commented. This approach was taken so that
the project would keep moving until the project period was up. This is as opposed to writing a
program that meets the objectives and then structuring and commenting it. The following sections
outline the extra functionality added to the microcontroller program. The first is the main
functionality requested which is digital control, the second is the use of two byte values to improve
the system resolution. The last addition allows users to write floating point values to the DAQ.
3.4.1 PID Digital Control
Digital control was implemented using PID parameters and a PID algorithm. The implementation was
of the actual algorithm proved to be an easy task. The algorithm can be viewed as a pluggable
module that takes an error signal and outputs a corrective signal which will be sent to the process
being controlled. The following parts will outline how the control functionality was integrated into
the DAQ.
The following flow chart shows how digital control was implemented and integrated into the main
code. Figure 3-1 shows how control mode is selected.
38. 31
Figure 3-2: Digital Control Flow Chart
Control Mode Selected
Read Set Point Value
from ADC Channel 0
Timer Interrupt Called
Read Set Point Value
from ADC?
Read Set Point from
Flash Memory
Determine Set Point
Value
Read Process Output
from ADC Channel 2
Calculate Error Value
(Set Point – Measured Value)
Return Error Value
Determine Corrective
Signal
Convert Corrective
Signal to Voltage Signal
Send Set Point Value to
Matlab Buffer
Send Measured Value
to Matlab Buffer
PID Algorithm
Return from
ISR
Yes
No
DAC Output to
Process Input
To Matlab Buffer
To Matlab Buffer
Process
Output
Analogue Set Point
Value
Set Point Value from
Memory
39. 32
Setup of Libraries
Libraries were used to improve the structure of the DAQ program. A library is a collection of
functions that are separated from the main code, each library has its own header file that lists the
functions available in the library. The header file is included in the main code to allow the use of the
library functions. There are two libraries on the DAQ; the first is “daq_functions” which holds all the
functions that are used but are not needed to understand the operation of the main code. This
function holds the download function, ADC function, DAC function, etc. The second library is the
control library which contains the control functions:
1. “Calculate Error” – Takes set value and ADC value and calculate the error between them
2. “PID_Main” – takes the error value, calculates the necessary corrective action and returns the
output to send to the DAC
3. “PID_Update” – called after a download to update the control parameters
4. “Update_Var” – used to convert four characters to float point value for P, I and D terms
These are just the basic functions needed to carry out digital control, this library can easily be
expanded to include digital filter functions, different control algorithms, etc.
PID Control Algorithm
A PID control algorithm was chosen because t
3.4.2 Sending IEEE Floating Point Values to the DAQ
One of the issues faced was writing down floating point values as the control parameters. This is a
decision that might be unnecessary. After researching how other microcontrollers implement
control algorithms it was clear that the lower ending ones use integers. The decision to use floats
was simply for convenience and could also be useful in the future where developers would like to
use floats as parameters for example in filters with B and A coefficients.
The communication mechanism between Matlab and the DAQ only allow single 8-bit values which
means the float must be broken into four bytes and then assembled when it reaches the DAQ. There
were two ways that this could be implemented:
1. The IEEE float is put together using a formula
2. The IEEE float uses four bytes of memory in Matlab this memory can be transferred to the
float in the DAQ
40. 33
The first option was giving a brief investigate but the conclusion was it was too difficult to implement
on the system. The second option was chosen and was a much easier option. Essentially the opinion
was if the float uses four bytes in Matlab then if those four bytes are put in memory on the DAQ well
the same value should be represented. This was implemented after some research with the use of
unions in C programming. The four bytes were separated into unsigned integers in Matlab and sent
down to the DAQ one after the other. A union structure allows the same block of memory being
interpreted as different data types. So was used to represent four characters as a float. This was
successful the function was placed in the control library. This function is called after a download
occurs and control mode is selected.
3.5 Implementation of Matlab Program
This section will follow the layout used in the review section and outline and discuss the suggestions
that were implemented on the Matlab side of the project. The Matlab code for the current project is
given in Appendix B.
3.5.1 Handling User Input Arguments
The user input section did not have any major flaws but needed to be re-structured and better
commenting to allow easier readability. The user interface section was implemented as function to
take the input arguments, process them and configure the parameters used for the other functions
based on the input arguments. The structure of the interface function is:
1. Define parameters with default options
2. Check input arguments against pre-defined options
3. Change parameters if options are selected
4. Group configuration parameters into arrays
5. Call download function to configure the DAQ and send it data
6. Call sample and plot function to receive the DAQ data and plot it
This structure is clearly laid out in a logical manner which makes it very easy for develops to modify
it in the future.
Constructing a Serial Port Object
This was not a large part of the project but turned out to cause frustration. A serial port object is
used to communicate with the Data Acquisition Board (DAQ) and it is important to properly open
41. 34
and close serial port objects. If this is not done then Matlab will not be able to create another serial
port object which means no communication with the DAQ. The original Matlab code solved this
problem and was successfully able to detect an available serial port, but the code was very long and
either needed to be reduced or separated into a function. This section will discuss how this problem
was solved.
Serial Port Object
The solution was not difficult but required reading a lot of Matlab document on serial ports to figure
out a simply way to detect an available serial port, open the serial port regardless of whether it was
properly closed or not. Detecting a serial port is done using the built in Matlab command
“instrhwinfo(‘serial’)” which returns the details of available serial ports. From this the serial port
name (e.g. COM1, COM2, COM3, etc in Windows) can be extracted.
The second part is to properly close a serial port object. This is done using the command “instrfind”
which returns a cell array of the serial port objects in Matlabs memory. The ‘fclose’ command is used
to close any open serial port objects returned by ‘instrfind’. Then the ‘delete’ command is issued to
delete them from Matlabs memory and finally the clear command is used to remove them from the
workspace.
3.5.2 Configuring the Data Acquisition Board with Basic Parameters
This section was moved to the “Write_2_DAQ” function which is called to download both
configuration parameters and data to the Data Acquisition Board (DAQ). The basic parameters have
been replaced by configuration parameters which are essentially the same thing but contain more
parameters than the original program. For example now the program sends the mode of operation
to the DAQ, resolution to use, analogue channel to read from and a few more that are needed to
operate in the mode selected by the user. The extra parameters are needed to allow the extra
features of the DAQ.
The configuration parameters are selected in the DAQ interface script and then configured in the
“Write_2_DAQ” function in their own section.
Writing Data to the Data Acquisition Board
The previous section mentioned that writing to DAQ has been split into a separate function. This was
implemented for two reasons; first the section “Writing_2_DAQ” was just sectioned with comments
in the main script but it became too large and thus it was moved to its own function. The second
reason is in the interest of producing a program that is modular the separation of functions where
possible is an aim of this project.
42. 35
This function has been separated into the following sections:
1. Organise Configuration Parameters for the DAQ
2. Configure data for sending to the DAQ
3. Open a Serial Port Object
4. Send Configuration Parameters to the DAQ
5. Send Data to the DAQ
6. Close the Serial Port Object
The main part of the function which is to send the data to the DAQ has only been changed slightly
since the original program. This is mainly better use of comments to explain the process.
The other main changes come from the separation of configuring both the parameters and the data
and then sending them down. This is a logical separation that is easy to follow, it has also been
necessary since sending 16-bit needs to be split into two unsigned integers before being sent to the
DAQ. This was done using another small function that was created called “int_2_uint8” which takes
an array of integers and coverts them to two unsigned integers. For example the function could take
the decimal value 2000 and split it into [7, 208] which will be re-assemble at the DAQ.
3.5.3 Sampling and Plotting
The review section outlined the size of this chunk of code in the original program. This has been
separated into its own function and called from the “daq_lite” interface program. This function was
made even more complicated because 16-bit data needed to be plotted and then the control
variables (which are both 16-bit) needed to be plotted. The function was further split into the
following sections:
1. Open Serial Port Object
2. Sample and Plot DAQ modes 1 and 2
3. Sample and Plot control variables
The Sample and Plot DAQ modes 1 and 2 deal with sampling and plotting sampled data and data
sent to the DAQ. The third section deals with sampling and plotting the control variables set point
value and process variable.
Sampling and Plotting DAQ Modes 1 & 2
One of the difficulties of this function was separating out sections because many functions are so
integrally linked together. For example sampling data and storing this into an array is one task but
this must be plotted immediately to provide the user with plot of the sampled data. Likewise
43. 36
sampling and plotting 8-bit and 16-bit data have to be separate but yet cannot be in separate
sections because this would create too much repetition and end in a long winded program. So the
functions were separated as best they could and then comments were used to explain what was
happening and why.
Sampling and Plotting Control Variables
This section was separated because it would make the previous section too complicated. The control
section reads the set point value and the process value from the DAQ in 16-bit values. This is slow
but accurate which for educational purposes was deemed more important than controlling process
with very fast responses that would be hard to analyse. The DAQ sends two bytes for the set point
value up first and then two bytes for the process value. These are stored in Matlabs buffer and then
read into an array. The values are then plotted on a graph that is updated each time they are read.
A second plotting mode is also available to use with the control mode which is continuously plot.
This is intended to allow users to continuously view the set point and process output values on
screen. This is useful for changing the set point and view the response over time.
Plotting the DATA Smoothly
In the original project it was observed that a low sampling rates the plot was not smooth. This was
something to work on in the current project, especially when doing control tests at low frequencies
and changing the set point manually. The reasons this occur was due to the way data was read from
the Matlab buffer. When Matlab is sampling it stores the data in its input buffer, which is filled by
the DAQ transmitting data on every sample. At low sample rates the buffer fills slowly and at high
sample rates the buffer fills quickly. The original program read every byte that was in the buffer each
time it was plotting a value and this results in a poor graphical plot.
This can be improved by reading the right number of bytes at a time. When the sampling rate is low
read only a few bytes at a time and when it is high read a large of bytes at a time. This result in a
mechanism to determine how many bytes should be read from the buffer on each loop. The
mechanism developed is based on both the sampling rate and also the number of samples selected
by the user.
3.6 Matlab additionally functionality
The two previous sections discussed how the original Data Acquisition System was improved upon.
This section will go through the additions made to the project which include; higher resolution, extra
analogue channel, control mode and the ability to download floating point values.
44. 37
3.6.1 Improved Resolution
The higher resolution option in Matlab was called ’16-bit’ because two bytes are used to implement
a single value. This does not mean however, that the resolution is 16-bit; the resolution of the
Analogue to Digital Converter (ADC) is 10-bits and the resolution of the Digital to Analogue
Converter (DAC) is 12-bits. The higher resolution means that the peripheral device resolution can be
fully utilised.
The main reasons for implementing a higher resolution system was one to fully utilize the hardware
used and two to allow users a higher accuracy when reading signals. Since this is an educational tool
students can gain more accurate results by having higher resolution values.
3.6.2 Adding an Analogue Channel
In the project a need for a second analogue arose when discussing how the set point source should
be implemented. Controlling the set point or reference value via an analogue input is a convenient
way to view how a system behaves at low frequencies. The ADC function was modified to take a
second argument which selects whether to read from the first or second analogue channel. This
functionality has proved very useful through the control testing phase.
3.7 Testing & Validation
The project was testing and validation under the following headings:
1. Backward Compatibility
2. Function of Improved System
3. Digital Control Testing
The first section outlines how well the new system retains backward compatibility. This means how
users of the original system could use the new system, this will include commands, options given to
the program, information about operating modes and understanding what is been plotted. This will
be done on the Matlab side of the system since the user generally will only interface with the main
Matlab program.
The second section will outline how the improvements have made the user experience better, given
the user more functionality and show that the system is working the way it should. Any problems
During the testing phase will be discussed.
45. 38
The last section will deal with the DAQ as a digital controller and how well in works. The PID control
algorithm is a simple algorithm with the aim of helping students gain more experience with control
systems.
3.7.1 Backwards Compatibility
One of the conditions of this project was that the end product should be useable by the users of the
original system. Consider a student who was using the original system during the last semester, the
system is now improved can the student simply switch without needed to read the documentation
to figure out how it works. Students will obvious need instructions on how use the new options.
Backwards compatibility has been kept in the new system by using the same command line
interface, the same command arguments, the same command options and the modes of operation
have not been change. For example the command is “daq_lite” with the arguments (200, 1000) this
will still return 200 samples from the ADC at a sampling rate of 1000Hz. The signal will be plotted on
a graph as expected. This is true for all the command line arguments and options, the extra functions
such as higher resolution, second ADC channel and control mode are selected by extra input
arguments or options.
3.7.2 Function of Improved System
The system has retained backwards compatibility so at first glance it is not obvious that changes
have been made. The new functions and options need to be thoroughly tested to ensure the system
works before programming the other systems with the new code.
The testing of the system was carried by going through mode and the different options within each
mode. Sampling high and low frequency signals and viewing how these were plotted in Matlab. The
control tests were left until last and are discussed in the next section. After carrying each test only
minor problems occurred and were easily solved.
3.7.3 Digital Control Tests
The scope of this project varied throughout the project, initially the scope was to get a functioning
digital controller. During the project the scope was increased and the plan was to include a digital
filter carry out the control algorithm. A digital filter algorithm could be easily integrated and the B
and A coefficients could be downloaded as floating point values. This however, was not
implemented due to time constraints. The scope of the control tests provided below will be limited
to show that the digital controller will show students the effects of changing the PID parameters.
46. 39
The tests are on a first order system with a gain of one and a time constant of one. The controller
was configured to read the set point from the ADC, the set point was changed and the resulting
process response is shown in the following graphs.
Figure 3-3: PID Control Tests – Proportional only with gain = 1
Set point in red and process output in blue; kp = 1, ki = 0, kd = 0
0 100 200 300 400 500 600
0
500
1000
1500
2000
2500
3000
3500
4000
47. 40
Figure 3-4: Proportional Only with Gain of 10
Figure 3-4 above shows a step response with increased gain compared to figure 3-3. This shows that
increases the proportional gain reduces the error between the set point and process values.
0 20 40 60 80 100 120 140 160 180 200
0
500
1000
1500
2000
2500
3000
3500
4000
48. 41
Figure 3-5: Proportional and Integral Control – kp = 2, ki = 1
Figure 3-5 shows the controller tested under both proportional and integral control. The controller
response is fast and there is almost no error between the set point and process values.
The control tests shown above are basic but show that the DAQ implemented digital controller and
changing the proportional and integral parameters result in the level of control expected.
3.8 Summary of Implementation Chapter
The implementation chapter closely follows the format of the review chapter. The review chapter
outlined the problems with the original data acquisition and suggested ways to solve them. The
implementation of the project was carried for the most part in accordance with the review
suggestions. The summary will outline the main parts of the implementation chapters.
3.8.1 Implementation of the DAQ software
The DAQ software implementation was carried out under the following five headings:
Sampling Analogue Signals
Sampling was improved in two ways; the first increased the maximum sampling rate and the second
implemented a more accurate sampling period. The sampling rate was increased by reviewing the
0 100 200 300 400 500 600
0
500
1000
1500
2000
2500
3000
3500
4000
49. 42
ADC hardware and implementing a more efficient function. The accuracy of the sample period was
improved by using the CCP module to set the sample interval independent from program execution
time.
Transmitting Data to Matlab
No major improvements were made in this function, it was reviewed and found to be as efficient as
possible.
Receiving Data from Matlab
This section proved to be the most troublesome and required the most amount of time. The main
improvements to the section are a faster data rate due to a higher baud rate and less time spent
moving between interrupt sub-routines. The original ISR was separated into a single function which
is called to receive the data from Matlab.
Writing Data to Memory
The original limitation on the flash memory usage was 4KB this was increased to 64KB be reviewing
the hardware and software techniques used to access and write data to the memory.
Writing Data to the DAC
The DAC function was not changed in any major way, the program code was modified to allow 12-bit
data values to be converted to a voltage level. Previously only 8-bit numbers could be converted.
3.8.2 Additional Functionality for DAQ
The additional functionality that was implemented on the DAQ is given under the headings below.
Digital Control
One of the main objectives of the project was to implement a control mode that allows the data
acquisition system act as a digital controller. This was implemented using a PID algorithm which is
based on positional control.
Download floating point values to the DAQ
One of the problems with the digital control algorithm is that operators generally specify the PID
parameters using decimal places. Floating point values are not easily transferred to the DAQ because
the only one byte can be sent at a time. This problem was overcome by the use of ‘unions’ in C
50. 43
programming language. Unions allowed four bytes of data to be sent from Matlab to the DAQ and
then assembled to represent a floating point value.
Higher Resolution
The original DAQ dealt with 8-bit values which restricted the resolution of the system. The ADC can
use 10-bits of resolution with increase the accuracy of the sampled signals four times. This feature
was implemented by using two bytes to represent a single value.
Two ADC Channels
The ADC function was modified to allow users select between two analogue channels. This was
implemented for the control mode to allow to the set point value be controlled by an analogue
signal. The second analogue channel can be used for sampling any mode.
3.8.3 Implementation of the Matlab Suggestions
The Matlab software was modified as suggested in the review section, the program was divided into
separate functions due to the large amount of program code. This was also a logical way of
separating the program.
User Inputs
The user inputs must be processed to pass the correct configuration parameters to the functions
that follow the interface function. This section was expanded to allow for the control parameters
and the extra options provided by the system.
Configuring Parameters and Data for the DAQ
Configuring parameters and data were placed into one section and then they were sent to the DAQ
in the next section. This has two advantages; it is easier for others to identify which parameters are
sent to the DAQ and second by sending the configuration parameters and the data together the
process of transferred data to the DAQ is more efficient.
Sampling and Plotting Data
The implementation of the sampling and plotting function was difficult because both 8-bit data and
16-bit data had to be read from the buffer and then plotted. This function was structured well but is
still integrates the sampling and plotting functions together.
51. 44
3.8.4 Matlab Addition Functionality
The functionality added to the Matlab software side of the acquisition system was mainly to support
the changes implemented on the DAQ. These include the control mode; Matlab was modified to
handle the control parameters and plot both the set point value and the process value.
4 Conclusions & Future Work
The main objectives of this project have been completed. The main objectives were firstly to
improve the existing software design and add addition functionality to allow the system operate as a
digital controller. The improvement phase of the project consumed more time than was expected
which meant that the implementation of digital control was basic. The software has been structured
to provide easy expansion and a pluggable PID control algorithm which can easily be upgraded to a
more complex algorithm. The following sections will start off with a summary of the project, discuss
the analysis of the main findings, discuss the methodology used throughout the project and finally
discuss future upgrades to progress the project further.
4.1 Summary of Project
The project started off with a review of a data acquisition system to improve. The review outlined
the faults with the system and suggested ways to improve it. The main fault with the systems was
on the software side, the software was poorly structured and not well commented. This made it
difficult to understand the functions the software was carrying out. The functionality of some of the
software was also inefficient and needed to be refined. The initial review also considered the
necessary changes needed to allow the data acquisition system implement digital control.
The implementation of the project began with basic programming on the DAQ, reading the
datasheet to get a full understanding of the hardware modules such as:
Analogue to Digital Converter
Digital to Analogue Converter
Universal Synchronous Asynchronous Transmitter Receiver
Flash Memory
Interrupts
The DAC module required only a basic understanding because it was working properly and no
obvious inefficiencies were noticed on the software side of it.
The project resulted in many improvements to the system:
52. 45
Cleaner code structure and good use of comments
Higher resolution samples
More accurate sampling rate
Higher sampling rate
Cleaner and faster download function
Limit on flash memory removed
Smoother plotting in Matlab
These improvements also made the implementation of digital control much simpler due to the
modular structure of the programming code.
A PID control algorithm was used to implement digital control and the P, I and D parameters can be
downloaded as floating point numbers for a more accurate and user friendly controller.
The last phase of the project was testing which turned out to be successful apart from some minor
bugs that were easily fixed. The new system can be used by a user who has experience with the
original data acquisition interface. The backwards compatibility was kept for this reason.
4.2 Critical Analysis of Methodology
The methodology used throughout this project did not vary much expect in some cases. The project
started with the basic hardware and software setup and continued onto some basic programming.
From this stage on the project was about adding functionality, testing this function and then coding
and commenting the function. For example the first hardware module reviewed was the ADC, the
first step was to use the program code from the original project and try to understand what it was
doing. If this could not be understood the datasheet for the microcontroller was consulted and most
of the time the information needed was in the datasheet. After reading the datasheet the function
was coding and tested. Finally once the function was working as expected it was commented in a
fashion that would allow another developer to understand it. This approach applied to many of the
problems encountered in the project and was successful in most cases. Some cases required the use
of internet resources to figure problems or implement solutions that were not included in the
datasheet.
The main criticism of the approach taken to the project is that it tended to concentrate quite a lot on
refining the software, making it very neat and well-organised. While this will be useful to others in
the future this time might have been better spent building a GUI, creating control tutorials that
students could carry out, implementing and testing digital filters. Although this criticism is not well
53. 46
founded because it could also be argued that the time spent refining the software gave a better
understand of the overall system and also allow future work to be implemented quicker.
4.3 Future Work
There is a lot more than could be done to make the data acquisition systems more functional, faster,
more user friendly and generally more useful as an educational tool. The following sections outline
some of the features that could be added to improve the overall system.
4.3.1 Future Work on Interface
One aspect of the project was not completed was the Graphical User Interface (GUI), this would
have been a very nice feature to have in the project and would allow users to carry out tasks faster
and spend less time learning the command line options. The current interface is well structured for a
GUI so it should not be a difficult task to build a GUI for the Matlab interface. However, GUI’s do
consume a lot of time and which is why it was left out of this project.
4.3.2 Future Work on Extra Functionality
The way the microcontroller program is structured it is easy to add to it. More control algorithms
could be added directly to the control library; digitals filters such as FIR and IIR filters could be
written and easily called from the main function. There are many more examples of the uses of this
system. However, the limitation comes in when audio processing functionality is needed because the
system is not fast enough to carry out this high frequency sampling. The program code could easily
be upgraded to carry out such tasks on higher end microcontrollers such as the dsPIC range from
Microchip.
4.3.3 Refinements
To further improve the performance of the microcontroller the program efficiency could be
improved. One such improvement could be made with the use of inline functions. Inline functions
are used where the actual function code is small compared to the overhead involved with calling the
function. The compiler moves the function to the main code so the overheads in moving the
function are removed. This could improve the sampling rate. Another way to improve the sampling
rate would be to use a while loop for each DAQ mode. Currently the microcontroller checks which
mode the DAQ is in and then executes the commands for that mode. A faster way would be to check
which mode it is in once and then stay in that loop. This could not be done in this project because
the interrupt returns to exactly the same place it was called from meaning that the mode could not
be changed during operation.