2005:E01
2005-06-03
Department of Technology, Mathematics and Comcuuter Science
A general interface for computer control in real time
Ulla Carlsson DI02
A general interface for computer control in real time
Ulla Carlsson DI02
Summary
This degree project completes a degree at the University of Trollhättan/Uddevalla, Department of Technology, Mathematics and Computer Science. The study program is Computer Engineering, Industrial IT.
The degree project is about communication between a PC (Personal Computer), a general purpose box and a pendulum system. The most important task in this project is to get the different parts to communicate between each other.
The general purpose box is built in a pre project, the communication between the general purpose box and a PC is solved.
The programming is made in C for the AVRX real-time kernel environment.
A literature study is done about the LQG-control with a Kalman filter.
Publisher: University of Trollhättan/Uddevalla, Department of Technology, Mathematics and Computer Science, Box 957, S-461 29 Trollhättan, SWEDEN
Preface
I would like to thank everyone who helped or encouraged me through the project and under my education. Especially to Anna-Karin Christiansson for her support and help.
Hans Dahlin for that I could share his hardware knowledge and life experience. Fredrik Danielsson and Mattias Ottosson for help with the C code. Christer Selvefors for using his scanning eyes to help me find the problem in the C code and the knowledge how to program he teach me in the JAVA course. I also will thank Lena Esser and Fredrik Gustavsson for their encourage.
A special thank to my husband Lars and my children Caroline and Hampus for their patience with me through my education.
ii
Contents
Summary...i
Preface ... ii
1 Introduction...1
1.1 Purpose and Aim...1
1.2 Background...1
1.3 Delimitation ...1
1.4 Software ...2
1.5 Hardware ...3
2 Hardware description...4
2.1.1 The Sensor HEDS-9100... 4
2.1.2 Sensor for the Pendulum Arms Angle... 5
2.1.3 Cart Position Sensor... 5
2.1.4 Facts on the Cart and Pendulum Arms Encoder... 5
2.1.5 Program Code for Reading the Encoders... 7
3 Communication between the System Parts...9
3.1 Initializing the Environments for Communication ...10
3.2 Programming Real Time Application ...10
3.2.1 Main Function ... 11
3.2.2 Task1, Testing the DC-Motor ... 11
3.2.3 Task2, Reading the Encoders... 12
3.2.4 Task3, The Communication ... 12
4 Control Design...12
4.1 Linear Quadratic Control...12
4.2 The Pendulum System ...13
4.3 The Mathematic Model of the Pendulum System...13
4.4 The Model used in Simulink...14
4.5 Kalman Filter...14
5 Result ...15
5.1 Result from the Communication Part ...15
5.1.1 Reading the Sensor Code ... 15
5.1.2 The Connection between Microcontroller Unit and HyperTerminal ... 15
5.1.3 Reading the Register and Write the Result in MATLAB... 15
5.1.4 Read Encoder and Control the Cart Movement ... 16
5.1.5 Summary of result... 16
6 Conclusions...16
6.1 Recommendation for Possible Further Work ...16
7 Personal Reflection...17 Appendices
A Program Code for the microcontrol unit
Figure
Figure 1 Parts of the Feedback hardware for the Pendulum system. ... 3 Figure 2 Principle for the encoder HEDS-9100, see appendix E. ... 5 Figure 3 The four states the channels could have... 7 Figure 4 The output of an encoder consists two signals denoted A and B, one shifted 90º (electrical degrees) with respect to the other... 8 Figure 5 Block diagram of the communication between the system parts... 9 Figure 6 Communication between PC and general purpose box through the com port... 9 Figure 7 Model of the pendulum system (Source electronic, see ref [2]). ... 13 Figure 8 Simulink model of the pendulum system in (2), see the UMICH homepage for details... 14
Table
Table1 Explanation of the relation between cycle, shaft rotation, electrical or mechanical degree and bar or window pair... 5 Table 2 Translation between the value in the register for the angle from the
pendulumarm sensor and the cart movement from the motor sensor... 6 Table 3 The chosen parameters for initializing the communication port. ... 10 Table 4 Port configuration for the Atmega16 microcontroller unit... 11
iv
List of symbols
AVRX – Program from the company Atmel, used to program in real time.
CPR - Counts Per Revolution DIP - Dual In line Package
HTU - The University of Trollhättan/Uddevalla IO – In and Out
LED - Light Emitting Diode MCU - Micro Controller Unit PC - Personal Computer
PCI - Peripheral Component Interconnect UDR – Universal Data Register
USART – Universal Synchronous and Asynchronous Receiver and Transmitter
1 Introduction
This degree project completes a degree at the University of Trollhättan/Uddevalla, Department of Technology, Mathematics and Computer Science. The study program is Computer Engineering, Industrial IT.
1.1 Purpose and Aim
The degree project is about communication between a PC (Personal Computer), a general purpose box and a pendulum system. The aim is to increase the knowledge of controlling a real system using modern tools. The most important task in this project is to get the different parts to communicate between each other.
1.2 Background
The University of Trollhättan/Uddevalla (HTU) has since long an inverted pendulum system. The hardware and software used for this pendulum system is too old for efficient use with modern computers. The intention from the school is to replace these.
The new hardware should also be able to work together with other equipment. The new box should be more general than the old one. The development of the general purpose box started in a project course as a preparation for the degree project. The general hardware box contains a MCU (Micro Controller Unit) with its driver circuits, and the intention is to use this instead of a PCI (Peripheral Component Interconnect) card connected to the PC. This makes the box movable between different PCs. The microcontroller unit will take care of the communication between the PC and the pendulum system. The box also includes a power supply, see appendix E. The old system has many functions, a crane system demonstration and an inverted pendulum demonstration. The new system should also have these functions, but for this degree project, the aim is at least to have a working crane system.
1.3 Delimitation
The software program MATLAB with Simulink, see 1.4, is the program that should control the pendulum system. A linear quadratic regulator with a Kalman filter should be as controller. The communication should be able to solve with standard serial port IO commands from MATLAB.
1
1.4 Software
Software used in the degree project.
• Microsoft® Word 2002 is used to write the degree project report.
• MATLAB 6.5 version 13 is used for communication, simulation and modelling with
Control System Toolbox, version 5.2
Simulink version 5.0
• Programmers Notepad version 2.0.5.18-mingus is used to create the C-code.
• AVR® studio 4.0 is the environment for the program code used for programming an Atmel microcontroller unit ATmega16.
• AVR®-GCC 2.97 is the compiler used.
• AVRX version 2.6e is used for real in time programming
1.5 Hardware
Under the development phase the starter kit STK500 [10] has been used instead of a built in microprocessor for testing the programming of the microcontroller unit. In addition, a developer’s box (HTU) with DIP-switches (Dual In line Package, a series of tiny switches built into socket) and LED (Light Emitting Diode) have been used for different tests.
The pendulum system, see figure 1, from the company FEEDBACK [11] consists of:
• A cart with two hanging pendulum arms and a rail for the cart with a driving belt.
• A 24 [V] DC-motor for driving the belt for the cart on a rail.
• Two Incremental Optical Encoders, one for the cart location and the other for the pendulum arm angle.
• A hardware box, which will be replaced by a general purpose box, see appendix E.
Figure 1 Parts of the Feedback hardware for the Pendulum system.
Documentation about the inverted pendulum, see FEEDBACK documentation [11].
DC-motor Cart
Pendulum arms Angle θ
Rotating wheel Driving belt
Rail
3
2 Hardware description
A description about the hardware used in this degree project see appendix E. The theory about how and what to know about the sensor HED-9100 is described below.
2.1.1 The Sensor HEDS-9100
Picture 1 The picture is from the cart showing the sensor with a codewheel assembled to the pendulum arms axis.
There are two optical incremental encoders, HEDS-9100A00 used with a codewheel for measuring angles. These modules detect rotary position. The modules consist of an emitter section and a detector section. Such encoders are often used in printers, plotters and factory automation equipment. They are not recommended for use in applications that are safety critical as ABS (Automatic Braking Systems) applications, life support systems and power steering. One of the encoders is indicating the cart position and the other the pendulum angle, see appendix E. Each optical sensor has an encoder with two digital channel outputs (channel A and channel B) and a single 5 [V] supply input
or relative encoder measures the distance of the movement. Therefore, it is important to note the start value of the position of the codewheel.
Figure 2 Principle for the encoder HEDS-9100, see appendix E.
2.1.2 Sensor for the Pendulum Arms Angle
The pendulum sensor reads the relative angular distance that the arm has moved since the encoder was reset. The sensor is assembled inside the cart and its output is available at a flat wire cable connected to the general purpose box.
2.1.3 Cart Position Sensor
The cart position sensor, assembled to the DC-motor axis, reads the distance that the cart has moved since the encoder was reset. The sensor is assembled to the motor axis and its output is available at a flat wire cable connected to the general purpose box.
2.1.4 Facts on the Cart and Pendulum Arms Encoder
The codewheels have 512 counts per revolution (CPR) or number of bar and window pairs. Table 1 explains the relation between cycle, shaft rotation, electrical or mechanical degree and bar or window pair.
Table 1 Explanation of the relation between cycle, shaft rotation, electrical or mechanical degree and bar or window pair.
Cycle Shaft rotation Electrical/mechanical degree Bar or window pair
1 360 electrical º 1
512 1 360 mechanical º 512
5
One cycle has four states depending on the A and B channels: 00, 01, 11 and 10. The first position represents channel B and the second channel A. When value 01, channel B is low and has the value 0 and channel A is high and has the value 1. In program code, see appendix A, a register pendelA (pendulum angle) and motorA (cart position) are increased or decreased ones per cycle. The different registers used in program code are explained below. By manually rotating the pendulum arms 180º (mechanical degrees) the changes of the pendulum register pendelA or motorA were displayed on the LEDs on the additional developer’s box. The result 180º was equivalent to the value 256 in the register. The same type of test was made for the cart position sensor by turning round the driving wheel and measuring the movement. The result 0,16 [m] was equivalent to the value 512 in the register. Data useful for the calculating part of the system see table 2. It is a translation for the cart movement against the value in the register and also the pendulumarms movement.
Table 2 Translation between the value in the register for the angle from the pendulumarm sensor and the cart movement from the motor sensor.
Value of the register Angle [º] Length [m]
pendelA: 1 0,703
motorA: 1 3,1 10-4
The angle resolution presented in equation (1) is if the program code is written such that every state change is increasing or decreasing in the register.
] [ 00307 , 2048 0
2 ≈ rad
=
∆ϕ π (1)
2.1.5 Program Code for Reading the Encoders
BA=XX 00 Increasing
10 01
11
Decreasing
Figure 3 The four states the channels could have.
The program code for the encoders is written in the language C on the PC and loaded into the microcontroller unit, see appendix A. Channel B is the first digit and channel A is the second digit in the state description. It is the change of state for channel A (the programmers choice) that is used as indication of a rotation, see figure 3. If the value of channel A is one and it was zero before, then it is interesting to know the value of channel B. This indicates the move of the pendulum arm or the cart. A variable is increased or decreased in a register depending on from which direction the pendulum arms or the cart comes. If the pendulum arms or the cart moves anticlockwise, the state changes from 00 to 11, passing through 10 then ”channel B is in lead” and the register is decreased. The opposite situation, clockwise, passing through 01 “channel A is in lead”
and the register is increased, see figure 4. The text ‘Encoder moves right to left’ in figure 4 means an anticlockwise rotation and ‘Encoder moves left to right’ a clockwise rotation.
7
Figure 4 The output of an encoder consists two signals denoted A and B, one shifted 90º (electrical degrees) with respect to the other.
Example of how the program code for determining how to handle the registers.
Following names are used in the program code for the different registers:
Value reads from the sensors: pendel and motor.
The old value from the sensor saved in this register: opendel and omotor.
The registers that will be increased or decreased depending of the situation: pendelA and motorA.
if (motor = = 0x00) // If channel A and B is 00 { if (omotor = = 0x20) // If the old value was 10
++motorA; // Increase motorA register
else if (omotor == 0x10) // If the old value was 01
--motorA; // else decrease motorA register omotor = motor; // Remember the old value
}
3 Communication between the System Parts
The communication between the system parts are shown in figure 5.
General
purpose box with the mcu Atmega16
Dc-motor OUT
Figure 5 Block diagram of the communication between the system parts.
The communication between the PC and the general purpose box (RXD and TXD) is through the microcontroller unit ATmega16 see appendix E with a RS232D port with a 9-pin socket, see ref. [6]. The American standard EIA-232D consists of Std ISO2110, instructions V.28 and V.24. ISO2110 describes the configuration of the 25-pin socket (DB-25). In this project, the DB-9 socket is used. V.28 defines voltage, current and resistance and V.24 defines the way circuits are set up for an interface between computers or other terminal equipment and data communications equipment.
The standardized method of sharing data USART (Universal Synchronous and Asynchronous Receiver and Transmitter) inbuilt in the microcontroller unit is used for the serial communication, see ref [7].
The MATLAB program in the PC, see appendix B, will use the information about the actual data from the encoders handled by the microcontroller unit, for calculating how the system should behave as inputs to the controller. This is done with the serial communication port. See figure 6.
Figure 6 Communication between PC and general purpose box through the com port.
PC with MATLAB and HyperTerminal
RXD
Sensors
TXD IN
PC General purpose box
Atmega16 MATLAB
Com1 Com1
9
3.1 Initializing the Environments for Communication
There is some initializing to do before it is possible to use the com port for communication between the PC and the general purpose box. This configuration should be identical for the serial port in MATLAB, the hardware file for the microcontroller unit and the port configuration for the PC. In this work, the communication parameters are chosen as in Table 3.
Table 3 The chosen parameters for initializing the communication port.
Baud rate / bits per second 19200
Data bits 8
Parity None
Stop bit 1
Flow control None
The microcontroller unit clock frequency is initialized to 8 [MHz].
3.2 Programming Real Time Application
Programming for real time applications implies that a couple of processes are to run, as it looks like, at the same time, see ref [8]. However, since a simple microcontroller unit cannot work in real “real-time” or as a PC, the software AVRX solves this problem by using the Round Robin principle, see ref [8]. AVRX software supports ready-made functions to use as a timer delay, interrupts etc, see ref [12]. Three tasks are used in this project, Task1 Testing the DC-motor, Task2 Running the encoders and Task3 The communication. They run simultaneously in this application. The different tasks are running one at a time. After a while an interrupt occurs when a delay routine is running checking if a new task is waiting in the queue. This is the way for changing between the tasks. When a new interrupt appears, the information from the running task is stored on the stack, while the new task fetches its former information from the stack. This principle makes it possible to do many different things “simultaneously” on the microcontroller unit. This will not delay the process if something is waiting for an event. It is also possible to use priority but in this case, the three tasks are given the same priority. In this work, Task1 was used for manual setting the speed for the DC- motor using DIP-switches. Task2 was reading the sensors and Task3 was handling the communication part. See appendix D for a simple user guide about the programming environment.
3.2.1 Main Function
The main function initializes the ports and their registers, the stack, allowed sleeping mode and sets timer interrupt. The function AvrXRunTask that starts up the tasks is also placed in the main function. PortA and PortB are used in the development phase and are thereafter free to be used for other things. See Table 4 for disposition of the microcontroller unit ports. If the development box (HTU’s own) not is used, then it is necessary to examine how PortD pin 0 and 1 should be configured depending of which hardware is used.
PortB is used under the development phase to display the value in the register on the LEDs. This is a way to see if the processes work as specified. When for example the pendulum arms stop moving, the LEDs should stop at the correct value. Table 4 shows how the port configuration is set up for the Atmega16 microcontroller unit. Inport is the same as input and outport is the same as output. These words are common for the microcontroller language.
Table 4 Port configuration for the Atmega16 microcontroller unit.
Port configuration Pin configuration Used for
PortA Pin 0 – 7, inport Under the development
phase used for manual control of the motor speed
PortB Pin 0 – 7 ,outport Under the development
phase used for the LED’s
PortC Pin 0 – 7, outport Voltage to the DC-motor
PortD Pin0, inport
Pin1, outport Pin4, inport Pin5, inport Pin6, inport Pin7, inport
USART, RXD “ , TXD
Pend. sensor Channel A “ “ “ B Motor “ “ A “ “ “ B 3.2.2 Task1, Testing the DC-Motor
This task was used for testing that the general purpose box could give the motor enough voltage to drive the cart forwards and backwards. Se appendix A and the comments what happened during the test.
11
3.2.3 Task2, Reading the Encoders
See flowchart appendix C. Task2 will take care of the encoder information. The code first reads the value of the pins, masks the results for the cart sensor and stores it in the motor variable. Then a comparison is done, and after finding the right condition the specified action is performed. The same procedure applies for the pendulum arms sensor. See appendix A and the comments about the code.
3.2.4 Task3, The Communication
Task3 will take care of the communication part. The function read_USART is waiting until something appears in a register UDR (Univeral Data Register). In this project a code is written in MATLAB that sends the action to the UDR register through the com port. A character or a character with a numeric value will sometimes come from MATLAB, depending on what the specified action demands. See appendix A.
4 Control Design
The control design is important in the development phase. A good control design demands a good mathematic model of the system, see any basic textbook on control design, e.g. [5].
4.1 Linear Quadratic Control
A Linear Quadratic (LQ) control was developed by the space industries in the United States and of the Soviet Union in the 1960s to solve space related control problems. The Linear Quadratic Gaussian (LQG) control design method is optimized to reject white noise disturbance (Gaussian) at plant input and for measurements. It is a design method that simultaneously can take into consideration not only one plant input and output, but several, see [3], [4].
In order to make such a design it is of great importance to have a really good linear mathematical model of the plant at the operating point. For nonlinear plants it is therefore important to linearise the model. These details have not been in focus in this project. In cases where it is not possible to direct measure the state variables for the feedback they must be estimated in some way. Here the Kalman filter is the most well known, see brief information in next section.
4.2 The Pendulum System
The theory about the pendulum system is a well-known education example in control applications. There are many different types of a pendulum system studied: inverted pendulum, double arm inverted pendulum, as a traverse crane etc, see e.g. [3], [4] and [5]. For most applications, the control principle does not emphasize on how much the cart is moving but that the pendulum arms should be as still as possible in a down hanging position, the angle θ = 0 [rad] for the crane, and in upright position, the angle θ
= π [rad] for the inverted pendulum.
4.3 The Mathematic Model of the Pendulum System
The mathematical model is taken from UMICH (University of Michigan) Control Tutorials for MATLAB and Simulink, see ref [2]. The state variable for the model are cart position, cart velocity, the pendulum angle and its angular velocity, see figure 7.
Figure 7 Model of the pendulum system (Source electronic, see ref [2]).
Summing the forces of the cart in the horizontal direction, the result will be the following equation of motion:
(2)
For details, see ref [2].
13
4.4 The Model used in Simulink
Figure 8 display how the model is built in Simulink.
Figure 8 Simulink model of the pendulum system in (2), see the UMICH homepage for details.
4.5 Kalman Filter
The Kalman filter, published by R.E. Kalman 1960, is a recursive solution to the discrete-time linear filtering problem. It is the optimal linear estimator. Peter S Maybeck see ref [9] writes there are many ways of defining optimal:
With respect to virtually any criterion that makes sense.
Incorporates all information than can be provided to it.
Processes all available measurements, regardless of their precision and estimate the current value of the variables of interest.
5 Result
All different communication parts, see figure 6, have been tested and work. The tests have been done in small steps so it should be possible to identify if there are any problems.
The communication between Simulink and the microcontroller unit does not work. It was not enough with time left for this part of the project.
5.1 Result from the Communication Part
The communication between the PC, the general purpose box with a microcontroller unit, the DC-motor and the sensors have been tested. The part between the microcontroller unit and the pendulum hardware works both reading the cart sensor and the pendulum arms sensor. Driving the cart from the microcontroller also works without problem. The communication part between the microcontroller unit and the PC both tested with the HyperTerminal and MATLAB, have some problems when more than one task is running. The experience from the test phase is that there is some delay problem in the system. Handling both the communication part and reading the encoders in the microcontroller unit takes too long time.
5.1.1 Reading the Sensor Code
To check the code written for Task2, reading the sensors, the result from the register was sent out to the LED’s, see appendix A for code and appendix C for flowchart. This works without problems for both the pendulum arm and cart. The value in the register is shown on the LED’s. When the movement of the pendulum arms or the cart stops the LED’s also stop changing values.
5.1.2 The Connection between Microcontroller Unit and HyperTerminal
Check of the connection between the microcontroller unit and the Microsoft inbuilt HyperTerminal in the PC is made with a C-program in the microcontroller unit, see appendix A Task3. An IF loop was written for the test. When the HyperTerminal sent an ‘a’ to the microcontroller unit, the microcontroller unit sends back an “A”. This part also works without problem.
5.1.3 Reading the Register and Write the Result in MATLAB
This test reads the value from the registers in the microcontroller unit to be displayed in MATLAB. See appendix A Task3.
First there were problems, the same value was written to MATLAB too often. A
“sniffing” cable, connected to the cable from the microcontroller unit and the RS232 connection on the PC, was used to detect the traffic on the serial communication.
15
It looks strange, after some hours of fault detecting, with help from the sniffing cable the reason was found. The problem was in the C-code. The old parameter value was initiated inside the while loop, which was wrong. After changing the code it worked when initiating in the main loop. This was the first time the delay problem appeared. If everything works, the register value should be written on the HyperTerminal like 4, 5, 6, 7, 6, 5, 4 and so on. However, this was written as 4, 5, 7, 3, 2, 1. Probably the reason for the problem is in AVRX where it needs to be a delay before switching tasks. The minimum of this delay time is 1 [ms]. The conclusion to this wasn’t solved.
5.1.4 Read Encoder and Control the Cart Movement
This was the test to check the possibility to control the microcontroller unit from MATLAB. When coming to this point it was no time left of the project.
5.1.5 Summary of result
The aim with the degree project to solve the communication part of the system is working. The encoder information interpretation and how to translate the value in the register to measurable value to use in MATLAB is solved. How to handle the value in MATLAB and to send it back to the pendulum system correctly is not solved. The control of the pendulum system is also left to another student. There is not a working system done in Simulink.
6 Conclusions
The conclusion from this project is that a general interface for computer control of arbitrary processes from a PC is working.
6.1 Recommendation for Possible Further Work
Investigate software for programming in real time. Maybe AVRX is not the optimal software for the pendulum system.
A strategy for the pendulum system could be to use LQG-control with a Kalmanfilter to solve the control problems with the system.
The communication causes some delay problems. A solution in future project could be to use more than one microcontroller unit. Then let one of them work as the communication master ant the other to take care of reading the encoders, drive the DC- motor and drive a LCD (Liquid Crystal Display) with information about for example the temperature, angle position etc.
7 Personal Reflection
Finally the degree project ended up happily. The main goal to get the communication between the general hardware, sensors, microcontroller unit and the software MATLAB in a PC is solved. Unfortunately I started with the simulating part of the LQG-control of the pendulum system. With result in my hand; the communication part should have been solved first. Ten weeks is not so long time.
The good thing from this project is the experience of identification of a system. In the real world, simulation works fine but when the hardware is connected then a lot of problems appear. I really had learned a lot about hardware and communication but not so much about controlling as I thought from the beginning. I had read about the Kalman filter, different Linear Quadratic regulators and almost the whole help about serial communication and Simulink in MATLAB. My practice in the English language has increased.
17
References
1. Schmithbaur, Bengt (1999) Modellbaserade reglersystem. Lund:
Studentlitteratur
2. University of Michigan (1997). Control Turtorials for Matlab. Example:
Modelling an Inverted pendulum. [Electronic] Michigan: Univeristy of Michigan. Accessible: www.engin.umich.edu/group/ctm/examples/pend/invpen.html
[2005-05-05]
3. Gopal, M (1993) Modern control system theory, second edition. New Delhi, India: Wiley Eastern Limited
4. Ogata, Katsuhiko (1997) Modern Control engineering. Upper Saddle River:
Prentice-Hall, Inc
5. Lennartson, Bengt (2002) Reglerteknikens grunder, fjärde upplagan. Lund:
Studentlitteratur
6. Jensen, Stig mfl. (2000) Data Kommunikation. Stockholm: Liber 7. Morton, John (2002) AVR An Introductory Course. Oxford: Newnes
8. Norström, Christer et al. 2000-08-18. Robusta realtidssystem Kompendium Version: rts-bok00-11
9. Maybeck, Peter S. (1979) Stochastic models, estimation and control. New York, San Francisco, London: Academic Press
Unknown references and manuals:
10. Atmel User Guide AVR® STK500 ,manual belong to the starter kit borrowed from HTU.
11. Feedback documentation. A manual for the old pendulum system from the company FEEDBACK stored in a binder at HTU.
12. Course RMB010 given at HTU spring 2004: Realtidsprogrammering 5 poäng.
Appendix A Program Code for the Micro Control Unit
A Program Code for the microcontrol unit
/*Program till kommunikationen mellan mikrodator och motor och Pc 2005-05-11 Måste kolla om varianten av myprocessor styr SIG_UART eftersom det heter USART och inte UART eller om det var så att det är AVRX egen definition DETTA SÅG UT ATT FUNGERAR ÄVEN FÖR ATMEGA16!!
2005-05-18 I task 2 lägger till om givarna alltså avläsning av dessa.
Det fung. till slut. Vet ej om värdet i reg är rätt men det är en annan sak.... dvs skjut på problemen
2005-05-19 I Task 3 lägger jag kommunikationen mot hyperterminalen som får fungera som Matlab, jag vill att när skickar ett kommando till mikrodatorn så ska md skicka tillbaka antingen reg för pendelgivaren eller motorgivaren. Använder USART för överföringen av informationen.
Fungerade!!!
2005-05-27 Fick hjälp med granskning av koden. Christer Selvefors, han hittade att jag init omotor på fel ställe vilket gjorde att samma värde kom väldigt många gånger. Fredrik Danielsson löste mitt fel med att jag inte fick in ett värde till att styra motor, jag läste bara in c och inte efter följande värde....illa...
Under test perioden:
Förklaringar till Portarna: Port B=LEDS, används till kontrollbit, utgång på lådan4
Port C=MOTOR, används till styrning av motor direktkopplad till utrustn.
Port A=LÄSA AV DIPPAR, används till farten till motorn, utgång5 på lådan
Port D=LÄSA AV GIV + RXD OCH TXD,används till avläsn. direktkopplad till utrustn.*/
// Inkluderingar, definitioner och annat allmänt
#include <C:/WinAVR/avr/include/avr/io.h>
#include <c:/avrx/avrx/avrx-io.h>
#include <c:/avrx/avrx/avrx-signal.h>
#include <c:/avrx/avrx/Avrx.h>
#include <stdlib.h>
#include "hardware.h"
AVRX_MUTEX(ReadReady); // AvrX Semaphore låser läsafunktionen RXC
AVRX_MUTEX(WriteReady); // AvrX Semaphore låser skrivfunktionen TXC
AVRX_MUTEX(SerialTransmitMutex); // Tillåter delad användning av skriva funktionen
AVRX_GCC_TASK(task1,70,3); // Task1,2,3 deklareras med stackstorlek 70 bytes och prio 3 AVRX_GCC_TASK(task2,70,3);
AVRX_GCC_TASK(task3,70,3);
Appendix A:1
TimerControlBlock Timer1,Timer2,Timer3; // Timers som används just nu
// Globala variabler
unsigned char RxByte; // Receive buffer.
int i,temp=0; //variabl. för allt möjl.
int stilla=128,styra=0,varde=0; // variabler för
styra,varde,stilla till motorn
int motorgivare=0,pendelgivare=0; // variabler för att ha koll på ursprungsläget int motor=0,motorA=0,omotor=0,pendel=0,pendelA=0,opendel=0;
// Variabler för avläsning av givarna AVRX_SIGINT(SIG_OVERFLOW0) // Avbrottsrutinen för
timer0, ska alltid vara med.
{
IntProlog(); // Byter till "kernel stack/context"
TCNT0 = TCNT0_INIT; // Nollställer "timer owerflow" räknaren AvrXTimerHandler(); // Anropar Timer kö
manager
Epilog(); // Återvänder till tasken
}
AVRX_SIGINT(SIG_UART_DATA) // UART0 Transmit Buffer Empty ISR ger en signal när UDR är tom
{
cbi(UCSRB, UDRIE);
IntProlog(); // Byter till "kernel stack/context"
AvrXSetSemaphore(&WriteReady); // Signalerar att redo för mera.
Epilog(); // Återvänder till RTOS
}
AVRX_SIGINT(SIG_UART_RECV) // UART0 mottager UDR {
cbi(UCSRB, RXCIE);
IntProlog(); // Byter till "kernel stack/context"
RxByte = UDR; // Läser in informationen från UDR
AvrXSetSemaphore(&ReadReady); // Signalerar redo sbi(UCSRB, RXCIE);
Epilog(); // Återvänder till RTOS
}
void init_USART(void) // Initierar uarten
Appendix A Program Code for the Micro Control Unit
UCSRB = 0xD8; // Sätter TXCIE och RXCIE interrupt enable och RXEN,TXEN enable 0b11011000
}
void write_USART(unsigned char data) // Skriver till UDR {
AvrXWaitSemaphore(&SerialTransmitMutex);
// väntar att semaforen ska vara ledig
if ((UCSRB&0x20)==0) // Tittar om UDRE biten i USR registet är noll, alltså mottaglig för påfyllning
{
sbi(UCSRB, UDRIE);
AvrXWaitSemaphore(&WriteReady);
// Väntar på besked att UDR är tömd dvs redo att fyllas igen
}
UDR = data; // Lägger data i UDR
AvrXSetSemaphore(&SerialTransmitMutex);
// Sätter startvärde på semaforen ledig
}
unsigned char read_USART(void) // Läser från UDRn {
AvrXWaitSemaphore(&ReadReady); // Väntar på att mottagar interrupt ska signalera kör...
return(RxByte); // Returnerar det som
finns i RxByte }
NAKEDFUNC(task1) // Läser in fart från
dippar värde ut till motorn
{
while(1) // Körs i evigheter
{
// Testar att köra motorn fram och tillbaka, gjort om det från asm kod
varde = PINA; // Läser in värdet på PortA, ska styra farten styra = stilla + varde; // Ökar 128-värde för att
gå framåt
PORTC = styra; // Ut till motorn
AvrXDelay(&Timer1,500); // Kort tidsfördröjning 0,5s
styra = stilla - varde; // Minskar 128-värde för att gå tillbaka
PORTC = styra; // Ut till motorn
AvrXDelay(&Timer1,500); // Kort tidsfördröjning 0,5s
} }
Appendix A:3
NAKEDFUNC(task2) // Läser in givare motorn och pendel
{ // Reg motor; läser in pinvärde
// Reg omotor; innehåller det föregående inlästa värdet // Reg motorA; används som
räkne, matlab hämtar givar värde från denna
while(1) // Körs i evigheter
{
motor = PIND & 0x30; // Läser in värdet på PortD till reg motor och maskar bit 4(A) och 5(B) // MOTORGIVAREN Kollar när A är ett, om A var noll värdet innan då adderas eller subtraheras reg beroende på B
if(motor == 0x00) // Om kanal A och B är 00 {
omotor = motor; // Värde läggs som minne i register omotor
}
else if(motor == 0x10) // Om kanal A och A är 01 {
if(omotor == 0x00) // Om det gamla värdet var 00 {
++motorA; // Öka motor A register }
omotor = motor;
}
else if(motor == 0x20) // Annars är A och B 10 {
omotor = motor;
}
else if(motor == 0x30) // Om kanal A och B är 11 {
if(omotor == 0x20) // Om det gamla värdet var 10
{
--motorA; // minska motor A
register
}
omotor = motor;
}
//PENDELGIVAREN Kollar när A är ett, om A var noll värdet innan då adderas eller subtraheras reg beroende på B
// Reg pendel; läser in pinvärde // Reg opendel; innehåller det föregående inlästa värdet // Reg pendelA; används som räkne, matlab hämtar givar värde
Appendix A Program Code for the Micro Control Unit
{
opendel = pendel;
}
else if(pendel == 0x40) // Om kanal A och B är 01 {
if(opendel == 0x00) // Om det gamla värdet var 00
{
++pendelA; // Öka motor A register }
opendel = pendel;
}
else if(pendel == 0x80) // Annars A och B är 10 {
opendel = pendel;
}
else if(pendel == 0xC0) // Om kanal A och B är 11 {
if(opendel == 0x80) // Om det gamla värdet var 10 {
--pendelA; // minska register
}
opendel = pendel;
}
//PORTB=motorA;
AvrXDelay(&Timer2,1); // Kort tidsfördröj. 1ms }
}
NAKEDFUNC(task3) // Har koll på om en
instruktion kommer från hyperterminalen, utför rätt åtgärd
{
//Variant1 om den inte används så kommentera bort den
while(1) // Körs i evigheter
{
char buf[10]; // Initierar en buffert för att läsa in från USART
int ii = 0; // Variabel
while((buf[ii]=read_USART())=='\n') // Loopar tills sluttecknet kommit = allt överskickat {
if(ii>=sizeof(buf)) {
ii=0;
} }
//char info = read_USART(); // läser in
if(buf[0] == 'a') // Om ett kommando kommer från hyper utför order
{
write_USART(pendelA+48);
write_USART(10); // lf
}
Appendix A:5
else if(buf[0] == 'b') // Om ett kommando kommer från hyper utför order {
write_USART(motorA+48);
write_USART(10); // lf
}
else if(buf[0] == 'c') // Ska läsa in värde från matlab, ut till motor {
varde = atoi(buf); // Läser värde från matlab
PORTB = varde;
}
AvrXDelay(&Timer3,1); // Kort tidsfördröj. 1ms }
//Variant 2 om den inte används så kommentera bort den while(1)
{
char buf[10]; // Initierar en buffert för att läsa in från USART
int ii = 0; // Variabel
while((buf[ii]=read_USART())=='\n') // Loopar tills sluttecknet kommit, allt överskickat {
if(ii>=sizeof(buf)) {
ii=0;
} }
switch(buf[0]) {
case 'a': // Skicka värdet av
pendelgivaren till matlab {
write_USART(pendelA+48); // Lagt
på 48 för att få ut ett ngl läsbart värde på hyperterm .
write_USART(10); // lf
}break;
case 'b': // Skicka
värdet av motorgiva
Appendix A Program Code for the Micro Control Unit
case 'c': // Ut till
motorn {
varde = atoi(buf);
//varde = atoi(buf[1]); // Måste nog göra en loop här för att få ut rätt värde PORTB = varde; // Hade för
att kolla om det kom rätt värde styra = stilla + varde; // Ökar
128-värde för att gå framåt
PORTC = styra; // Ut
till motorn }break;
case 'd': // Ut
till motorn {
varde = atoi(buf);
PORTB = varde; // Hade
för att kolla om det kom rätt värde styra = stilla - varde; //
Minskar 128-värde för att gå bakåt
PORTC = styra; // Ut
till motorn }break;
styra = stilla; // motor stilla
PORTC = styra; // Ut till motorn }break;
}
AvrXDelay(&Timer3,1); // Kort
tidsfördröjning 1ms för att kunna skifta mellan tasken
} }
int main(void) // Huvudprogrammet
{
Appendix A:7
AvrXSetKernelStack(0); // Initizerar stacken till aktuellt SPL/SPH outp((1<<SE),MCUCR); // Tillåter "sov" instr.
outp(TCNT0_INIT,TCNT0); // Nollställer "timer owerflow" räknaren outp(TMC8_CK256,TCCR0); // Timer0 för 256 klocktick outp((1<<TOIE0),TIMSK); // Tillåter Timer0 owerflow
avbrott
outp(0,DDRA); // PortA inport, värde som ska reglera farten, dipparna
outp(0,PORTA); // Nollar porten
outp(255,DDRB); // PortB används under testning för att se om det sker något, outp(0,PORTB); // Visas på LED's nollar porten outp(255,DDRC); // PortC utport, kopplad till hw
ger spänning
PORTC = stilla; // Motorn ska stå stilla från början outp(0x02,DDRD); // PortD bit:PEND in 7 kanB, 6 PendA,
MOT in 5 kanB, 4 kanA, 1 TXD ut, 0 RXD in
outp(0,PORTD); // Nollar porten init_USART(); // Initierar uarten
motorgivare = PIND & 0x30; // Läser in ett initvärde var vagnen står från början,görs 1:a gången
pendelgivare = PIND & 0xC0; // Läser in ett initvärde var pendeln står från början,görs 1:a gången
omotor = motorgivare; // Initierar det värde som fanns vid start och lägger i gamla motor
opendel = pendelgivare; // Initierar det värde som fanns vid start och lägger i gamla pendel
AvrXRunTask(TCB(task1)); // Task1 anropas AvrXRunTask(TCB(task2)); // Task2 anropas AvrXRunTask(TCB(task3)); // Task3 anropas
Epilog(); // Startar upp tasken och lämnar huvudprogrammet
}
Appendix B MATLAB code
B MATLAB code
This is an example of MATLAB code used for testing the system.
s2 = serial('COM2', 'BaudRate', 19200);
fopen(s2);
fprintf(s2,'a') % utdata till "motor"
mgiv = fscanf(s2); % indata från "encoderar"
fprintf(s2,'b');
pgiv = fread(s2);
fclose(s2);
Appendix B:1
C Flow Chart Task2
Read Pin 4,5 (motor sensor)
Read Pin 6,7 (pend. sensor)
00 Old value = value
Old value = value
10 01
11
00
10
Increase reg
Decrease reg Old value = value
Old value = value
Old value = value
Old value = value
Old value = value
Old value = value
Increase reg
Decrease reg 01
11 00
00
10
10
Old value = value
Old value = value No
Yes
01 BA
Appendix D User Guide about the Programming Environment
D User Guide about the Programming Environment
This a simcule user guide from the writer to start up quickly using the software AVRX.
The following software is used:
Pn (Programmer Notepad) found under C:Program/AVR
Cmd (Command window), opened from Start – drive write cmd <enter>
AVR studio 4.0 if installed on the PC, opened from Start – All program This files needs to be updated for the project:
Hardware.h - the correct data for the used microcontrol unit is written here
Makefile – information to the GCC comcuiler, imcuortant that the correct filename is specified here
M16.def – information about the microcontrol unit like port configuration etc, fetch this file either from the comcuany at www.Atmel.com or www.ELFA.se Here is an explanation what too do:
Pn – Here is the code written, it is imcuortant that the file is saved as the file type .c Cmd – Here is the comcuilation of the code done. First go to the working directory use the commands: cd - change directory, ls – list directory
AVR – There is two or more way to program the microcontrol unit. If using the ST500 starter kit. If not using the starter kit check another alternative.
Go to File – open file in AVR, a dialog appears, write *.cof in File name then press the open button. Click on the file that appeared, press open button again.
The object file is loaded
Go to Tools – STK500/AVRISP/JTAG ICE
Choose the correct DEVICE, Mark Use Current Simulator/Emulator FLASH Memory, the press the button Program
If it does not work, see fault message for reason
Appendix D:1
PROJEKTARBETE
2005-03-26
Hårdvarugränssnitt för
datorreglering av inverterad pendel
Ulla Carlsson Di02 ,2005-06-15 utgåva 2
PROJEKTARBETE
Hårdvarugränssnitt för datorreglering av inverterad pendel Ulla Carlsson Di02
Sammanfattning
Den hårdvara som idag tillhör pendelsystemet har identifierats. En ny hårdvara som ska vara mer generell har byggts. Från den nya hårdvaran är det möjligt att ta 5, 12 eller 24 [V] enligt önskemål. Hårdvaran har testats tillsammans med skolans utvecklingsmaterial STK 500 med en mikroprocessor 8515. En enkel kod har används för att testa så att givarna kan läsas av. Detta projekt har avslutats i examensarbetet där det även har testats så att vagnen kan köras fram och tillbaka.
Utgivare: Högskolan Trollhättan/Uddevalla, Institutionen för teknik, matematik och datavetenskap, Box 957, 461 29 Trollhättan
Tel: 0520-47 50 00 Fax: 0520-47 50 99 Web: www.htu.se Examinator: Doktor Anna-Karin Christiansson
Handledare: Anna-Karin Christiansson
Nivå: Projektarbete nivå C Poäng: 5
Datum: 2005-01-19, utgåva 2 2005-06-15
Nyckelord: Hårdvara, spänningsförsörjning, intelligenta delen, ytterhölje, givare, motor, pendel
i
Innehållsförteckning
Sammanfattning...i 1 Inledning ...1 1.1 Bakgrund...1 1.2 Syfte och mål...1 1.3 Mjukvara...1 2 Förutsättningar ...1 2.1 Detaljbeskrivning...1 2.2 Avgränsningar ...2 3 Identifikation av den befintliga lådan och kringutrustning...2 3.1 Lådans ytterhölje ...2 3.2 Innehåll i den befintliga lådan...4 3.3 Motorn till pendeln ...4 3.4 Givarna till motor och pendel...5 4 Nya lådans innehåll...6 4.1 Spänningsförsörjning...6 4.2 Intelligenta delen ...15 4.3 Ytterhölje...15 4.4 Lådans utsida...16 5 Mätningar...16 5.1 Spänningsdelen ...17 5.2 Drivkretsdelen...17 5.3 Intelligenta delen ...17 6 Resultat ...17 7 Slutsatser...17 7.1 Rekommendationer till fortsatt arbete ...17 Källförteckning...18
Bilagor
A Kod för avläsning av givare till pendelarm. (3 sid) B Apparatintag (3 sidor)
C Transformator (3 sidor) D Likriktarbrygga (3 sidor)
E Elektrolytkondensator (3 sidor) F Switchregulator_L4970A (22 sidor) G Drivkrets (12 sidor)
H Atmel Atmega16 (20 sidor)
Figurer
Figur 1 Skiss över innehållet i befintlig låda... 4 Figur 2 Principen för givare HEDS-9100 (Källa: elektronisk se ref. [4]) ... 5 Figur 3 De olika ingående delarna av lådan ... 6 Figur 4 Transformatorns färgmärkning på ledare (Källa ELFA datablad)... 7 Figur 5 Schema över spänningsstabilisatorn med komponenter (Källa: se ELFA
datablad bilaga F figur 35) ... 10 Figur 6 Schematillägg för att få ut fast 24 [V] ... 10 Figur 7 Kopplingsschema motordrivkrets ... 12 Figur 8 Kopplingsschema PWM modulator... 12 Figur 9 Princip hur PWM modulering fungerar. ... 13 Figur 10 Mönster på givarna, tid längs X-axel och ett eller noll längs Y-axel. ... 15 Figur 11 Stiftens innehåll i uttaget som kommer från pendelsystemets givare... 16 Bilder
Bild 1 Framsida på befintlig låda. ... 2 Bild 2 Baksida på befintlig låda. ... 3 Bild 3 Likriktare med ledare monterade från transformator och vidare till
elektrolytkondensator. ... 8 Bild 4 Kretskortet med den switchade spänningsstabilisatorn. ... 9 Bild 5 Motordrivkrets. ... 11 Bild 6 Kretskort med PWM modulering. ... 13
iii