Design and Implementation of an Embedded Real-Time...

37
KUNGL TEKNISKA HÖGSKOLAN Institutionen för Signaler, Sensorer & System Reglerteknik 100 44 STOCKHOLM ROYAL INSTITUTE OF TECHNOLOGY Department of Signals, Sensors & Systems Automatic Control SE-100 44 STOCKHOLM Design and Implementation of an Embedded Real-Time System A Master’s Thesis by Paul Cedwall December 2003 IR–RT–EX–0321

Transcript of Design and Implementation of an Embedded Real-Time...

KUNGL TEKNISKA HÖGSKOLANInstitutionen förSignaler, Sensorer & SystemReglerteknik100 44 STOCKHOLM

ROYAL INSTITUTEOF TECHNOLOGY

Department ofSignals, Sensors & Systems

Automatic ControlSE-100 44 STOCKHOLM

Design and Implementation of an EmbeddedReal-Time System

A Master’s Thesis byPaul Cedwall

December 2003

IR–RT–EX–0321

Design and Implementation of an Embedded Real-Time System A Master’s Thesis by Paul Cedwall.

i

Abstract This Master’s thesis considers the design and implementation of an embedded real-time system. The system will serve as a demonstration example of what can be done with the PIC16F877-processor that is a part of a QIC system from Quanser Incorporation.

One of the goals for this thesis was to build a demonstration example with the QIC system as a base. The second goal for this thesis was to evaluate if the QIC system was suitable as a base for a laboration as part of a new course at the Royal Institute of Technology in Stockholm, Sweden.

A motor, a sensor, a reference generator and two LED’s where attached to the QIC system and suitable instructions where written in C, compiled and downloaded to the system. By building a construction in Lego, the different parts were held together and a complete system was created. The final version resulted in an embedded real-time system, where the encoder axis is connected to the motor axis. The encoder measures the angle its axis is turned to and the motor makes the encoder axis turn into desired angle. The angle is decided by the position of the potentiometer. The LED’s will flash in different ways depending on the position of the potentiometer.

A demonstration model of an embedded real-time system was successfully created, which fulfilled the first goal of the thesis. The QIC system investigated will be suitable for developing a laboration system, especially a portable system.

Design and Implementation of an Embedded Real-Time System A Master’s Thesis by Paul Cedwall.

ii

Acknowledgement This report is the result of a Master’s thesis done at the Royal Institute of Technology for the Department of Signals, Sensors & Systems.

I would like to thank my supervisor Doc. Karl Henrik Johansson for giving me the opportunity to do this project.

I would also like to take the opportunity to thank the people around me who have been of great help to me during the process of work with my thesis. Thanks to my parents for financial aids, help and encouragement along the way to my final goal. Special thanks to my friends, Patrik Ström, Björn Malmgren and Johan Lindén, for supporting me when I most needed it. Stockholm 2003-12-29

Paul Cedwall

Design and Implementation of an Embedded Real-Time System A Master’s Thesis by Paul Cedwall.

iii

Table of contents Abstract..........................................................................................................................i Acknowledgement ........................................................................................................ii Table of contents .........................................................................................................iii 1 Introduction..........................................................................................................1

1.1 Background ....................................................................................................1 1.2 Context ...........................................................................................................1 1.3 Literature survey............................................................................................2 1.4 Summary........................................................................................................2 1.5 Thesis outline .................................................................................................2

2 The task.................................................................................................................3 2.1 The basic idea.................................................................................................3 2.2 The control problem.......................................................................................3 2.3 Summary........................................................................................................4

3 Hardware development .......................................................................................5 3.1 System............................................................................................................5 3.2 Motor..............................................................................................................6 3.3 Sensor.............................................................................................................6 3.4 Reference generator .......................................................................................7 3.5 LED................................................................................................................7 3.6 Power .............................................................................................................7 3.7 Microprocessor...............................................................................................7

3.7.1 QIC Carrier Board..................................................................................8 3.8 Summary........................................................................................................9

4 Software development ........................................................................................10 4.1 Real-time software .......................................................................................10

4.1.1 Usual occurring demands on real-time systems...................................10 4.1.2 Different types of tolerance..................................................................10 4.1.3 Construction principles for real-time systems .....................................11 4.1.4 How do we choose implementation? ...................................................11 4.1.5 How to verify the implementation? .....................................................11 4.1.6 Which programming method should be used?.....................................11 4.1.7 Scheduling............................................................................................13

4.2 ‘Flow diagram’.............................................................................................13 4.3 Operation system of the microprocessor......................................................14 4.4 The final Program........................................................................................14 4.5 The header files ............................................................................................15 4.6 Compiler.......................................................................................................15 4.7 Downloading files to the PIC.......................................................................16 4.8 Summary......................................................................................................17

5 Conclusions .........................................................................................................18 5.1 Suitable as a Laboration process? ................................................................18 5.2 Result ...........................................................................................................18 5.3 Comments on the results ..............................................................................19 5.4 Future works ................................................................................................20

References...................................................................................................................21 Appendix ....................................................................................................................... I

Hints of steps to follow in startup ...............................................................................I

Design and Implementation of an Embedded Real-Time System A Master’s Thesis by Paul Cedwall.

iv

Final version of the instructions written in C........................................................... III The explanation of the different pins ......................................................................VII QIC Starter Guide .................................................................................................VIII

Design and Implementation of an Embedded Real-Time System A Master’s Thesis by Paul Cedwall.

1

1 Introduction Traditionally many courses at KTH use laborations as a part of the examination. This Master’s thesis purpose is to investigate a QIC system built by Quanser Consulting Incorporation and evaluate its suitability as a base for a laboration project in a new course at KTH. Through designing and implementing an embedded system with the QIC system as a demonstration example, knowledge for an evaluation of the system will be collected.

Automatic control engineering and computer technology has always had a strong connection. Nowadays there is a computer involved in basically every control system. Control systems are one of the most common examples of an embedded system and since control systems are dependent on data that is up to date, these kinds of systems are often called real-time systems. To count correctly is not enough for the computer to serve this kind of system. It is also important that the operations occur at the correct time, since everything happens in real-time and no delays are accepted. The problem is even more complicated since it is very common that the system has several computers communicating with each other.

In chapter 1.1 some discussion of the background of the thesis will be discussed, in chapter 1.2 the context of the project will be the topic and the chapter 1.3 considers the literature survey. The purpose of this thesis will be discussed in chapter 1.4 and an orientation of the report can be found in chapter 1.5.

1.1 Background New courses that will be started at KTH needs projects, as a part of the courses. Projects that will help the students to test and evaluate their newly found knowledge, based on the theories from the course, in real life situation. The theory and the reality do, as everybody knows, not always compute. To do this they will need to do experiments on an existing object, in real life situation. This includes imperfect equipment, environment that is outside the computer. The system should accept delays and small gaps in the equipment.

A vision for this Master’s thesis was to create a laboration system that could be portable. Graduate students make a lot of laborations in laboratories, but the school could save quite a lot of money if the students could do their laboratory experiments at home. If the equipment would cost less than 100 kr, the students could borrow a circuit with a couple of devices attached to it, and a CD with all the programs and instructions necessary, and do the experiment at home with their own computer. The average student today does not always have an own computer and therefore the goal for this Master’s thesis might be fulfilled in a couple of years when hopefully every student has access to a computer at home. From idea to completion, the way might be long. No other project, similar to this one, with the same system and the PIC16F877, has been found on the Internet during the research for this Master’s thesis. Therefore the QIC system, used in this Master’s thesis, will be evaluated to see if it is suitable as a portable laboration system.

1.2 Context This Master’s thesis includes control systems, real-time systems and computers which all together results in an embedded system. Without control theory, the system will have some trouble to work. All the readings and inputs have to be considered directly so the outputs can react quickly, otherwise the absence of real-time inputs will have

Design and Implementation of an Embedded Real-Time System A Master’s Thesis by Paul Cedwall.

2

effect on the outputs. Computers are needed to make the correct code. Programming in C and compile the code into HEX-code and then download it to the circuit. If one doesn’t consider the demands of the reality the whole system will probably fail to work. It might be a gap somewhere, temperature changes or the wind might blow in through the window. In this thesis, it has been difficult to build the Lego-structure without any gaps and the motor gets weak when it rotates at low velocities but it also become too quick and strong at high velocities. A point where everything works satisfactory has to be found.

1.3 Literature survey Through searching Internet a literature survey has been done. Other Master’s thesis has been found and investigated, but there seems to be no other work done on the same QIC system with the same accessories attached to it. The first month of this Master’s thesis was spent searching the Internet for other projects done on similar QIC systems. Some university courses in Gothenburg, Linköping and Lund were investigated. By reading the overheads, shown during the lectures of these courses, some knowledge on the subject real- time systems was found. The laboration tasks to these courses were also investigated, but they where all pure computer-based tasks. None of them hade a system similar to the QIC system with the same accessories attach to it. The survey gave some ideas about how to complete this Master’s thesis.

1.4 Summary The purpose of this thesis was to investigate the QIC system, with the PIC16F877 microprocessor, built by Quanser Consulting Incorporation. By trying out the system, by attaching all the equipment listed in chapter 3, a final system could be developed. The result and experiences of the work will be used to see if the system is suitable as a base for a laboration in any course at KTH that involves real-time systems.

The degree of success of this project can therefore be measured in two ways. Firstly in terms of whether it achieves the basic goals set out for this Master’s thesis, to see if the QIC system was suitable as a base for a laboration process, and secondly whether it can be used in a real life situation, to make demonstration example to work. The way this Master’s thesis was done, the final working example can mostly be used as a demonstration example of an embedded real-time system.

1.5 Thesis outline • Chapter 2 presents the problem this Master’s thesis has been assigned to solve.

The system is revealed with a simple description and picture. • Chapter 3 will concern the hardware used in this project. The base of the

project as well as the accessories used to build the embedded real-time system will be presented.

• Chapter 4 start with an explanation of real- time since the knowledge has been one of the topics used in this thesis. Software used and created during the thesis will be presented and explained in this chapter.

• Chapter 5 summarizes the thesis and presents suggestions for future work.

Design and Implementation of an Embedded Real-Time System A Master’s Thesis by Paul Cedwall.

3

2 The task The design and implementation of the embedded real- time system has been the head task during this Master’s thesis. The experience learnt from fulfilling this task, will serve as a source for making arguments to fulfill the second goal of this thesis, to see if the QIC system is suitable as a base for a laboration system. In this chapter the problem is introduced. Chapter 2.1 shows a simple description of the system and in chapter 2.2 the control problem will be formulated. In chapter 2.3 a small summary of the chapter will end this chapter. Although a more thoroughly explanation of the hardware will be discussed piece by piece in chapter 3 and the software in chapter 4.

2.1 The basic idea The basic idea is to connect the motor axis to the encoder axis and let the motor rotate until the encoder gets into a desired position/angle. The reference value will be given by the potentiometer, the reference generator. When the potentiometer is set into its lowest position, the motor should turn the encoder axis to lowest value, zero degrees, and when the potentiometer is set into its top position, the motor should turn the encoder axis to 360 degrees. In this case both those extreme cases on the potentiometer will result in the same position on the encoder, since zero degrees and 360 degrees is on the same place on the encoder. The LED’s will show in what region the desired angle is positioned, see table 1.

Figure 1. The design idea.

A more exhaustive explanation of the system is explained during this next section, chapter 2.2

2.2 The control problem Without a control system the embedded real-time system will have some trouble to work. By showing and explaining the problem with both text and figures, the reader of this report should find it easier to grasp the whole picture. To control the angle of the encoder axis, it has to send information of its angle/position to the brains of the process. The brain of the system has to control the motor and the motor has to be able to change the position/angle of the encoder axis. Otherwise there will not be a control system to control.

The figure 2 shows how the control problem of the system is built up. The reference value is given by the potentiometer and is shown as ‘ref’ in the figure. The potentiometer is referred to as the reference generator in this report. The brains of the system, the PIC16F877 microprocessor is defined as the function F(s). By programming the microprocessor, it will make the motor control the angle of the encoder axis, with the signal v. The encoder axis gives feedback with the signal w to F(s), regarding its present angle/position. A control system with feedback is created. The signal y(t) sends instructions to the LED’s and they will flash, depending on the

Design and Implementation of an Embedded Real-Time System A Master’s Thesis by Paul Cedwall.

4

reference value, to show what region the desired angle of the encoder will be in, see table 1 chapter 3.

Figure 2. The control system.

Figure 3. The system.

Turning off the motor when it has got into desired position and by turning it on when it is not in the desired position solves the control problem. The motor becomes too weak at low velocities and too quick at high velocities. By making the motor turn off and on digitally, the motor will run at the same speed everytime. A Lego construction holds the motor axis and the encoder axis together.

A picture of how the different parts of the system are linked together physically to form an embedded system is shown in figure 3. The encoder axis has been linked together with the motor axis and it shows how the signal v, in figure 2, is sent between the two blocks.

2.3 Summary Chapter 2 contains an overview of the control problem solved during this thesis as well as introducing the different parts of the system. Figure 2 shows the flow of the control system and figure 3 gives an understanding on how the different attachments are physically linked together.

Design and Implementation of an Embedded Real-Time System A Master’s Thesis by Paul Cedwall.

5

3 Hardware development The QIC Carrier board does not do much by its own. A program can be run inside it, but a spectator will have some trouble knowing if its doing any thing or not. Therefore some equipment has to be applied to the board. The equipment given to this Master’s thesis was:

• A small dc motor from Johnson electric. • Optical encoder S1-1024-B from US digital. • Potentiometer from Xicon/Alpha. • 2 LED's. • A power box to deliver power to the carrier board, although the system can

run with a 9-volt battery, once the operating system is downloaded to the microprocessor.

• QIC Carrier board, with the PIC16F877 microprocessor. • Personal Computer • Cables.

The equipment will be described in the following chapters. The structure of the embedded real- time system is shown in chapter 2. In chapter 3.1 the system will be shown and in chapter 3.2, 3.3 and 3.4 the motor encoder and the reference generator is presented. Chapter 3.5 will show how the LED’s are used in the system followed by the power source SELTRON in chapter 3.6.. The brains of the system will be shown in chapter3.7 and the chapter 3 end with a small summary in chapter 3.8.

3.1 System The system designed and implemented is built up with the accessories listed in the beginning of chapter 3. The equipment is held together with a structure of Lego. The microprocessor has to be programmed and works as the brain for the whole system. By turning the potentiometer a reference value is collected and the microprocessor makes the motor turn around the encoders axis until the encoder returns a data value to the microprocessor that is within ten degrees from the reference value. The microprocessor makes the motor stop, waits for two seconds and collects a new reference value, but more information on how the program works can be found in chapter 4. All the accessories are connected to the QIC system with wires. The microprocessor is located in the middle of the QIC processor core, see chapter 3.7. All the key accessories and how they are linked together can be seen in figure 4.

Design and Implementation of an Embedded Real-Time System A Master’s Thesis by Paul Cedwall.

6

Figure 4. The hardware structure. [7],[15],[4],[8]

How to connect the different wires to the QIC system is described in the Appendix.

3.2 Motor The motor used is a small permanent magnet DC motor from Johnson electric.

Figure 5. DC motor. [4]

3.3 Sensor The optical encoder is a product from US Digital. It will return values depending on how the encoder axis has been turned.

Figure 6. The encoder.[8]

By measuring a start position (angle1) from the encoder and use it as a reference point. The next data measured (angle2) from the encoder will help to get a value in degrees, by measuring the difference (angle2-angle1). More data can be found at the address found in the reference [8].

Design and Implementation of an Embedded Real-Time System A Master’s Thesis by Paul Cedwall.

7

3.4 Reference generator The Reference generator is a Potentiometer that gives an analog voltage value on the wire in the middle. By reading of this value, it will be possible to se in what position the potentiometer is. In figure 7 the left overview of the potentiometer shows three holes in the bottom of the encoder. Three wires should be attached there.

Figure 7. The potentiometer.[7]

Where the left is connected to GND, the right to VCC and the middle one connected to the pin that reads analogue voltage values. More data can be found at the address found in the reference [7].

3.5 LED The two LED’s were the only equipments that could tell a viewer if all the different data inside the system were ok, or in which region they were in at different times of the programs. Since no display was available during this Master’s thesis, the LED’s were the only possible way to interpret the values from the encoder and the potentiometer at the different moments. By altering the LED’s, 00 01 10 11, four different regions, of the data, could be tested. In the final version the LED’s show in what region the desired value is by flashing according to table 1.

Angles LED 1 LED 2 If the desired angle is less than 90 (degrees). 0 0 If the desired angle is less than 180 (degrees). 0 1 If the desired angle is less than 270 (degrees). 1 0 If the desired angle is less than 360 (degrees). 1 1

Table 1. The explanation of how the LED’s flash. This will make the LED’s flash, 00 01 10 11, if the desired data value is less than 90 degrees.

3.6 Power The system needs power to be able to run. The Power box used was an old power box from SELTRON, Sweden, and it worked without any problems during the entire thesis, but as written earlier in this report, a normal 9 volt battery could also be enough to make the system run once the bootloader, the operating system of the microprocessor, has been downloaded.

3.7 Microprocessor The PIC microprocessor, a PIC16F877 microprocessor, has been the brains of the whole system on the QIC carrier board from Quanser consulting incorporation. The available data memory on the PIC itself is minimal, only 256 bytes of EEPROM memory, 8K Flash program memory and 368 bytes of RAM. [16] The microprocessor

Design and Implementation of an Embedded Real-Time System A Master’s Thesis by Paul Cedwall.

8

is located in the middle of the QIC daughter board, or the processor core as it sometimes is referred as. It is attached to the QIC Carrier board seen in chapter 3.7.1.

Figure 8. The QIC daughter board with the PIC16F877 microprocessor.[16]

3.7.1 QIC Carrier Board The QIC Carrier board offers a lot of different possibilities. By attaching different types of accessories it can be used in different kinds of situations. The most common accessories that can be used are motor drivers, encoder counters, extended I/O and of course the power supply (necessary to make the system run). Since the board allows different kinds of combinations of the accessories, various types of projects with new designs can be rapidly developed. It doesn’t have to be connected to a computer, once the programs have been downloaded, which makes it a good platform for mobile robotics applications. The power from a 9-volt battery is enough to keep the system running.

3.7.1.1 Power supply The QIC Carrier board is designed so it can be powered from a single power source. Once the bootloader has been downloaded to the PIC, 9-volt will be enough to either download hex-files or to run the system. Therefore a 9-volt battery will be an ideal power source [15]. Figure 4 shows where, on the QIC motherboard, the 9-volt should be connected as well as the connection to the encoder.

Figure 9. Power and Encoder connections. [15]

The power supply is designed to deliver 5 volts to the components on the board and the QIC Processor Core. 5-volt is also delivered to the connectors for the encoders. The power is applied via the connector J1 to the board. To protect the power connections from reversal current a diode (D9) has been installed. A LED is used to indicate the presence of power on the board.

3.7.1.2 Input power requirements To make sure that the regulators work properly, the input voltage should be higher than 7.6 volt, since they need to be powered from a source, 2 volts greater than its

Design and Implementation of an Embedded Real-Time System A Master’s Thesis by Paul Cedwall.

9

output voltage. In this case, the output voltage is 5 volts, so the input voltage should be greater than 7 volts. But since a diode has been put into the system to prevent reversal of the battery power, the input voltage has to be a little higher. Usually a diode increases the voltage drop by 0.6 volts, and it is the same in this case as well. This results in a minimum for the input power at 7.6 volts. In a case where the only power source is at 7 volts, the system can still be used. But the user then has to trust on his good luck, that the power will not be reversed. By either removing the reverse polarity protection diode (D9) and replace it with a short or simply bypass the diode with a jumper. This will drop the minimum input voltage requirement to 7 volts.

The maximum input voltage is 18 V and the minimum is 7.6 V, but the recommended input voltage is 9 V, according to manual [15]. When downloading the bootloader to the system, 12-volts has also to be applied to JP2 on the processor core, but this is a one-time task.

3.8 Summary By linking together all the equipment described in chapter 3 an embedded system can be created. The microprocessor is attached to the QIC system as well as the motor, the sensor, the reference generator, the LED’s and the power source. The power source could be replaced with a 9-volts battery, as described under 3.7.1.1.

Design and Implementation of an Embedded Real-Time System A Master’s Thesis by Paul Cedwall.

10

4 Software development The final version of the program has been written with serial execution and natural stops, such as delay loops. The scheduling has been done in a simple way, where the program runs in a while- loop, over and over again, and executing all the tasks necessary. If the program would crash, no harm would be done, so it is just to reset the program and start over again. Therefore this Master’s thesis will be an example of a soft real time system.

In chapter 4.1 real-time systems are considered and in chapter 4.2 a ‘flow diagram’ of the program is shown. The operation system is mentioned in chapter 4.3 and the most important operations of the instructions are described in chapter 4.4. The function of header-files is shown in chapter 4.5. Chapter 4.6 mentions the compiler used and chapter 4.7 shows the program used to download the compiled instructions to the QIC system. Chapter 4.8 gives a small summary of the chapter.

4.1 Real-time software Real-time systems have got involved in a lot of areas in our society. Real-time systems are often control-systems and they are often used in manufacturing-systems, processing-systems, telephone switch, cars, airplanes and space shuttles. It is also used in transaction-systems in areas such as ticket booking, cash machines, stockexchange and in mobile telephones. Multimedia is also an area where it is common, video-on-demand and virtual reality. It has a lot of areas where it can be used. The common factor is that it is desirable to have a punctually system, even if the complicity of the system varies from very simple to very complicated systems. The calculated results have to be delivered within a certain time, since the correctness of the systems is dependent of the delivery time. But punctuality is not the same as rapidity. Some real-time systems have to be high performing, but some high performing computer-systems minimize the average response time, but don’t give any guaranties for punctuality. Real- time systems are often embedded systems, and they are often a part of a commercial product.

4.1.1 Usual occurring demands on real-time systems The demands on a real- time system vary, but the most occurring are:

• Correctness. Real-time systems have to be correct in the aspect that they shall deliver correct outputs for all combinations of inputs. The output has to be correct in respect of both time and the value.

• Reliability. Real-time system has often high demands on reliability. For a control system for an airplane, the probability for a failure, of the system, has to be extremely small. One way of achieving high reliability is to build the system of very reliable and very well known components.

• Error tolerance. Systems that can tolerate errors are constructed in a way that they should be able to work although some parts of the system have failed.

Where do all these demands come from? The demands come from the system, which has to obey the laws of the nature e.g.; bodies in movement (the robot arm on a robot system) or the speed of the eye (minimal frequency of pictures in a movie).

4.1.2 Different types of tolerance There are two different types of tolerance in real-time systems. One of them is ‘Hard real-time demands’, either it works without faults or the system will crash. The other

Design and Implementation of an Embedded Real-Time System A Master’s Thesis by Paul Cedwall.

11

one is ‘Soft real-time demands’, small mistakes or errors can pass through, but are not good. Correctness, for the systems with hard real-time demands, has to be verified before the system is started or come into operation. If a system like that crashes, the functionality of the system will be lost and a non-working system will result in loss of money, a critical system. Examples of such systems are manufacturing systems, telephone switches and engine control systems. If a system crashes it can cause big damage or even loss of life. Examples of such systems are traffic controller, fly-by-wire, drive-by-wire and ABS-braking systems. The system does not have to crash, but work with reduced functionality, a non-critical system. Examples of such systems, that have soft real-time demands, are seat-reservations, cash dispenser, stock trade, video-on-demand, virtual-reality and computer games.

4.1.3 Construction principles for real-time systems Steps or questions, that has to be thought through before constructing a real-time system:

1. Specifications • What shall be done, and • When should it be done?

2. Implementation • How shall it be done?

3. Verification • Could it be done with the given implementation?

4.1.4 How do we choose implementation? There are different types of programming models. Sequential programming is one of the types, where the program is constructed in one single loop. A second model is parallel programming, where the program is constructed by several different sequential sequences.

4.1.5 How to verify the implementation? When the system is built up and ready, it has to be tested. There are two test methods used, ‘ad hoc’ and a more exhaustive test. Letting the system be run for a while and then check for faults makes an ad hoc test. The absence of faults proves the correctness of the system. This is a quick method that indicates that ‘all seems to be ok’, but this method is only suitable for soft real-time systems. Unfortunately this is the most common test method in the industry. The other test method is a more exhaustive test, where all combinations of input data and time are verified. It is important to verify the implementation so it can be discovered if parallel programs interrupt each other when competing over the shared resource. Some programs, that run parallel to each other, can block the others and this must be discovered before the system is put into use.

4.1.6 Which programming method should be used? There are two different methods to build a program, sequential and parallel. Sequential programming method is the easiest solution, although it has some disadvantages. Everything has to be done with the same interval and when the program is getting info from a sensor, no other reading can be done at the same time. The program does not take into consideration that the system consists of separate

Design and Implementation of an Embedded Real-Time System A Master’s Thesis by Paul Cedwall.

12

subsystems. When these kinds of system are complex, they will be hard to understand and maintain. A small change in the program can affect the time characteristics, which might result in trouble in analysing the time characteristics of the systems. Wait- loops are often used in this type of programs and are hard to verify and understand.

The advantages of parallel programming are that the different processes can be executed parallel to each other with their own infinite loops. When one process is waiting for input data, the others can execute and no wait-loops are needed. Without parallel processes, the program has to be structured as a single loop. When several programs are working at the same time, side by side, all of them will send information to the screen at the same time. The screen can just receive information from one process at the time, which is a disadvantage with this type of programming. This results in a need for a third process, when two processes are running, that has to control the access to the screen in a way that both processes can use the screen at the same time. Parallel systems need a Run-Time system to manage the scheduling and the communication process. A Run-Time system has a lot of properties common to an operation system and exists logically between the application program and the hardware. The system can be designed as an operation system permanent downloaded to the computer and can be called from the application program as a system call, a module or a standard program package that is stored as an object-module library. A simple real-time system, Run-Time system, usually at least contains process managing (create, terminate, change process), synchronize (semaphore), communication process (channels), communication with the environment (input/output), interrupt handling (clock, I/O) and time management (clock, interval timer).

4.1.6.1 Interrupt Service Routine By using ISR, Interrupt Service Routine, a special program sequence can be run with a certain interval. This sequence will interrupt the main program, with a certain interval, and execute the things that need to be checked with a certain interval. An example for this can be the position of a moving object. Otherwise the program might react on data that are not up to date, and not steer or stop when it should. Several programs can be run, for example every 100:th millisecond, but they can also be run with different intervals. Due to limitations in the compiler used in this work (the CCS freeware version has a limit of 2k signs in the code), this was not used in the final version of the program because the code got to big when the ISR was used.

Design and Implementation of an Embedded Real-Time System A Master’s Thesis by Paul Cedwall.

13

4.1.7 Scheduling In most cases, the numbers of processes are larger than the number of processors, which becomes a problem. The following questions have to be answered, to solve that problem:

1. How can the processor be shared? • Serial execution (cyclic executive). • Pseudo-parallel execution.

2. When should the change of process occur? • At natural stops (wait, delay). • At a change of state in the system. • At clock or I/O-interrupt.

3. What process should be running? • Scheduling.

Serial execution involves a process that executes until it terminates, and then starts the next process in line. Pseudo-parallel execution has several running processes that compete over the control of the processor, which also results in a scenario where a process is executing, but get terminated for the advantage of another process. The advantage for these kinds of executions is that the time for response gets very short.

There are two types of approaches regarding scheduling, static- and dynamic scheduling. Static scheduling is made before the processes are running, often before the system is taken into operation. In other words this means that the order of execution is set before the system is started. Dynamic scheduling makes the order of execution while the system is running. The processes are put in a queue and get access to the processor based on what priority the process has. Another option is to have a time-controlled sys tem or a case controlled system. In a time-controlled system, the processes are executed according to a known “timetable”. In a case controlled system the processes are executed as a result of an interior or exterior event in the system. A case controlled system demands support for dynamic scheduling in the system. There is also non-preemptive scheduling where a new scheduling decision is taken when no process is executing. The opposite for non-preemptive scheduling is preemptive scheduling where a new scheduling decision is taken as soon as the state of the system is changed, even during an execution.

4.2 ‘Flow diagram’ The instructions written in C have been written as the flow diagram in figure 10 indicates. It starts with some declarations and sets the different pins, on the QIC system, as in- or outputs as well as digital or analogue. Then it gets data from the encoder, a start data value that serves as a reference position, zero degrees.

Design and Implementation of an Embedded Real-Time System A Master’s Thesis by Paul Cedwall.

14

Figure 10. Flow diagram.

The program gets a reference value from the potentiometer that will be considered as the desired angle, turns the motor on and flashes the LED’s according to table 1. Reads new data from the encoder compares it with the start data value from the encoder and recounts the difference into degrees. The program gets into a loop until the encoder angle is within 10 degrees of the desired angle, then turns off the motor, waits and reads a new desired angle.

4.3 Operation system of the microprocessor Every processor needs an operation system. In this QIC system the operation system was the bootloader. The bootloading functionality is the most important part of the software and it is henceforth collectively referred to as the bootloader. The bootloader works as following, once it has given control to a program, it has no more control of the process until the system is restarted. The bootloader also has to ensure that no downloaded code overwrites any of the bootloader’s code space. The bootloader uses a function, Timer0(), and any other programs downloaded to the system can not use this function.

The bootloader allows users to upload programs via a serial cable connected to a PC, using a basic terminal program, the PIC programmer. The pins required to program the PIC16F877 are all brought out to the edge of the board. The bootloader provides a method to reprogram the microprocessor ‘on the fly’, which is essentially the definition of a bootloader. Since the total program memory space on the PIC is only 8KB, the bootloader should take up as little space as possible so that there is enough space to load a useful user program. It seems like the bootloader takes up half of the memory of the PIC. The bootloader can be built or simply downloaded from the Internet. On this system, the bootloader was already downloaded when the system arrived. But still a new one was downloaded to the system to ensure that the card was working all right.

4.4 The final Program In the final program the motor turns the encoder into a position, given by the reference value from the potentiometer. If the reading from the potentiometer is 200, the motor will turn around the encoder until it reaches a point between 190 and 210

Design and Implementation of an Embedded Real-Time System A Master’s Thesis by Paul Cedwall.

15

degrees, then the motor stops, the program goes into a delay- loop and then reads the potentiometer again and so on until the power is switched off or the construction fails to work. See chapter 4.2.

The function, getAngle(), measuring the angel given by the encoder has been copied from a program from the CD given by Quanser Consulting Incorporation. By comparing two different data from this function, a data value in degrees can be collected. Before the program goes into the while- loop, it measures a reference position (startvinkel) from the encoder, zero degrees, and by comparing all the new positions (nyvinkel), measured from the encoder, with the reference value, a value, in degrees, can be found (nyvinkel-startvinkel=vinkel). By looking in the instructions written in C at the end of this report, in the Appendix, it can be better understood.

The function tid(), is a delay function, that makes a lot of loops. The potentiometer’s, the reference generator, position is saved in the variable

analogvalue and will decide the position where the motor should make the encoder axis get to.

The LED’s can flash in four different ways, 00 01 10 11. It flashes as described in table 1. It is the angle/position of the potentiometer that decides the degree and therefore decides how the LED’s should flash. Deeper knowledge of the program can be found by reading the program, instructions written in C, in the Appendix.

4.5 The header files Header files are included in the instructions written in C and in this chapter a small explanation of the function of header files will be described. A header file is a file containing C declarations and macro definitions. If a header files is wanted to be used in a program, it has to be included by writing #include desired_file.h. The files supply definitions and declarations to make it easier to use some variables and makes the program easier to understand, since there is no need to write non understandable definitions. The header files contain declarations for interfaces between the source files of your program. Each time it is needed to have a group of related declarations and macro definitions all or most of which are needed in several different source files, a header file should be created for them.

Including a header file, produces the same results in C compilation as copying the header file into each source file that needs it. But such copying would be time-consuming and would increase the probability of errors. With a header file, the related declarations appear in only one place. If they need to be changed, they can be changed in one place, and programs that include the header file will automatically use the new version when next recompiled.

In this work the header files have been very useful because they have defined every pin on the QIC daughter board with understandable names, such as A0, A1, A2 and B2. Otherwise the instructions, written in C, would have been very confusing. Very often, one header file includes another. It could easily happen that a certain header file is included more than once, which might lead to errors. Therefore, it is desired to prevent multiple inclusion of a header file.

4.6 Compiler Throughout this Master’s thesis the compiler has played an important role. By reading other peoples opinions and recommendations of the different compilers, during the literature survey, a suitable compiler could be found. The different kinds of compiler that exist on the market today do not work the same way. Some are better than the others, but the better ones do of course often cost more. If it is very important that the

Design and Implementation of an Embedded Real-Time System A Master’s Thesis by Paul Cedwall.

16

HEX-file is small, a better program should be purchased. The HI-TECH compiler was regarded as the best available on the market, but it was also the most expensive ($1000) [9]. Since a lot of other Master’s thesis had used the CCS compiler with good results, it was used in this thesis as well. Most other works had been done on the version that could be bought, but the freeware was evaluated and it worked fine on the tests. The CCS compiler was used during the thesis, since it was simple to work with and because it was a freeware. The demo was the actual CCS compiler, with some restrictions such as:

• The compiler was licensed for only 30 days. This limit did probably not work, since it was used much longer during the tests.

• Luckily the compiler worked for the Microchip 14 bit PIC16F877, but there were a lot of compilers it did not work for.

• There was a 2K-program size limit, which was experienced when an interrupt service routine was included in the instructions written in C.

Some small modifications had to be done to the header-files to be able to compile the program correctly with the CCS compiler. The version used in the tests was the PCW Compiler (30 day evaluation), IDE Version 3.36, PCM Version 3.170d, PCH Version 3.170d from Custom Computer Services, incorporation [10].

4.7 Downloading files to the PIC To make the QIC system to run several steps have to be taken. First one must write the instructions in C-code. Secondly a bootloader, see chapter 4.3, has to be downloaded to the PIC. It can easily be downloaded with the PIC-downloader [17]. By applying 9-volts to J1 on the card and 12 volt to JP2, the ‘bootloader.HEX-file’ can be downloaded to the QIC system, see Appendix. The next step will be to convert the C-code into Hex-code by using a Compiler, but these will be discussed in the chapter 4.6. Then download it to the PIC16F877 microprocessor on the QIC-system. The bootloader only has to be downloaded the first time the system is used. The bootloader can be built, if one has some deeper knowledge, or it can be downloaded from the Internet. The bootloader takes up 50 to 60 percent of the available memory space on the PIC.

Figure 11. The different Pins on the processor core.[16]

Design and Implementation of an Embedded Real-Time System A Master’s Thesis by Paul Cedwall.

17

When the C-code has been compiled into HEX-code, it can be downloaded into the QIC system. This can also easily be done with the PIC-downloader, while 9-volts are applied to J1. The bootloader also makes sure that the bootloader file is not deleted or overwritten and its other task is to make the other downloaded files to run.

4.8 Summary In chapter 4.1 the reader of this thesis gets an introduction to the demands of a real-time system. The rest of chapter 4 describes the use of different programs necessary to design and implement the embedded real-time system.

Design and Implementation of an Embedded Real-Time System A Master’s Thesis by Paul Cedwall.

18

5 Conclusions This chapter contains a discussion of the results of the thesis as well as the conclusions. Since the question regarding if the QIC system is suitable as a laboration system or not, it will be described in chapter 5.1. Conclusions are drawn and presented in form of a list for easy reading in chapter 5.3. The final part of this chapter will suggest future work that can be done.

5.1 Suitable as a Laboration process? A lot of laborations, that is part of courses, sometimes make the student follow some instruction without making the student create something on its own. This will not make the student more secure about the theories learnt during the lectures, which should be the purpose of the laborations. Otherwise a simple demonstration, in front of the whole class would be better.

This QIC system can be a very good base for a laboration system, but it will need a program with a user interface where the students easily can vary different data to make the system work in other ways. To change data in the C code instructions might be done, but the possibility of making other changes by mistake makes this choice a bad one. Then the student has to compile the instructions and find the correct HEX-file, in the computer, and download with the PIC downloader program via the serial port of the computer through a cable to the QIC system. To make the QIC system available to receive information, a button on the system has to be pressed. When all is downloaded, this button has to be pressed once again to make the system run. Most of these steps can be done with a user interface program on the computer, so that the students don’t have to make all the steps on their own. Because then the students have to learn a lot of the procedures to make the instructions get into the system, instead of understanding how the system reacts to different inputs.

This card can be used for laborations for the students at the Royal Institute of Technology, but it needs some further development. Although a system in a virtual environment should probably be more suitable, since the system would need a structure that did not change at all. Otherwise the task would not be the same during a lot of tests. In the way it is built now, a simple punch will destroy the whole process, since it is built with the help of some Lego-pieces. A system like this can work as an example of how the information, learnt during a course, can be applied in a real life situation. A lot of courses get quite theoretical and the student might want to know if the theories can be used or not on a real embedded system.

5.2 Result In this Master’s thesis, a lot of tests and theories have been tried out. Since the system did not have any display attached to it, the troubleshooting process got quite complicated. The only output used to check the values of the different variables, was the two LED’s that were flashed in four different ways, 00 01 10 11, to show in what region the data was in at the different situations.

With this QIC system new assembler code can be sent, new instructions compiled into a HEX-file, down to the microprocessor via a cable attached to the Serial port on the computer. Then the new instructions for the microprocessor will start to execute. The bootloader makes it possible to receive and transmit the new code to the board. When the board receives a new code through the serial port it puts the code in the memory and start to execute it.

Design and Implementation of an Embedded Real-Time System A Master’s Thesis by Paul Cedwall.

19

This QIC system can be suitable as a laboration process in a course at the Royal Institute of Technology, but that will have to be completed in another Master’s thesis, since it will involve quite a lot of work. The QIC is, according to the author of this Master’s thesis, best suited as a base for a demonstration example.

The QIC system has shown some very good qualities during this Master’s Thesis. It can be varied into a lot of different types of projects. The System can be run with a 9-volt battery to make it portable, but a power box is strongly recommended to keep the system running without any interrupts in the power supply.

In this thesis the compiler used had some limitations, as in the size of the instructions, which made it difficult to make more advanced tasks to be compiled, as an ISR (Interrupt Service Routine).

When instructions written with a lot of functions, outside the main function and called from the main function, the data from the encoder and the potentiometer did not work as they should. In this case a display, attached to the system, would have made the troubleshooting process a lot simpler.

The software to the final version that worked on the system is attached in the Appendix to this report, and written in C. This can be compiled into a HEX-file using the CCS freeware program [10]. The version used in the last tests was the PCW Compiler (30 day evaluation), IDE Version 3.36, PCM Version 3.170d, PCH Version 3.170d from Custom Computer Services, incorporation. By using this compiler and by following the description in the Appendix, the system can be recreated.

5.3 Comments on the results

Experiences learnt working with the QIC system with the PIC16F877 microprocessor are:

• To keep the instructions, the program written in C, simple. Otherwise the different data from the encoder and potentiometer will probably get into regions that they usually do not get into. The RAM memory of the microprocessor was too small and experienced difficulties with too much going on at the same time.

• A display, attached to the card would help troubleshooting. By displaying the data one can quickly find out where the faults in the tested files are. The two diodes, used in this work, gave a hint where the values of the data were, but it takes some time to find out exactly what the values of the different variables during the tests.

• The QIC system will be best suited as a demonstration example. • The CCS compiler worked satisfactory, but due to limitations on the version

used, the instructions had to be kept simple. • To be able to use the compilers, the user has to have some knowledge in

writing C. All the compilers tested during this Master’s thesis would only work on instructions written in C.

The author’s knowledge in writing instruction in C, use Compiler, handling with a QIC system and trying to get information has definitely increased. The final version of the system was a success, see figure 12, and will be helpful for showing what can be built and created in a Master’s thesis as well as evaluating the possibilities of building a laboration process.

Design and Implementation of an Embedded Real-Time System A Master’s Thesis by Paul Cedwall.

20

Figure 12. The final working structure.

5.4 Future works One idea on a future laboration project is the model shown in figure 13. It includes a motor with a propeller attached to it. This would blow a board, attached to the encoder, so it would lean in a certain angle. The encoder would measure the angle and when the angel becomes too big, 45 degrees from the vertical position, the motor should stop blowing. It should start blowing again when the angle is below 20 degrees. The blowing direction is marked with an arrow in figure 1. This would require some construction work, and a large propeller.

Figure 13. A suggestion of a model.

Design and Implementation of an Embedded Real-Time System A Master’s Thesis by Paul Cedwall.

21

References [1] Information on the QIC system and a QIC User’s Guide. http://www.quanser.com/ Accessed on 2003-03-21 [2] Information on Real- time systems from a course at Chalmer institute of

technology, Gothenburg. http://www.ce.chalmers.se/undergraduate/D/EDA221/#AKTUELLT Accessed on 2003-02-17 [3] Information on Real- time systems from a course at Lund Institute of

technology, Lund, Sweden. http://www.control.lth.se/~kurstr/ Accessed on 2003-01-31 [4] Electronic parts. http://www.allelectronics.com/ Accessed on 2003-03-17 [5] Data sheet for PIC16F87X.

http://www.microchip.com/download/lit/pline/picmicro/families/16f87x/30292c.pdf

Accessed on 2003-04-14 [6] Downloaded the header file 16F877.h, used during most testes.

http://www.ifi.unizh.ch/groups/ailab/people/lunga/Tech/Software/RunningDog/

Accessed on 2003-08-29 [7] Information on the potentiometer. http://www.mouser.com/catalog/specsheets/143103.pdf Accessed on 2003-01-31 [8] Technical data on the encoder. http://www.usdigital.com/ Accessed on 2003-07-01 [9] Downloading the HI-TECH freeware compiler. http://www.hitech.com.au/ Accessed on 2003-06-11 [10] Downloading the CCS freeware compiler. http://www.ccsinfo.com/ Accessed on 2003-06-19

Design and Implementation of an Embedded Real-Time System A Master’s Thesis by Paul Cedwall.

22

[11] Information and description of the PIC16F877 in another Master’s thesis. http://mobile.act.cmis.csiro.au/documentation/thesis/thesis.pdf Accessed on 2003-05-09 [12] Information on the PIC16F877. http://www.ep.liu.se/exjobb/itn/2002/de/248/exjobb.pdf Accessed on 2003-10-31 [13] Information on difficulties in programming C.

http://developer.apple.com/documentation/DeveloperTools/gcc-3.3/cpp/Header-Files.html

Accessed on 2003-10-31 [13] Brian W. Kernighan and Dennis M. Ritchie. The C Programming Language,

Second Edition. Prentice Hall, Inc., 1988. [14] QIC User’s Manual, Quanser Consulting inc., 2001. [15] QIC Carrier V2 Manual, Quanser Consulting inc., 2002. [16] QIC Processor Core V16 User’s Manual, Quanser consulting inc., 2002. [17] PIC downloader. http://www.ehl.cz/pic/pic_e.htm Accessed on 2003-11-01

Design and Implementation of an Embedded Real-Time System A Master’s Thesis by Paul Cedwall.

I

Appendix

Hints of steps to follow in startup To be able to recreate this project, all the components in chapter 5 have to be brought together. The QIC system, CD from Quanser, encoder, potentiometer, LED’s, motor, personal computer and Lego, for making the construction hold together, has to be used. A power supply that delivers 9 volt and another that delivers 12 volts also has to be included as well as some wires. The instructions, written in C, can be found in the Appendix at the end of this report. The header files necessary, found on the cd from Quanser incorporation, will have to be downloaded to the same file as the instructions. The instructions have to be compiled into a HEX-file using a compiler. The compiler used was the freeware program, downloaded on http://www.ccsinfo.com/, ’PCW Compiler (30 day evaluation), IDE Version 3.36, PCM Version 3.170d, PCH Version 3.170d’ from Custom Computer Services incorporation. By reading the instruction to the compiler, the instructions written in C can be compiled into a HEX-file. The HEX-file has to be downloaded from the personal computer using a cable connected to the serial port on the computer and the other end to the programming port on the daughter board of the QIC system. The program that transfers the file to the system is the ‘PIC downloader 1.07’ [17].

Figure I. PIC downloader.

Here comes a step-by-step instruction on how to recreate the final version of the system built in this Master’s thesis:

1. Apply power, 9-volts, to J1 on the QIC motherboard, then apply 12-volts to JP2, on the daughter board. Put a Jumper on JP1, see figure 7.

2. Connect the cable, from Quanser, between the serial port on the PC, and the programming port on the QIC daughter board. The part of the connection, on the QIC connection side, that is marked red should be close to pin1.

3. Start the ’PIC downloader 1.07’, press [F2], mark the bootloader.HEX file on the cd from Quanser. Press Write, press the reset button S1 on the daughter board. This will put the QIC into programming mode and the process of downloading the HEX-file will initiate. When the file has been downloaded, press the button S1 again.

Design and Implementation of an Embedded Real-Time System A Master’s Thesis by Paul Cedwall.

II

4. Now the bootloader has been installed on the QIC system and the 12-volts applied to JP2 on the daughter board can be removed, since this is only necessary when downloading the bootloader. Remove Jumper on JP1.

5. Create a folder on the PC and download the files q_config.h and encoder.h from the cd from Quanser. Another file used was the 16F877.h, the address where this file can be found is written in the references. Download the instructions found in the Appendix of this report and put it in the same folder.

6. Compile the instruction using the compiler from CCS inc. 7. Start the ’PIC downloader 1.07’, press [F2], mark the finalversion.HEX in the

folder created above. Press Write, press the button S1 on the daughter board and when the file has been downloaded, press the button S1 again.

8. Connect the wire on the right side of the potentiometer to pin 36 (VCC), the left one to pin 18 (GND) and the middle one to pin 12 (RA0) on the daughter board.

9. Connect the red wire on the motor to pin 7 (RB6) or pin 8 (RB7), because they work the same way in this program, and the other wire to pin 12 (GND). This means there will be two wires connected to pin 12, but the motor needs an extension wire to its wires and the extension wire can easily be connected to the bottom of pin12.

10. Connect the encoder to J3 on the QIC motherboard with the GND away from the daughter board, se Figure 4.

11. The first LED can be connected to pin4 (RB3) and GND on JP2 on the QIC daughter board. The second LED connects to pin 3 (RB2).

12. Build a Lego structure where the motor and encoder axles are connected. 13. Press the button S1 on the daughter board. 14. Now the system should be running and all should be working just fine.

Design and Implementation of an Embedded Real-Time System A Master’s Thesis by Paul Cedwall.

III

Final version of the instructions written in C ///////////////////////////////////////////////////////////////////////////////////// // // finalversion2.c // When the potentiometer is moved, the LED's flash differently, depending on // the position of the potentiometer.... // 0-90--black,90-180--black->one flash, // 180-270--black->one flash->another flashes, // 270-360--black->one flash->another flashes->two flashing LED's // The motor moves the encoder to the position decided by the potentiometer.... // All the code is based on programs from Quanser consulting inc. // (Due to bad lego-construction,the encoder might not stopp at the exact position..) // Compiled with Custom Computer Services, inc. // PCW Compiler IDE Version 3.36 // PCM Version 3.170d // PCH Version 3.170d /////////////////////////////////////////////////////////////////////////////////////// #include <q_config.h> #include <encoder.h> //Gives values to create the encoder axis position in degrees float getAngle(); float tid(); // the variables to hold the conversion parameters float high_m, calx1, calx1_mid, calx1_high, offset_x1; void main() { double analogvalue, max, min, flagga=0, test=0;//analogvalue=potentiometer double startvinkel=0, nyvinkel=0; //ref. angle and a testangle double vinkel; // // calculate the calibration parameters calx1 = 360./4096.; // conversion from encoder counts to degrees calx1_mid = calx1*256; // multiplication factor for the middle byte (in degrees) calx1_high = calx1_mid*256;// multiplication factor for the upper byte (in degrees) offset_x1 = ((calx1*256.)*256.)*128.; // factor to account for negative values set_tris_a(ALL_OUT); /* PORTA is set as all inputs */ set_tris_b(ALL_OUT); /* PORTB configured as 11110100 */ set_tris_c(0b10000000); /* PIN RC7 is serial RX from HOST */ set_tris_d(ALL_OUT); /* PORTD is all digital OUTPUTS */ set_tris_e(ALL_OUT); /* PORTE is all digital OUTPUTS */ PORTB = 0xFF; // finally, we setup the analog input channels. We will be reading on RA0 setup_port_a(A_ANALOG); // Configure Port A and A/D to use all analog channels setup_adc(ADC_CLOCK_DIV_32); // Set the A/D clock frequency set_adc_channel(0); // Setup A/D channel 0 for reading

Design and Implementation of an Embedded Real-Time System A Master’s Thesis by Paul Cedwall.

IV

delay_us(10); // small delay to make sure A/D convevrter is ready init_encoder(ENCODER0); // initialize the encoders first! tid(); //delay read_encoder(ENCODER0, X_AXIS); //from J3 startvinkel= getAngle(); //get startvalue tid(); output_high(PIN_B3); //Turn on diod-test output_high(PIN_B2); //Turn on diod-test tid(); output_low(PIN_B3); //Turn off diod-test output_low(PIN_B2); //Turn off diod-test tid(); while(1) { analogvalue = read_adc(); // read the analog voltage analogvalue=(analogvalue+1); // Makes it zero from the beginning output_high(PIN_B7); //Turn on motor output_high(PIN_B6); //Turn on motor max=analogvalue+10; if (max>360){ While(max>360){ max=max-10; test=test+10; } max=test; test=0; } min=analogvalue-10; if (min<0){ While(min<0){ min=min+10; test=test-360; } min=test; test=0; } //Diodes show the position of the potentiometer If(analogvalue<90){ output_low(PIN_B3); output_low(PIN_B2); tid(); } If(analogvalue<180){ output_low(PIN_B3); output_high(PIN_B2); tid(); }

Design and Implementation of an Embedded Real-Time System A Master’s Thesis by Paul Cedwall.

V

If(analogvalue<270){ output_high(PIN_B3); output_low(PIN_B2); tid(); } If(analogvalue<360){ output_high(PIN_B3); output_high(PIN_B2); tid(); } while(flagga<1){ //flagga=flag in swedish read_encoder(ENCODER0, X_AXIS); // read the encoder J3 nyvinkel= getAngle(); //get second value vinkel=nyvinkel-startvinkel; //vinkel=angle in swedish nyvinkel=new angle while(vinkel>360){ vinkel=vinkel-360; } if(vinkel>min){ if(vinkel<max){ output_low(PIN_B7); //if the encoder is in position, motor off output_low(PIN_B6); //if the encoder is in position, motor off tid(); //tid=time in swedish tid(); tid(); tid(); tid(); tid(); flagga=1; }//end if max }//end if min }//end while flagga flagga=0; } //end while(1) } // returns the angle in degrees computed from the values in the array encoder_data[] // defined in encoder.h // byte zero, encoder_data[0] contains the lowest order byte (bits 0 - 7) // byte two, encoder_data[2] contains the higest order byte (bits 16 - 23) // note that the 23 bit is the sign bit, and when set to a 1 indicates a negative value. // See the code below for details on how to calculate the angle in degrees. float getAngle() { //function copied from Quanser inc. test programs float x1; // mask off the sign bit to do angular calculation high_m = encoder_data[2]&0x7f; x1 = calx1 * encoder_data[0] + calx1_mid * encoder_data[1] + calx1_high * high_m; // compute the offset if the angle was negative

Design and Implementation of an Embedded Real-Time System A Master’s Thesis by Paul Cedwall.

VI

if((encoder_data[2]&0x80) == 0x80){ x1 = x1 - offset_x1; } // return the computed angle return x1; } float tid() { //delay function unsigned long i=0, j=0, p=0; while(i!=20000000000){ i=i+1;} // delay 2sek? while(j!=20000000000){ j=j+1;} // delay 2sek? while(p!=20000000000){ p=p+1;} // delay 2sek? return 0; }

Design and Implementation of an Embedded Real-Time System A Master’s Thesis by Paul Cedwall.

VII

The explanation of the different pins

Figure II. The names of the different pins.[14]

Design and Implementation of an Embedded Real-Time System A Master’s Thesis by Paul Cedwall.

VIII

QIC Starter Guide This document has been designed to give a brief introduction to the QIC Development System. The tutorial will take you through a sequence of steps, which should be followed when working with embedded systems. Before attempting to start programming the QIC please read through this guide once. This guide will take you through the steps of designing the serial cable, installing software and test program. Making the QIC serial programming cable Two approaches will be described. The first approach is to purchase all the required parts and the second is to purchase and hack a DB-9 serial cable. Required parts: • Ribbon Cable (6 wires) or DB-9 cable with two female connectors • Female DB-9 solder tab connector • 6 pin Female header Socket and pins See Figure (1) for connections. QIC Software Installation This section will describe how to install the software required for the development the use of the QIC development system. You have to install three different modules; “QIC Serial Programmer”, “QIC Commander” and the “Bootloader”. QIC Serial Programmer

1. Insert the QIC CD-ROM into the CD-ROM drive. 2. Open File Explorer and select the CD-ROM drive. 3. Double click QICProg_1_00_setup9x.exe and follow the setup procedure. 4. Select the default C:\Program Files\Quanser\QICProg installation directory

when installing.

QIC Commander To use the QIC Commander, copy the 'QICCommander' folder from the QIC CD-ROM to C:\Program Files\Quanser\. If QIC commander installed under another directory then the QP.bat file located in QICCommander directory must be modified to reflect those changes. Bootloader Bootloader is a freeware software, which can be downloaded from the Internet, but is also included on the QIC CD-ROM. Follow the installation instruction in the

Design and Implementation of an Embedded Real-Time System A Master’s Thesis by Paul Cedwall.

IX

bootloader documentation. Once the bootloader software is installed, the next step is to download the bootloader program to the QIC motherboard. This is done by applying +12V to the programming pin and enabling the programming jumper. See Diagram. Download the bootloader to the QIC motherboard is a one-time task, unless the bootloader is erased accidentally. Use the bootloader windows software to download your program to the QIC motherboard. QIC Programming This section will describe how to program the QIC using two methods. QIC can be programmed using QIC Serial Programmer in High Voltage Programming (HVP) mode or using a Bootloader. Both methods are described in detail. QIC Serial Programmer Note: You only need to use High voltage programming when installing the bootloader. This is a one-time task.

1. Jumper JP1 on the QIC Motherboard. 2. Use a jumper wire from pin 1(square pad) of JP2 to pin labeled +12V on the

QIC Daughter board. 3. Connect the Serial cable (Green wire -> Pin1 (square pad) and Black wire ->

Pin6 on the QIC Serial Header). 4. Execute QIC Serial Programmer.exe 5. Select the correct COM port by clicking Setup -> Serial Port -> COMx. 6. Execute QICProg and open 62019 - bootldr-16F876-77-20Mhz-19200bps.hex. 7. Apply Power to board. 8. Click Write. 9. Press the reset button on the QIC Motherboard. 10. Message comes up confirming that the bootloader program has been installed

correctly. 11. Bootloader has been installed. 12. Remove Jumper JP1 and the Jumper wire connecting Pin1 of JP2 to +12V.

This is very important. 13. QIC is ready to be programmed using Bootloader.

Boot Loader 1. Compile the qled.c file and connect an LED as describe in qled.c. Note: Make

sure you have 200 - 500 ohm resistor in series with the LED. 2. Execute Pic_downloader.exe. 3. Select the correct COM port and select 19200 baud. 4. Open qled.hex. 5. Click "write". 6. Press the reset button the QIC Motherboard. 7. Massage verifies that the program has been written.

QIC Test 1. Compile loopback.c using CCS PICC compiler. Skip this step if you do not

have the CCS PICC compiler. You can purchase a copy from CCS or download a demo version. http://www.ccsinfo.com/demo.shtml

2. Connect a loopback cables from A/D0 to D/A0 and A/D1 to D/A1. Note: Make sure JP3 and JP4 are configured to use the D/A. See QIC Users Manual. Enable J6 (Low-pass filter1) and J7 (Low-pass Filter2). Enable Vref by placing a jumper on JP10.

Design and Implementation of an Embedded Real-Time System A Master’s Thesis by Paul Cedwall.

X

3. Download the loopback.hex code to QIC Motherboard via serial cable using QIC Programmer or the Bootloader. Note: The Bootloader must reside on QIC prior to downloading user program.

4. Execute QIC Commander by double clicking QP.bat file. 5. Click x2 so it turns blue. Press the Connect button to connect to QIC. 6. Two-triangle waveform should be observed. 7. Check or re-configure the QIC software if step 6 was unsuccessful.