ee319k laboratory manual - trillworks...jonathan w. valvano ee319k spring 2010 lab manual page 1...

69
Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 1 [email protected] 3/9/2010 EE319K Laboratory Manual Univ of Texas at Austin, Valvano, Yerraballi, Erez Do not print the entire document, we will be making small changes. Spring 2010 (3/9/10 version) Table of Contents LAB 1. A DIGITAL LOCK ...................................................................................................................................................... 5 LAB 2. SWITCH AND LED INTERFACING........................................................................................................................ 7 LAB 3. MINIMALLY INTRUSIVE DEBUGGING METHODS ....................................................................................... 15 LAB 4. TRAFFIC LIGHT CONTROLLER ......................................................................................................................... 19 LAB 5. LCD DEVICE DRIVER ............................................................................................................................................ 25 LAB 6. REAL-TIME POSITION MEASUREMENT SYSTEM ........................................................................................ 31 LAB 7. DISTRIBUTED DATA ACQUISITION SYSTEM................................................................................................. 39 LAB 8. DIGITAL PIANO USING A DIGITAL TO ANALOG CONVERTER................................................................ 47 LAB 9. TEXAS ROBOTS 1.84 ............................................................................................................................................... 55 HOW TO DEVELOP C PROGRAMS METROWERKS/TECH ARTS 9S12DP512 BOARD ....................................... 65 A) TO OPEN AN EXISTING METROWERKS PROJECT ................................................................................................................. 65 B) HOW TO CONFIGURE CREATE A NEW METROWERKS PROJECT ............................................................................................ 65 C) HOW TO RUN METROWERKS C CODE ON THE REAL 9S12DP512 BOARD ........................................................................... 68 This lab manual is updated each semester. If you find a mistake, or if you find a section vague or confusing, please email me at [email protected]. If you enjoy EE319K, you might also enjoy EE345L. Furthermore, if you are good at EE319K, you might consider specializing in embedded systems. 9S12DP512 I/O Pins Chip TechArts TExaS V1.36 Simulation PAD15-PAD8 H2 Digital input PAD7-PAD0 H1 Analog input or Digital input PA7-PA0 H2 Digital I/O, no external data bus PB7-PB0 H2 Digital I/O, no external data bus PE7-PE0 H1/H2 no PE5,PE6 Digital I/O, no IRQ, no XIRQ, no external data bus PH7-PH0 H1 Digital I/O, Key wakeup PJ7-PJ6 H2 Digital I/O, Key wakeup, no I2C, no CAN PJ1-PJ0 H2 Digital I/O, Key wakeup PM7-PM0 H2 Digital I/O, no CAN, no SPI PP7-PP0 H1 Digital I/O, Key wakeup, no SPI, no PWM PS7-PS0 H1 Digital I/O, SCI0 or SCI1 (not both), no SPI PT7-PT0 H1 Digital I/O, input capture, output compare Please return the serial cable and LCD that you borrow from the 2 nd floor lab when done with Lab 7. If you do not return either of these two items we will drop your overall grade in EE319K one letter grade.

Upload: others

Post on 16-Oct-2020

2 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: EE319K Laboratory Manual - Trillworks...Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 1 valvano@mail.utexas.edu 3/9/2010 EE319K Laboratory Manual Univ of Texas at Austin,

Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 1

[email protected] 3/9/2010

EE319K Laboratory Manual Univ of Texas at Austin, Valvano, Yerraballi, Erez

Do not print the entire document, we will be making small changes. Spring 2010 (3/9/10 version)

Table of Contents LAB 1. A DIGITAL LOCK ......................................................................................................................................................5

LAB 2. SWITCH AND LED INTERFACING........................................................................................................................7

LAB 3. MINIMALLY INTRUSIVE DEBUGGING METHODS .......................................................................................15

LAB 4. TRAFFIC LIGHT CONTROLLER.........................................................................................................................19

LAB 5. LCD DEVICE DRIVER ............................................................................................................................................25

LAB 6. REAL-TIME POSITION MEASUREMENT SYSTEM ........................................................................................31

LAB 7. DISTRIBUTED DATA ACQUISITION SYSTEM.................................................................................................39

LAB 8. DIGITAL PIANO USING A DIGITAL TO ANALOG CONVERTER................................................................47

LAB 9. TEXAS ROBOTS 1.84 ...............................................................................................................................................55

HOW TO DEVELOP C PROGRAMS METROWERKS/TECH ARTS 9S12DP512 BOARD .......................................65 A) TO OPEN AN EXISTING METROWERKS PROJECT .................................................................................................................65 B) HOW TO CONFIGURE CREATE A NEW METROWERKS PROJECT............................................................................................65 C) HOW TO RUN METROWERKS C CODE ON THE REAL 9S12DP512 BOARD ...........................................................................68

This lab manual is updated each semester. If you find a mistake, or if you find a section vague or confusing, please email me at [email protected]. If you enjoy EE319K, you might also enjoy EE345L. Furthermore, if you are good at EE319K, you might consider specializing in embedded systems. 9S12DP512 I/O Pins Chip TechArts TExaS V1.36 Simulation PAD15-PAD8 H2 Digital input PAD7-PAD0 H1 Analog input or Digital input PA7-PA0 H2 Digital I/O, no external data bus PB7-PB0 H2 Digital I/O, no external data bus PE7-PE0 H1/H2 no PE5,PE6 Digital I/O, no IRQ, no XIRQ, no external data bus PH7-PH0 H1 Digital I/O, Key wakeup PJ7-PJ6 H2 Digital I/O, Key wakeup, no I2C, no CAN PJ1-PJ0 H2 Digital I/O, Key wakeup PM7-PM0 H2 Digital I/O, no CAN, no SPI PP7-PP0 H1 Digital I/O, Key wakeup, no SPI, no PWM PS7-PS0 H1 Digital I/O, SCI0 or SCI1 (not both), no SPI PT7-PT0 H1 Digital I/O, input capture, output compare Please return the serial cable and LCD that you borrow from the 2nd floor lab when done with Lab 7. If you do not return either of these two items we will drop your overall grade in EE319K one letter grade.

Page 2: EE319K Laboratory Manual - Trillworks...Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 1 valvano@mail.utexas.edu 3/9/2010 EE319K Laboratory Manual Univ of Texas at Austin,

Page 2 Introduction to Embedded Systems: Interfacing to the Freescale 9S12

03/09/10

Laboratory grading policies: This is a programming class. Therefore, the quality of the software you write will significantly affect your grade. In addition to writing software, each lab has specific activities that must be documented and turned in with the lab. These deliverables will be screen shots, circuit diagrams, measurements or data analyses. When you get the program finished, make a printout of your assembly listing, all deliverables, and staple a grading sheet to the front, and then demonstrate it to a TA. The TA will record the performance and demonstration grades on the grading sheet. Labs are due during your scheduled lab period. A detailed schedule follows. Late assignments incur a penalty of 10% of the maximum score per day for the first three days and will not be accepted afterwards. Exceptionally "good" programs may be given extra credit. If you do extra functions in your program, point out and demonstrate the extra functions to the TA when you demonstrate your program. Partial credit, not to exceed a maximum of 75% of full credit, may be awarded to a program that does not meet all specifications. Often it is better to demonstrate an incomplete program, rather than incur late penalties while fixing all its bugs. There are five components to the lab grade: 1. Deliverables 20% (graded later): 2. Performance 30% (graded by the TA at the time of checkout): How well does it work? Does it crash? Does it handle correctly all situations as specified? How clean is the user interface? Possible 5% Bonus, does it do more than specified? 3. Demonstration 30% (graded by the TA at the time of checkout): Can you explain to the TA how your software works? Be prepared to explain the data flow through your system. Can you explain why you made certain software engineering tradeoffs? Both partners if applicable must be present during the demonstration. There is a lot of starter code in the book and installed with TExaS. It is natural and appropriate for you to look at these examples. However, during demonstration you are expected to understand both the algorithm used and the implementation details of ALL 9S12 software you are running at the time of checkout. In particular, the contents of these starter files will be examinable for the lab checkouts as well as for in-class written exams. Even if your program works, you may get very poor score on the entire lab (e.g., 0 to 50%) if you do not understand how it works. If your system runs on the simulator, but does not fully run on the real hardware, you may be assessed a 20% penalty on the entire lab. 4. Software quality 20% (graded later): Clearly describe the data and program structures in the software comments. Simple well-structured software with descriptive labels is much easier to understand than complex software with voluminous comments. Use either top-down or bottom up structure. Modular programming divides the problem into "natural divisions" with minimal coupling. The interfaces should be simple and natural. The software will be graded on the correctness of the program function, the comments, the interface to the user, the style, and the organization. The effort spent to write high quality software will be rewarded both during debugging and when it is time to add features in the future. 5. Late penalties (-10% per day, see next page). There will be no late submissions for Lab 9. Cut and trim a label to place between the 9S12 and the protoboard.

9S12DP512

25

50

26

1

PAD11

PA3

PA0

PA6PA5PA4

PA1

PB7PB6PB5PB4PB3

PB0

PB2

PA7

PA2

PB1

PAD10PAD9PAD8

PE2PE4

PE1PE3

PJ1

PAD14

PK4

PK1PK0PJ0PJ7PJ6PM7PM6PM5

PK3

PK5PK7PE7Gnd +5

PK2

PAD15

PM3PM4

PAD13PAD12

PM2

PM0PM1

H29S12DP512

25

50

26

1

PAD3

PS1

PT5

PS5PS6PS7

PT6

PT4PT3PT2PT1PT0

PP5

PP7

PS4

PT7

PP6

PAD2PAD1PAD0

PP4PP3

PP1PP2

PP0

PAD6

PE0

PH0PH1PH2PH3PH4PH5PH6PH7

Reset*

PE1+5PS0GndGnd

PE7

PAD7

PE4PS2

PAD5PAD4

PS3

VRHVRL

H19S12DP512

25

50

26

1

AN03

TxD0

PT5

MOSISckSS*

PT6

PT4PT3PT2PT1PT0

PP5

PP7

MISO

PT7

PP6

AN02AN01AN00

PP4PP3

PP1PP2

PP0

AN06

XIRQ*

PH0PH1PH2PH3PH4PH5PH6PH7

Reset*

IRQ*+5RxD0GndGnd

PE7

AN07

EclkRxD1

AN05AN04

TxD1

VRHVRL

H19S12DP512

25

50

26

1

AN11

AD11

AD8

AD14AD13AD12

AD9

AD7AD6AD5AD4AD3

AD0

AD2

AD15

AD10

AD1

AN10AN09AN08

R/WEclk

IRQ*LSTRB*

PJ1

AN14

XA18

XA15XA14PJ0SCLSDAPM7PM6PM5

XA17

XA19ECS*

XCLKS*Gnd +5

XA16

AN15

PM3PM4

AN13AN12

PM2

RxCANTxCAN

H2DM912C32

20

40

21

1

CANL CANH

PE1

PT5PT4PT3PT2PT1PT0PM0PM1

PT7

PE0+5ResetGndVin

PT6

AN0

AN3

RXDTRGnd

AN2

AN4AN5AN6AN7PM5

PM2

PM4

TX

AN1

PM3

EE319K EE345L

Page 3: EE319K Laboratory Manual - Trillworks...Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 1 valvano@mail.utexas.edu 3/9/2010 EE319K Laboratory Manual Univ of Texas at Austin,

Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 3

[email protected] 3/9/2010

Comments and policies about EE319K from the Lab Introduction given the first week 1) EE319K is a "hands on" class and therefore, even though the labs are only 30% of the total grade, there is NO WAY to make it through this class without taking all the labs seriously. It is during the lab experience that you will really learn. 2) The class is rapidly changing so even if you repeat the class, or heard about from friends who took it even in the last semester, some things have changed. So, please read the lab manual and go to class. 3) The lab checkout times will take place during the lab slot to which you are registered. 4) This lab manual describes the task for each lab and provides and examples of questions you can be asked. The questions are meant to give you an idea of the topics, depth and scope of the questions. Your TA may ask similar but different questions. You may also be asked ANY question related to the material/previous labs and etc. 5) In addition the lab manual specifies a list of "deliverables". You will have to hand these deliverables to the TA at the beginning of the check-out. And they will be returned to you after grading. When you print the deliverables, there is no need to print them in color; it will not give you any bonus. You better try to print on both sides, even 2 pages per sheet if possible, to save paper. There is a lab grade component for the deliverables (see grading policy in the lab manual) and missing some of them will affect the grade. You will be able to pick-up you deliverables after graded. We will announce shortly the exact way to do so. 6) You need to have printed the deliverables before your time slot. If you begin to print after the checkout started, you will be considered as not ready, and it will impact the grade. 7) Starting with Lab 2, each student will be assigned a check-out time (by the TA). 8) You will need to come to lab ahead of your assigned time, log-in, connect the microcontroller if needed and download your code. This way you are ready to demonstrate at the beginning of your assigned checkout time. These are going to be VERY short slots and there is no way a TA can check you out if you will have to spend half of the time on setting-up or printing. 9) Student(s) not ready with everything set-up on the time assigned, won't be able to check-out during their slot, they will have to do a "late-check-out" and loose at least 10% (see late checkouts). 10) Partnerships are described in detail are in the syllabus. The TA will randomly select partners for Lab 4 to 8, and the partnerships will be rotated week to week. Note that we cannot guarantee that you will have a partner for each of the labs. Both partners must be present during the TA demonstration. If your partner does not show up for your assigned time, then one student may demonstrate, and the other student (the one not present) will receive a zero and not be allowed to make it up. If you and your partner do not get along, you are still both responsible for the lab. For late checkouts, both students in a partnership must be present. The TA may assign a different grade to each partner based on your performance during your checkout demonstration. You will be allowed to choose your own partner for the last lab (TRobots). 11) Grading : you will receive your lab grade trough the blackboard. The TA that checked you out will be upload it within a week after the check-out. There is no need to send emails and ask about it during that week. However, if you don't see your grade after that week, please send an email to the TA (if it is not the TA you usually check-out with, consider a cc to your TA as well). 12) We do NOT recommend you to print this whole lab manual now since it is being updated from time to time. Therefore if you decide to print, it will be best if you print only the part of the manual for the lab on which you are working. 13) Office hours : each Prof. and TA has office hours time. You can find the office hours of the professors on their websites. The office hours of the TAs will be posted soon. They will be posted on blackboard and a hard copy of the schedule will be on the wall in the 319lab. You can attend any office hours, even if it is not your professor/TA. 14) Late check-outs, in case you didn't make it to check-out during the slot you were assigned, you still can check it out later during office hours of ANY TA - no need to ask/register for that, just show up. If you show up at the end of a TA office hour, there may not be time to check you out. There is a penalty of 10% for each late day, see the table below. “/-10%” means that

Page 4: EE319K Laboratory Manual - Trillworks...Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 1 valvano@mail.utexas.edu 3/9/2010 EE319K Laboratory Manual Univ of Texas at Austin,

Page 4 Introduction to Embedded Systems: Interfacing to the Freescale 9S12

03/09/10

if you check out during your scheduled time, it is possible to get full credit, but checking out later that same day will still be considered as 1 day late. No check-outs will be allowed after Monday following the due dates. Students in the Thursday lab have an advantage of having their labs due later, but students in the Tuesday lab move more opportunities for late checkout. If you have special circumstances, please talk with your professor about it. If you have something that will not allow you to check-out and you know about it ahead of time, consider asking to check-out early (during office hours of ANY TA) - send an email to the TA you want to check-out early with, explain why, cc your original TA.

Date of your lab Tuesday Wednesday Thursday Friday Monday Tuesday 0/-10% -10% -20% -30% -40% Wednesday 0/-10% -10% -20% -30% Thursday 0/-10% -10% -30%

15) Lab lecture: we will soon post the times of lab lectures. There will be 3 (TBD) such lectures for each lab starting with lab2. All the lectures for lab2 for example will cover the same things. So you will have the flexibility to attend the lecture most convenient for your schedule. The lecture(s) will take place couple of days (up to a week) before your check-out time. During the lecture a TA will answer questions you might have, present a possible solution (how it works at the end - not the code). The TA may give some hints and will answer your questions. Therefore we strongly recommend you read the lab manual before coming to l the lecture so you'll have some time to think of the lab and see if you have any questions. 16) Communication : Sometimes you need to ask a specific person a specific questions. For example, you might ask your TA about a missing grade, it would be nice to email Valvano about possible typos in the book, or you might want to ask your professor about a special circumstance. In these cases, contact the specific person. Conversely, if you have a general question about the 9S12, the lab, or the lab equipment, please ask the question using a special email address [email protected] Using this email address will allow us to provide more clear, more consistent and faster answers. 17) The schedule of the labs is available in the syllabus. From time to time (marked in the schedule) we will use the lab slot to provide a demonstration (of tools) or introduction. You will have to attend the whole hour (or as long as that session will take). Other times, when we will do check-outs you will have to attend your check-out slot only (still you have to be ahead of time to set everything up as explained). 18) As mentioned in the lab manual/syllabus, you will need a multi-meter for this class. In case you plan to buy one, no need to spend too much money, the cheap one will be good enough. 19) The tools you will for this class are installed in all the ECE computers, you can work in any of these. Note however, that only the 319 lab has the cables already connected to the serial port. It might also happen that machines in other rooms may not even have a serial port. 20) You can download the software tools we use for the class (Texas, Metrowerks, TRobots) from the web (the TExaS link is posted on blackboard), install it on you own machine. We know that these tools were successfully used on Vista, Mac* and Linux* (*-using virtual machines). However, we can not assure you will be able to run it on any OS/hardware. Therefore in case of nay problem, you'll have to work in the lab. Moreover, if you work on your assignment on other machine, it is your own responsibility to make sure you get correct behavior on lab machines, since this is where it will be examined. (i.e., it doesn't help that you swear it worked yesterday at home, if it doesn't work during the check-out at the lab). 21) Some modern machines (and most of the laptops) do not have a serial port. You still can work on these machines, but you'll need to arrange yourself (buy/borrow from a friend) a Serial-USB adapter.

Page 5: EE319K Laboratory Manual - Trillworks...Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 1 valvano@mail.utexas.edu 3/9/2010 EE319K Laboratory Manual Univ of Texas at Austin,

Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 5

[email protected] 3/9/2010

Lab 1. A Digital Lock Preparation Read Chapter 1 of the book Read Sections 2.1, 2.2, 2.3, 2.6 and 3.7 of the book Install and run TExaS, execute Help->GettingStarted, read up to but not including “Developing C software…” Download and run the first three lessons at

http://users.ece.utexas.edu/~valvano/Readme.htm Purpose The general purpose of this laboratory is to familiarize you with the software development steps using the TExaS simulator. Starting with Lab 2, we will use TExaS for both simulation and debugging on the real board, but for this lab, we will use just the simulator. You will learn how to perform digital input/output on parallel ports of the 9S12. Software skills you will learn include port initialization, logic operations, and unconditional branching. System Requirements

The specific device you will create is a digital lock with two binary switch inputs and one LED output. The LED output represents the lock, and the operator will toggle the switches in order to unlock the door. Let T be the Boolean variable representing the lock (0 means LED is off and door is locked, 1 means LED is on and door is unlocked). Let H and P be Boolean variables representing the state of the two switches (0 means the switch is not pressed, and 1 means the switch is pressed). The specific function you will implement is

H & P T = This means the LED will be on if and only if the P switch is pressed and the H switch is not pressed, as shown in Figure 1.1.

Figure 1.1. TExaS IO window showing the door is unlocked. Procedure

The basic approach to this lab will be to first develop and debug your system using the simulator. Part a) Use the TExaS simulator to create three files. Lab1.rtf will contain the assembly source code. Lab1.uc will contain the microcomputer configuration. Lab1.io will define the external connections, which should be the two switches and one LED as shown in Figure 1.1. In this class, we will use the 9S12DP512 microcomputer, which you can specify using the Mode->Processor command. You should connect switches to PP1 (means Port P bit 1) and to PH1 (means Port H bit 1). You should connect an LED to PT1 (means Port T bit 1). The switches should be labeled H and P, and the LED should be labeled T. When H switch is “off” or open position, the signal at PH1 will be 0V, which is a logic “0”. For this situation, your software will consider H to be false. When the H switch is “on” or closed position, the signal at PH1 will be +5V, which is a logic “1”. In this case, your software will consider H to be true. The P switch, which is connected to PP1, will operate in a similar fashion. When your software writes a “1” to PT1, the LED will turn on. Figure 1.1 shows the condition with the LED is on because P is pressed and H is not pressed. void main(void){ DDRH = 0x00; // make Port H an input, PH1 is H DDRP = 0x00; // make Port P an input, PP1 is P DDRT = 0xFF; // make Port T an output, PT1 is T while(1){ PTT = (~PTH)&PTP; // LED on iff PH1=0 and PP1=1 } } Program 1.1. This C program specifies the operations your assembly program should perform in Lab 1.

Page 6: EE319K Laboratory Manual - Trillworks...Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 1 valvano@mail.utexas.edu 3/9/2010 EE319K Laboratory Manual Univ of Texas at Austin,

Page 6 Introduction to Embedded Systems: Interfacing to the Freescale 9S12

03/09/10

Part b) You will write assembly code that inputs from PH1 and PP1, and outputs to PT1. Program 1.1 describes the software algorithm in C. Notice that this algorithm affects all bits in a port, although only one bit is used. In general, this will be unacceptable, and we will learn later how to write code that affects one bit at a time. You can copy and paste the address definitions for ports H, P, and T from the port12.rtf file. In particular, you will need to define DDRH DDRP DDRT PTH PTP and PTT. The structure of assembly programs in this class is shown as Program 1.2. The opening comments include: file name, overall objectives, hardware connections, specific functions, author name, TA, and date. The equ pseudo-op is used to define port addresses. Global variables are declared in RAM, and the main program is placed in EEPROM. The 16-bit contents at $FFFE and $FFFF define where the computer will begin execution after a power is turned on or after the reset button is pressed. This template, shown in Program 1.2, can be found in most example programs for the 9S12DP512. ;****************** Lab1.RTF *************** ; Program written by: Your Name ; Date Created: 7/29/2009 6:06:11 PM ; Last Modified: 7/29/2009 6:06:18 PM ; Section 1-2pm TA: Nachiket Kharalkar ; Lab number: 1 ; Brief description of the program ; The overall objective of this system is a digital lock ; Hardware connections ; PH1 is switch input H ; PP1 is switch input P ; PT1 is LED output T (on means unlocked) ; The specific operation of this system ; unlock if P is pressed and H is not pressed ;I/O port definitions on the 9S12DP512 PTH equ $0260 ; Port H I/O Register DDRH equ $0262 ; Port H Data Direction Register PTP equ $0258 ; Port P I/O Register DDRP equ $025A ; Port P Data Direction Register PTT equ $0240 ; Port T I/O Register DDRT equ $0242 ; Port T Data Direction Register org $0800 ; RAM ; Global variables (none required for this lab) org $4000 ; flash EEPROM main ;Software performed once at the beginning loop ;Software repeated over and over bra loop org $FFFE fdb main ;Starting address Program 1.2. Assembly language template. Demonstration

During the demonstration, you will be asked to run your program to verify proper operation. You should be able to single step your program and explain what your program is doing and why. You need to know how to set and clear breakpoints. You will be asked to look up the meaning of commands like Mode->FollowPC using the on-line help. Be prepared to make changes to Lab1.io, such as changing the names and colors of the switches and LEDs. Deliverables 1) Assembly listing of your final program 2) One screen shot of the UC and IO windows, showing PTT PTP and PTH in the lab1.uc window and showing the case with the LED on.

Page 7: EE319K Laboratory Manual - Trillworks...Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 1 valvano@mail.utexas.edu 3/9/2010 EE319K Laboratory Manual Univ of Texas at Austin,

Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 7

[email protected] 3/9/2010

Lab 2. Switch and LED interfacing Preparation Read Chapter 2 as a review of EE306 Read Chapter 3 Purpose The purpose of this lab is to learn how to interface a switch and an LED. You will perform explicit measurements on the circuits in order to verify they are operational and to improve your understanding of how they work. Software skills you will learn include masking, toggling, if-then, and looping. You will learn to use a free design tool called PCBArtist from Advanced Circuits for drawing electrical circuits. This tool will be used in EE319K, EE345L and EE345M. To download this tool, go to http://www.4pcb.com/ When installed, there will be a drawing application called PCB Artist, which we will use to draw electrical circuits. Open the starter file EE319K_DP512_Artist.sch using PCB Artist. We will also use PCB Artist to design PCB boards in EE345L. System Requirements The system has one input switch and one output LED. Figure 2.1 shows a switch interface that implements positive logic. This means the PT1 signal will be 0 (low, 0V) if the switch is not pressed, and the PT1 signal will be 1 (high, +5V) if the switch is pressed. Figure 2.1 also shows an LED interface that also implements positive logic. A positive logic LED interface means if the software outputs a 1 to PT0 (high, +5V) the LED will turn on, and if the software outputs a 0 to PT0 (low, 0V) the LED will be off. You will attach this switch and LED to your protoboard (the white piece with all the holes), and interface them to your 9S12. Overall functionality of this system is described in the following rules. Make PT0 an output and make PT1 an input. The system starts with the LED off (make PT0 =0). If the switch is pressed (PT1 is 1), then the LED will flash on and off at about 4 Hz (any value from 1 to 8 Hz is ok). If the switch is not pressed (PT1 is 2), then the LED should turn off.

Figure 2.1. Hardware circuit diagram. There are two ways to look up how long each instruction takes to execute. The first method uses the Freescale data sheet. For example, the following is a page from the CPU12 manual. Figures 2.2 and 2.3 show example pages from this manual, which can be found at http://users.ece.utexas.edu/~valvano/Datasheets/S12CPUV2.pdf

Page 8: EE319K Laboratory Manual - Trillworks...Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 1 valvano@mail.utexas.edu 3/9/2010 EE319K Laboratory Manual Univ of Texas at Austin,

Page 8 Introduction to Embedded Systems: Interfacing to the Freescale 9S12

03/09/10

Figure 2.2. Freescale manual page for the ldaa instruction.

To determine the execution time we first determine which addressing mode it is using, then count the letters in the Access Detail field. For example, ldaa #10 is immediate mode addressing and the access detail is P. Since there is one letter, it executes in one bus cycle. For example, ldaa $0240 is extended mode addressing and the access detail is rPO. Since there are three letters, it executes in three bus cycles. Most instructions have a simple predictable execution time like this example. However, the conditional branch instructions have a variable execution time depending on whether or not the branch is taken. There are two access detail descriptions PPP and P. This means it will take three bus cycles if the branch is taken and one bus cycle if the branch is not taken.

Figure 2.3. Freescale manual page for the bne instruction.

The other method to determine execution cycle is to enable cycle counts in the TExaS assembler. First, click on your source code file, then execute Assemble->Options… Within this dialog activate (make the check mark appear) for the “Show the # of cycles to execute each instruction” option, as shown in Figure 2.4.

Figure 2.4. TExaS dialog box for the Assemble->Options… command.

Page 9: EE319K Laboratory Manual - Trillworks...Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 1 valvano@mail.utexas.edu 3/9/2010 EE319K Laboratory Manual Univ of Texas at Austin,

Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 9

[email protected] 3/9/2010

The following is a portion of the listing file generated with these options. The data in red defines the number of cycles to execute each instruction. The numbers in blue are the running total (this running total does not account for branches). Notice also, the PPP/P code for the conditional branch. As mentioned previously, a branch instruction requires 3 cycles if the branch occurs and 1 cycle if the branch does not occur. $401E CDC350 [ 2]( 29){OP }Delay ldy #50000 $4021 1810 [12]( 31){Offffffff+}ll idiv ;12 cycle delay $4023 03 [ 1]( 43){O } dey $4024 26FB [ 3]( 44){PPP/P } bne ll $4026 3D [ 5]( 47){UfPPP } rts Procedure

The basic approach to this lab will be to first develop and debug your system using the simulator using positive logic mode for the switch and LED. During this phase of the project you design and debug your software in the simulator. After the software is debugged, you will build and test your hardware. During this second phase of this lab, you will run your system on the real 9S12. The final demonstration will be run stand-alone without connection to the PC. Part a) Write a subroutine that delays about 125 ms. Any delay from 60 to 500 ms is OK. To implement a delay, you could set a 16-bit register to a large number, and then count it down to zero. Because there are 1,000,000 E clock cycles in 125 ms, you will need to add some “do-nothing” operations inside the loop. For example, it takes 48 cycles to execute the idiv instruction four times. If the total time to execute the loop is 51 cycles (four idiv and one dbne Y), then executing the loop 19608 times will be about 125 ms. E.g., 19608(loops)*51(cycles/loop)*125(ns/cycle) equals about 125 ms (in RUN mode). The 9S12 executes 3 times faster in LOAD mode (24 MHz) than RUN mode (8 MHz). We do not care whether your program delays 125 ms in RUN mode or in LOAD mode, as long as you understand that there is a difference in execution speed.

Write a main program that implements the input/output system and test it on in simulation mode. Pseudo code is shown on the left and C code on the right, illustrating the basic steps for the system. main Initialize the stack pointer Set the direction register so PT1 is an input and PT0 is an output Set PT0 so the LED is off Enable interrupts for the hardware debugger, cli loop Delay about 125ms Read the switch and test if the switch is pressed If the switch is pressed, toggle PT0 If the switch is not pressed, clear PT0 Go to loop

DDRT &= ~0x02; // PT1 input DDRT |= 0x01; // PT0 output PTT &= ~0x01; // PT0 off asm cli while(1){ unsigned short i; delay(); if((PTT&0x02)==0){ PTT = PTT^0x01; // toggle } else{ PTT &= ~0x01; // clear PT0 } }

During the simulation phase of the project you can run with a small loop constant (change 19608 to 100) so the

simulation runs more quickly. During the real-board phase of this lab (later in Part d), use a loop constant large enough so you will be able to see the LED flash with your eyes (any value you can see flash with your eyes is ok). Part b) Engineers must be able to read datasheets during the design, implementation and debugging phases of their projects. During the design phase, datasheets allow us to evaluate alternatives, selecting devices that balance cost, package size, power, and performance. For example, we could have used other IC chips like the 7405, 74LS05, or 74HC05 to interface the LED to the 9S12. In particular, we chose the 7406 because it has a large output current (IOL = 40 mA), 6 drivers, and is very inexpensive (53¢). During the implementation phase, the datasheet helps us identify which pins are which. During the debugging phase, the datasheet specifies input/output parameters which we can test. Download the 7406, LED, and switch datasheets from the web http://users.ece.utexas.edu/~valvano/Datasheets/7406.pdf http://users.ece.utexas.edu/~valvano/Datasheets/LED_red.pdf http://users.ece.utexas.edu/~valvano/Datasheets/B3F-switch.pdf

Page 10: EE319K Laboratory Manual - Trillworks...Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 1 valvano@mail.utexas.edu 3/9/2010 EE319K Laboratory Manual Univ of Texas at Austin,

Page 10 Introduction to Embedded Systems: Interfacing to the Freescale 9S12

03/09/10

and find in the datasheet for the 7406 the two pictures as shown in Figure 2.5. Next, hold your actual 7406 chip and identify the locations of pins 1-14. Find in the datasheet the specification that says the output low voltage (VOL) will be 0.4V when the output low current (IOL) is 16 mA (this is close to the operating point we will be using for the LED interface).

Figure 2.5. Connection diagram and physical package diagram for the 7406. Similarly, hold an LED and identify which pin is the anode and which is the cathode. Find on the switch datasheet the two pictures of the B3F-1052 switch as shown in Figure 2.6. Next, hold an actual switch and identify the locations of pins 1-4.

Figure 2.6. Connection diagram and physical package diagram for the B3F-1052 switch.

To build circuits, we'll use a solderless breadboard, also referred as a protoboard. The holes in the protoboard are internally connected in a systematic manner, as shown in Figure 2.7. The long columns of holes along the right and left of the protoboard are electrically connected. Some protoboards like the one in Figure 2.4 have four long columns (two on each side), while others have just two long columns (one on each side). We will connect one column to +5V and another column to ground, and we refer to them as power buses. In the middle of the protoboard, you'll find two groups of holes placed in a 0.1 inch grid. Each adjacent row of five pins is electrically connected. We usually insert components into these holes. IC chips are placed on the protoboard, such that the two rows of pins straddle the center valley. The 9S12 module also is inserted into the protoboard in such a way that the two rows of pins are across the center. The piece of paper from the kit or from page 2 of this manual should be trimmed and placed between the 9S12 and the protoboard, making it easy to identify the 9S12 pins. For example, assume we wish to connect 9S12 PT0 output to the 7406 input pin 1. First, cut a 24 gauge solid wire about a 0.5 in longer than the distance between PT0 and pin 1 of the 7406. Next, strip about 0.25 in off each end. Place one end of the wire in one of the four remaining holes of the PT0 row and the other end in one of the four remaining of the 7406 pin 1.

Page 11: EE319K Laboratory Manual - Trillworks...Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 1 valvano@mail.utexas.edu 3/9/2010 EE319K Laboratory Manual Univ of Texas at Austin,

Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 11

[email protected] 3/9/2010

Place 9S12 overthe center valley.

The five pins ineach row areconnected

The pins on theouter columnsare connected

The pins on theouter columnsare connected

The five pins ineach row areconnected Place paper

between 9S12and protoboard.

Connect +5V andground from 9S12to power buses.

Figure 2.7. The dotted lines in this figure illustrate the pattern of which pins are internally connected. Part c) After the software has been debugged on the simulator, you will build the hardware on the real board. EE319K_DP512_Artist.sch is a starter file you should use to draw your hardware circuit diagram (like Figure 2.1). The first step is to interface a push button switch. You should implement a positive logic switch, as shown in Figure 2.8. Do not place or remove wires on the protoboard while the power is on.

+5V

10kΩR1

Touched

+5V PT1

+5V

10kΩR1

Released

+0V PT1

Figure 2.8. Switch interface. Before connecting the switch to the microcomputer, please take these measurements using your digital multimeter. The input voltage (VPT1) is the signal that will eventually be connected to PT1. With a positive logic switch interface the resistor current will be VPT1/10kΩ. The voltages should be near +5 V or near 0 V and the currents should be much less than 1 mA. Parameter Value Units Conditions Resistance of the 10k resistor, R1

ohms

with power off and disconnected from circuit

Supply Voltage, V+5

volts

Powered

Input Voltage, VPT1

volts

Powered, but with switch not pressed

Resistor current

mA

Powered, but switch not pressed I=VPT1/R1

Input Voltage, VPT1

volts

Powered and with switch pressed

Resistor current

mA

Powered and switch pressed I=VPT1/R1

Table 2.1. Switch measurements.

Page 12: EE319K Laboratory Manual - Trillworks...Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 1 valvano@mail.utexas.edu 3/9/2010 EE319K Laboratory Manual Univ of Texas at Austin,

Page 12 Introduction to Embedded Systems: Interfacing to the Freescale 9S12

03/09/10

Next, you can connect the input voltage to PT1 and use the debugger to observe the input pin to verify the proper operation of the switch interface. In particular you can place PTT in the ViewBox with a b (8-bit binary) or h (8-bit hex) format, then click the Sample button to see the values of PTT. You will have to assemble your program so the label PTT is defined. The next step is to build the LED output circuit. LEDs emit light when an electric current passes through them, as shown in Figure 2.9. LEDs have polarity, meaning current must pass from anode to cathode to activate. The anode is labeled a or + , and cathode is labeled k or -. The cathode is the short lead and there may be a slight flat spot on the body of round LEDs. Thus, the anode is the longer lead. LEDs are not usually damaged by heat when soldering. Figure 2.1 shows an interface circuit that can be used in this lab. Look up the pin assignments in the 7406 data sheet. Be sure to connect +5V power to pin 14 and ground to pin 7. The 0.1 μF capacitor from +5V to ground filters the power line.

Photo: Circuit symbol: Figure 2.9. LEDs. You can use the debugger to set the direction register for PT0 to output. Then, you can set the PT0 high and low, and measure the four voltages (+5 V supply voltage, input to 7406, output from 7406 which is the LED cathode voltage, and the LED anode voltage). When active, the LED voltage should be about 2 V, and the LED current should be about 10 mA. Parameter Value Units Conditions Resistance of the 220Ω resistor, R4

ohms

with power off and disconnected from circuit

+5 V power supply V+5

volts

9S12 Output, VPT0 input to 7406

volts

with PT0 =0

7406 Output, Vk- LED k-

volts

with PT0 =0

LED a+, Va+ Bottom side of R4

volts

with PT0 =0

LED voltage

volts

calculated as Va+ - Vk-

LED current

mA

calculated as (V+5 - Va+)/R4

9S12 Output, VPT0 input to 7406

volts

with PT0 =1

7406 Output, Vk- LED k-

volts

with PT0 =1

LED a+, Va+ Bottom side of R4

volts

with PT0 =1

LED voltage

volts

calculated as Va+ - Vk-

LED current

mA

calculated as (V+5 - Va+)/R4

Table 2.2. LED measurements.

a + k - Anode Cathode

Page 13: EE319K Laboratory Manual - Trillworks...Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 1 valvano@mail.utexas.edu 3/9/2010 EE319K Laboratory Manual Univ of Texas at Austin,

Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 13

[email protected] 3/9/2010

Part d) Debug your combined hardware/software system on the actual 9S12 board. Warning: NEVER INSERT/REMOVE WIRES/CHIPS WHEN THE POWER IS ON.

Demonstration You will show the TA your program operation on the actual 9S12 board. The TA may look at your data and expect

you to understand how the data was collected and how the switch and LEDs work. Also be prepared to explain how your software works and to discuss other ways the problem could have been solved. Why the 7406 was used to interface the LED? Why do you need capacitor for 7406 chip? If there is a capactor across +5V to ground on the microcontroller board, why is a separate capacitor needed at this chip? Why was the delay 125 ms choosen (what if it were 100 times faster? 100 times slower?) How would you modify the software to change the rate at which LED flickers? The TA will pick an instruction and ask you which addressing mode it is. Execute the program step-by-step and run to cursor. What is reset vector and why do you need it? What if you change the org $4000 to org $3800? What does org do? What does fdb do? What operating point (voltage, current) exists when the LED is on? Sketch the approximate current versus voltage curve of the LED. Explain how you use the resistor value to select the operating point. What is the different between a positive logic and negative logic interface for the switch or the LED?

Deliverables 1) Two screen shots showing the system running in simulation mode, one with the LED one and one with it off. In the screen shots, please include the microcomputer and I/O windows. Typical examples are shown on the next page. 2) Circuit diagram, PCBArtist printout with your name and date (or hand drawn if you want) 3) Switch measurements (Table 2.1) 4) LED measurements (Table 2.2) 5) Assembly listing of your final program

Example screen shots in simulation mode

Page 14: EE319K Laboratory Manual - Trillworks...Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 1 valvano@mail.utexas.edu 3/9/2010 EE319K Laboratory Manual Univ of Texas at Austin,

Page 14 Introduction to Embedded Systems: Interfacing to the Freescale 9S12

03/09/10

Precautions to avoid damaging your system 0) Do not attach or remove wires on the protoboard when power is on. Always shut power off when making hardware changes to the system. 1) Touch a grounded object before handling CMOS electronics. Try not to touch any exposed wires. 2) Do not plug or unplug the 9S12 board into a protoboard while the system is powered. 3) The male pins on the docking module have been very robust as long as you limit the twisting forces. To remove the docking module from the protoboard pull straight up (or at least pull up a little at a time on each end.) 4) Use and store the system with the 9S12DP512 module plugged into a protoboard (this will reduce the chances of contacting the metal pins tied directly to the 9S12 with either your fingers or stray electrical pulses). 5) Do not use the 9S12 with any external power sources, other than the supplied wall-wart. In particular, avoid connecting signals to the 9S12 that are not within the 0 to +5V range. In particular, voltages less than 0V or greater than +5V will damage the ADC. 6) Do not connect any wires to the pins labeled PS0, PS1, PS2, PS3 or Reset. These Port S signals are already connected on the board to serial interface chips.

Apple iPhone from McDermott’s EE384N notes

Page 15: EE319K Laboratory Manual - Trillworks...Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 1 valvano@mail.utexas.edu 3/9/2010 EE319K Laboratory Manual Univ of Texas at Austin,

Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 15

[email protected] 3/9/2010

Lab 3. Minimally Intrusive Debugging Methods Preparation Read Chapter 4 (skip starred sections) as a review of EE306 Read Sections 5.1, 5.2, 5.3, 5.8, 6.1, 6.2, and 6.11 Purpose The purpose of this lab is to learn minimally intrusive debugging skills. When visualizing software running in real-time on an actual microcomputer, it is important use minimally intrusive debugging tools. The first objective of this lab is to develop an instrument called a dump, which does not depend on the availability of a debugger. A dump allows you to capture strategic information that will be viewed at a later time. The second useful debugging technique you will learn is called a heartbeat. A heartbeat is a visual means to see that your software is still running. The debugging techniques in this lab use both hardware and software and are appropriate for the real 9S12. Software skills you will learn include indexed addressing, array data structures, the TCNT timer, and subroutines. System Requirements

First, you will redesign your Lab 2 delay function using a double-nested loop without any cycle wasting instructions like idiv fdiv ediv or edivs. Next, you will design, implement, test and employ debugging instruments to experimentally verify the correct operation of your Lab 2 system. For the software approach, you will record the PTT value (includes both the input and output signals) and the time during each execution through the outer loop of the main program of Lab 2 as your system runs in real time. You will activate the TCNT timer (set TSCR1 = $80, TSCR2 = $07), which will make the timer increment every 5.33 μs in 24 MHz LOAD mode and can be used to measure time differences up to 349.5 ms. To measure the current time, you simply read the 16-bit TCNT value. This software dump should store PTT and TCNT data into arrays while the system is running in real-time, and the information will be viewed at a later time. Software dumps are an effective technique when debugging real-time software on an actual microcomputer. We will define the debugging instrument as minimally intrusive if the time to collect and store the information is short compared to the time between when information is collected. You will define an array capable of storing about 3 seconds worth of 8-bit measurements of PTT, and an array capable of storing about 3 seconds worth of 16-bit measurements of TCNT. For example, if the outer loop of your Lab 2 executes in about 62 ms (LED flashes at 8 Hz in 24 MHz LOAD mode), then the loop will be executed about 50 times in 3 seconds, so the array sizes will need to be 50 elements each. You may use either pointers or counters to store data in the arrays. You will collect performance data on the system with a no-touch, touch, no-touch sequence during the 3-second measurement.

PP7 is already interfaced to a red LED on the 9S12DP512 board itself. Write debugging software and add it to the Lab 2 system so that this LED always flashes while your program is running. In particular, initialize the direction register so PP7 is an output, and add code that toggles the LED each time through the loop. A heartbeat of this type will be added to all software written for Labs 3 through 8 in this class. It is a quick and convenient way to see if your program is still running. When you get to EE345L you can implement multiple heartbeats at various strategic places in the software and that toggle much faster than the eye can see. In these situations, you will use a logic analyzer to visualize many high-speed digital signals all at once. However, in EE319K there will be one heartbeat on PP7, and the heartbeat must occur slow enough to be seen with the eye.

Procedure

The basic approach to Lab 2 through Lab 8 will be to first develop and test the system using simulation mode. After debugging instruments themselves are tested, you will collect measurements on the real 9S12. Part a) Rewrite the Delay subroutine so it uses two nested loops. You are not allowed to use any instructions that take 10 or more cycles per instruction like idiv fdiv ediv or edivs in this subroutine. Using cycle counting, estimate how long your new function will take to execute. Part b) Write two debugging subroutines that implement a dump instrument. If we saved just the input/output data, then the dump would be called functional debugging, because we would capture input/output data of the system, without information specifying when the input/output was collected. However, you will save both the input/output data and the time, so the dump would be called performance debugging. The first subroutine (Debug_Init) initializes your dump instrument. The initialization should activate TCNT, place $FF or $FFFF into the two arrays, and initialize pointers and/or counters as needed. The second subroutine (Debug_Capture) that saves one data-point (PT1 input data, and PT0 output data) in the first array and the TCNT in the second array. Since there are only two bits to save in the first array, pack the information into one 8-bit value for ease of visualization when displayed in hexadecimal. For example, if

Page 16: EE319K Laboratory Manual - Trillworks...Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 1 valvano@mail.utexas.edu 3/9/2010 EE319K Laboratory Manual Univ of Texas at Austin,

Page 16 Introduction to Embedded Systems: Interfacing to the Freescale 9S12

03/09/10

Input (PT1) Output (PT0) save data 0 0 0000,00002, or $00 0 1 0000,00012, or $01 1 0 0001,00002, or $10 1 1 0001,00012, or $11

In this way, you will be able to visualize the data in an effective manner. Place a call to Debug_Init at the beginning of the system, and a call to Debug_Capture at the start of each execution of the outer loop. The basic steps involved in designing the data structures for this debugging instrument are as follows Allocate DataBuffer in RAM (to store 3 seconds of 8-bit input/output data) Allocate TimeBuffer in RAM (to store 3 seconds of 16-bit TCNT data) Allocate two 16-bit pointers (DataPt, TimePt), one for each array, pointing to the place to save the next data The basic steps involved in designing Debug_Init are as follows Set all entries of the first buffer to $FF (meaning no data yet saved) Set all entries of the second buffer to $FFFF (meaning no data yet saved) Initialize the two 16-bit pointers to the beginning of each buffer Set TSCR1 = $80 (enables TCNT), TSCR2 = $07 (TCNT is 128 times slower than E clock) The basic steps involved in designing Debug_Capture are as follows Return immediately if the buffers are full (pointer past the end of the buffer) Read PTT and TCNT port = PTT time = TCNT Mask capturing just bits 1,0 data = ((port&$02)<<3)+(port&$01) Dump debugging information into DataBuffer (*DataPt) = data (8-bit store) Increment pointer to next address DataPt = DataPt+1 (adds one to the address) Dump time into TimeBuffer (*TimePt) = time (16-bit store) Increment pointer to next address TimePt = TimePt+2 (adds two to the address) Both routines should save and restore any registers that it modifies (except CCR), so that the original program is not affected by the execution of the debugging instruments. The temporary variables data port time may be implemented in registers. However, the buffers and the pointers should be permanently allocated in global RAM. You can observe the debugging the arrays using a Stack window. After you have debugged your code in simulation mode, capture a screen shot showing the results as the switch is pressed then not pressed. The dumped data should start with some $00 data, next it should oscillate between $10, $11 as the switch is pressed, then return to $00 when the switch is released. Part c) By counting cycles in the listing file, estimate the execution time of the Debug_Capture subroutine. Assuming the actual E clock speed, convert the number of cycles to time. Next, estimate the time between calls to Debug_Capture. Calculate the percentage overhead required to run the debugging instrument (100 times execution time divided by time between calls, in percent). This percentage will be a quantitative measure of the intrusiveness of your debugging instrument. Either hand-write the estimations and calculations on your printout or type it in as comments to your program. Part d) Write the debugging instruments that implement the heartbeat (initialization and toggle). The heartbeat instruments can be embedded as simple assembly language software without making them separate subroutines. Part e) Debug your combined hardware/software system first with the simulator, then on the actual 9S12 board. Part f) Run your debugging instrument capturing the sequence of input/outputs as you touch, then release the switch. Use the collected data to measure the period of the flashing LED. Your measurement should be accurate to 5.33 μs. Demonstration You will show the TA your program operation on the actual 9S12 board. The TA may look at your data and expect you to understand how the data was collected and what the data means. Also be prepared to explain how your software works and to discuss other ways the problem could have been solved. Does the LED flash at a slower rate in Lab 3 than it did in Lab 2? Why? The TA will pick an instruction in your program and ask how much time does it take that instruction to execute in μsec. Does it always take same amount of time to execute? You will be asked to create a breakpoint, and a scanpoint. What’s

Page 17: EE319K Laboratory Manual - Trillworks...Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 1 valvano@mail.utexas.edu 3/9/2010 EE319K Laboratory Manual Univ of Texas at Austin,

Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 17

[email protected] 3/9/2010

the difference between two? Is your debugging tool minimally intrusive or non-intrusive? What do you mean by intrusiveness? Is your code “friendly”? How do you define masking? How do you set/clear one bit in an 8-bit number without affecting other bits? What is the difference between bra, jmp and bsr instructions? How do you initialize the timer? What is one TCNT in μsec? How much time does your debugging routine take? Are there other ways to measure the time for your debugging code to execute? How do you calculate the sizes of the port data and the timestamp data? Does it make any difference, to the collected timer data if the board is in run mode instead of load mode? Why does the pointer to the time-stamp array need to be incremented by two, if you want to point to the next element in the array? How do you allocate global variables? Deliverables 1) A screen shot showing the system running in simulation mode. In the screen shot, please show the dumped data in a stack window and the I/O window, as illustrated below 2) Assembly listing of your final program with both the dump and heartbeat instruments 3) Estimation of the execution time of your debugging instrument Debug_Capture (part d) 4) Results of the debugging instrument (part e) and the calculation of the flashing LED period in msec.

Example screen shot of Lab3 in simulation mode. The log window shows the scanpoint inside the main loop. The stack window’s Memory box displays contents from address DataBuffer to TimeBuffer+2*SIZE, where SIZE is 50 in this solution. In simulation mode, the E clock period is 125 ns. With divide by 128, the TCNT period is 16 μs. Notice the first time difference between executions through the loop is $4027-$21A2, which is 7813. 7813*16 μs is about 125 ms, as originally designed in Lab 2. In LOAD mode, the E clock period will be 41.67 ns, and the TCNT period will be 5.33 μs.

Page 18: EE319K Laboratory Manual - Trillworks...Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 1 valvano@mail.utexas.edu 3/9/2010 EE319K Laboratory Manual Univ of Texas at Austin,

Page 18 Introduction to Embedded Systems: Interfacing to the Freescale 9S12

03/09/10

9S12DP512

25

50

26

1

PAD11

PA3

PA0

PA6PA5PA4

PA1

PB7PB6PB5PB4PB3

PB0

PB2

PA7

PA2

PB1

PAD10PAD9PAD8

PE2PE4

PE1PE3

PJ1

PAD14

PK4

PK1PK0PJ0PJ7PJ6PM7PM6PM5

PK3

PK5PK7PE7Gnd +5

PK2

PAD15

PM3PM4

PAD13PAD12

PM2

PM0PM1

H29S12DP512

25

50

26

1

PAD3

PS1

PT5

PS5PS6PS7

PT6

PT4PT3PT2PT1PT0

PP5

PP7

PS4

PT7

PP6

PAD2PAD1PAD0

PP4PP3

PP1PP2

PP0

PAD6

PE0

PH0PH1PH2PH3PH4PH5PH6PH7

Reset*

PE1+5PS0GndGnd

PE7

PAD7

PE4PS2

PAD5PAD4

PS3

VRHVRL

H19S12DP512

25

50

26

1

AN03

TxD0

PT5

MOSISckSS*

PT6

PT4PT3PT2PT1PT0

PP5

PP7

MISO

PT7

PP6

AN02AN01AN00

PP4PP3

PP1PP2

PP0

AN06

XIRQ*

PH0PH1PH2PH3PH4PH5PH6PH7

Reset*

IRQ*+5RxD0GndGnd

PE7

AN07

EclkRxD1

AN05AN04

TxD1

VRHVRL

H19S12DP512

25

50

26

1

AN11

AD11

AD8

AD14AD13AD12

AD9

AD7AD6AD5AD4AD3

AD0

AD2

AD15

AD10

AD1

AN10AN09AN08

R/WEclk

IRQ*LSTRB*

PJ1

AN14

XA18

XA15XA14PJ0SCLSDAPM7PM6PM5

XA17

XA19ECS*

XCLKS*Gnd +5

XA16

AN15

PM3PM4

AN13AN12

PM2

RxCANTxCAN

H2DM912C32

20

40

21

1

CANL CANH

PE1

PT5PT4PT3PT2PT1PT0PM0PM1

PT7

PE0+5ResetGndVin

PT6

AN0

AN3

RXDTRGnd

AN2

AN4AN5AN6AN7PM5

PM2

PM4

TX

AN1

PM3

EE319K EE345L

9S12DP512

25

50

26

1

PAD11

PA3

PA0

PA6PA5PA4

PA1

PB7PB6PB5PB4PB3

PB0

PB2

PA7

PA2

PB1

PAD10PAD9PAD8

PE2PE4

PE1PE3

PJ1

PAD14

PK4

PK1PK0PJ0PJ7PJ6PM7PM6PM5

PK3

PK5PK7PE7Gnd +5

PK2

PAD15

PM3PM4

PAD13PAD12

PM2

PM0PM1

H29S12DP512

25

50

26

1

PAD3

PS1

PT5

PS5PS6PS7

PT6

PT4PT3PT2PT1PT0

PP5

PP7

PS4

PT7

PP6

PAD2PAD1PAD0

PP4PP3

PP1PP2

PP0

PAD6

PE0

PH0PH1PH2PH3PH4PH5PH6PH7

Reset*

PE1+5PS0GndGnd

PE7

PAD7

PE4PS2

PAD5PAD4

PS3

VRHVRL

H19S12DP512

25

50

26

1

AN03

TxD0

PT5

MOSISckSS*

PT6

PT4PT3PT2PT1PT0

PP5

PP7

MISO

PT7

PP6

AN02AN01AN00

PP4PP3

PP1PP2

PP0

AN06

XIRQ*

PH0PH1PH2PH3PH4PH5PH6PH7

Reset*

IRQ*+5RxD0GndGnd

PE7

AN07

EclkRxD1

AN05AN04

TxD1

VRHVRL

H19S12DP512

25

50

26

1

AN11

AD11

AD8

AD14AD13AD12

AD9

AD7AD6AD5AD4AD3

AD0

AD2

AD15

AD10

AD1

AN10AN09AN08

R/WEclk

IRQ*LSTRB*

PJ1

AN14

XA18

XA15XA14PJ0SCLSDAPM7PM6PM5

XA17

XA19ECS*

XCLKS*Gnd +5

XA16

AN15

PM3PM4

AN13AN12

PM2

RxCANTxCAN

H2DM912C32

20

40

21

1

CANL CANH

PE1

PT5PT4PT3PT2PT1PT0PM0PM1

PT7

PE0+5ResetGndVin

PT6

AN0

AN3

RXDTRGnd

AN2

AN4AN5AN6AN7PM5

PM2

PM4

TX

AN1

PM3

EE319K EE345L

Page 19: EE319K Laboratory Manual - Trillworks...Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 1 valvano@mail.utexas.edu 3/9/2010 EE319K Laboratory Manual Univ of Texas at Austin,

Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 19

[email protected] 3/9/2010

Lab 4. Traffic Light Controller Preparation Read Sections 4.5, 6.1, 6.5, 6.8 in the textbook See http://users.ece.utexas.edu/~valvano/EE319K/LED_yellow.pdf See http://users.ece.utexas.edu/~valvano/EE319K/LED_green.pdf In preparation for this assignment, review finite state machines, linked-lists, and memory allocation. You should also run and analyze the linked-list controllers found in example files moore.rtf and mealy.rtf. Purpose

This lab has these major objectives: 1) the understanding and implementing linked-list data structures; 2) learning how to create a segmented software system; and 3) the study of real-time synchronization by designing a finite state machine controller. Software skills you will learn include advanced indexed addressing, linked-list data structures, creating fixed-time delays using the TCNT timer, and debugging real-time systems.

System Requirements Consider a 4-corner intersection as shown in Figure 4.1. There are two one-way streets are labeled North (cars travel South) and East (cars travel West). There are three inputs to your 9S12, two are car sensors, and one is a walk button. The North sensor will be true (1) if one or more cars are near the intersection on the North road. Similarly, the East sensor will be true (1) if one or more cars are near the intersection on the East road. The Walk button will be pushed by a pedestrian when he or she wishes to cross in any direction. To request a walk, a pedestrian must push and hold the walk button until the walk light is active (i.e., it behaves like a person sensor rather than a traditional walk button). When a car sensor is released, it means no cars are waiting to enter the intersection. There are 7 outputs from your microcomputer that control the two Red/Yellow/Green traffic lights, and the “don’t walk” light. You will use the existing red LED on PP7 for the “don’t walk” light. When both Red lights are on, both Yellow lights are on, and the “don’t walk” light is off, pedestrians are allowed to cross. When the “don’t walk” light flashes (and the two traffic signals are red), pedestrians should hurry up and finish crossing. When the “don’t walk” light is on, pedestrians should not enter the intersection. The simulator allows you to attach binary switches to simulate the three inputs and colored LED lights to simulate the seven outputs.

North

EastR

GY

R Y G R

Walk

Don’t walklight

Port T

Port P

Figure 4.1. Traffic Light Intersection (both red and yellow simultaneously on means walk). Traffic should not be allowed to crash. I.e., there should not be a green or yellow LED on one road at the same time there is a green or yellow LED on the other road. You should exercise common sense when assigning the length of time that the traffic light will spend in each state; so that the system changes at a speed convenient for the TA (stuff changes fast enough so the TA doesn’t get bored, but not so fast that the TA can’t see what is happening). Cars should not be allowed to hit the pedestrians. The walk sequence should be realistic (off means walk, flashing means hurry, continuous on means don’t walk). You may assume the three sensors remain active for as long as service is required.

There is no single, “best” way to implement your system. However, your scheme must use a linked-list data structure stored in EEPROM. There should be a 1-1 mapping from the FSM states and the linked-list elements. A “good” solution will have about 10 to 20 states in the finite state machine, and provides for input dependence. Try not to focus on the civil engineering issues. I.e., the machine does not have to maximize traffic flow or minimize waiting. On the other hand if there are multiple requests, the system should cycle through, servicing them all. Build a quality computer engineering solution that is easy to understand and easy to change. We expect your solution to behave reasonably and have 10 to 20 states. It is unacceptable if your machine is less than 10 states. If your machine has more than 20 states, you have made it

Page 20: EE319K Laboratory Manual - Trillworks...Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 1 valvano@mail.utexas.edu 3/9/2010 EE319K Laboratory Manual Univ of Texas at Austin,

Page 20 Introduction to Embedded Systems: Interfacing to the Freescale 9S12

03/09/10

more complicated than we had in mind. Because we have three inputs, there will be 8 next state arrows. One way to draw the FSM graph to make it easier to read is to use X to signify don’t care. For example, compare the Figure 6.20 in the book to the FSM graph in Figure 4.2 below. Drawing two arrows labeled 01 and 11 is the same as drawing one arrow with the label X1. When we implement the data structure, we will expand the shorthand and explicitly list all possible next states.

goN

30

Next if input is 01 or 11

100001

Wait time

X1X0 waitN

5100010

goE

30001100

waitE

5010100

XX 1X0X

XX

Output

Figure 4.2. FSM from the book Figure 6.20 redrawn with a short hand format.

This lab was written in a manner intended to give you a great deal of flexibility in how you draw the FSM graph, while at the same time require very specific boundaries on how the assembly controller must be written. This flexibility causes students to be question “when am I done?” or “is this enough for an A?” To clarify the distinction between computer engineering, and civil engineering, I restate the computer engineering requirements. In particular do these 8 requirements well and you can get a good grade on this lab.

0) The system provides for input dependence. This means each state has 8 arrows such that the next state depends on the current state and the input. You can implement a Mealy machine if you want, but we expect most students will implement a Moore. This means you can not solve the problem by simply cycling through all the states regardless of the input.

1) There must be a 1-1 mapping between state graph and data structure. For a Moore machine, this means

each state in the graph has a name, an output, a time to wait, and 8 next state arrows (one for each input). The data structure has exactly these components: a name, an output, a time to wait, and 8 next state pointers (one for each input). There is no more or no less information in the data structure then the information in the state graph.

2) There can be no conditional branches in program, other than the bpl in Timer_Wait and the dbne in Timer_Wait10ms. See the example 6.6 in the book.

3) The state graph defines exactly what the system does in a clear and unambiguous fashion. 4) Each state has the same format of each state. This means every state has exact one name, one output, one

time to wait, and 8 next pointers. 5) Please use good names and labels (easy to understand and easy to change). Examples of bad state names

are S0 and S1. 6) Do not allow cars to crash into each other. Do not allow pedestrians to walk in one direction while any

cars are allowed to go. Engineers do not want people to get hurt. 7) There should be 10 to 20 states with either a Mealy or Moore finite state machine. What if I have less than

10 states? Usually students with less than 10 states did not flash the don’t walk light, or they flashed the lights using a counter. Counters violate the “no conditional branch” requirement.

There are many civil engineering questions that students ask. How you choose to answer these questions will

determine how good a civil engineer you are, but will not affect your grade on this lab. For each question, there are many possible answers, and you are free to choose how you want to answer it. It is reasonable however for the TA to ask how you would have implemented other answers to these civil engineering questions using the same FSM structure.

0) How long should I wait in each state? Possible answer: 1 to 2 seconds of real TA time.

Page 21: EE319K Laboratory Manual - Trillworks...Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 1 valvano@mail.utexas.edu 3/9/2010 EE319K Laboratory Manual Univ of Texas at Austin,

Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 21

[email protected] 3/9/2010

1) What happens if I push 2 or 3 buttons at a time? Possible answer: cycle through the requests servicing them in a round robin fashion. If all three buttons are pushed continuously you could cycle 16 states:

Green North, Red East, Don’t Walk Yellow North, Red East, Don’t Walk Red North, Red East, Don’t Walk Red North, Green East, Don’t Walk Red North, Yellow East, Don’t Walk Red North, Red East, Don’t Walk Red+Yellow North, Red+Yellow East, (means walk) Red North, Red East, Don’t Walk (short time) Red North, Red East (short time) Red North, Red East, Don’t Walk (short time) Red North, Red East (short time) Red North, Red East, Don’t Walk (short time) Red North, Red East (short time) Red North, Red East, Don’t Walk (short time) Red North, Red East (short time) Red North, Red East, Don’t Walk (short time) 2) What if I push the walk button, but release it before it is serviced? Possible answer: ignore the request as

if it never happened. Possible answer: add a duplicate set of states. The first set of states means the walk button is not pressed. The second set of states means the walk operation is requested. Go from the first set to the second set whenever the walk is pushed. Go from the second back to the first whenever the walk condition is output. The two sets of states allow you to remember that a walk has been requested; in this way the request is serviced when appropriate.

3) What if I push a car button, but release it before it is serviced? Possible answer: ignore the request as if it

never happened (e.g., car came to a red light, came to a full stop, then turned right). 4) Assume there are no cars and the light is green on the North, what if a car now comes on the East? Do I

have to recognize a new input right away or wait until the end of the wait time? Possible answer: no, just wait until the end of the current wait, then service it. Possible answer: yes; break states with long waits into multiple states with same output but shorter waits.

5) What if the walk button is pushed while the don’t walk light is flashing? Possible answer: ignore it, go to

a green light state and if the walk button is still pushed, then go to walk state again. Possible answer: if no cars are waiting, go back to the walk state. Possible answer: remember that the button was pushed, and go to a walk state after the next green light state.

6) Does the walk occur on just one street or both? Possible answer: stop all cars and let people walk across

either or both streets. 7) How do I signify a walk condition? Possible answer: output red+yellow on both streets and turn the

don’t walk LED off as shown in Figure 4.3.

Figure 4.3. One possible way to signify walk is to put both red and yellow on.

Page 22: EE319K Laboratory Manual - Trillworks...Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 1 valvano@mail.utexas.edu 3/9/2010 EE319K Laboratory Manual Univ of Texas at Austin,

Page 22 Introduction to Embedded Systems: Interfacing to the Freescale 9S12

03/09/10

In real products that we market to consumers, we put the executable instructions and the finite state machine linked-list data structure into the nonvolatile memory such as flash EEPROM. A good implementation will allow minor changes to the finite machine (adding states, modifying times, removing states, moving transition arrows, changing the initial state) simply by changing the linked-list data structure, without changing the executable instructions. Making changes to executable code requires you to debug/verify the system again. If there is a 1-1 mapping from FSM to linked-list data structure, then if we just change the state graph and follow the 1-1 mapping, we can be confident our new system operate the new FSM properly. Obviously, if we add another input sensor or output light, it may be necessary to update the executable part of the software, re-assemble and retest the system. Procedure You will create a segmented software system putting global variables into RAM, local variables into registers, constants and fixed data structures into EEPROM, and program object code into EEPROM. Most microcontrollers have a rich set of timer functions. For this lab, you will develop the ability to wait a prescribed amount of time. This initialization function will enable the 16-bit TCNT timer, by setting bit 7 of TSCR1. The value in TSCR2 determines the rate at which TCNT will increment. Let n be the value in TSCR2, which can vary from 0 to 7, the TCNT counts 2n times slower than the E clock. ;************ Timer_ Init *************** ; inputs: none ; outputs: none ; errors: be careful, other routines may also set TSCR2 Timer_Init movb #$80,TSCR1 ; enable TCNT movb #$07,TSCR2 ; TCNT counts 128 times slower than the E clock rts The following function will wait a fixed number of cycles using the TCNT timer. ;************ Timer_Wait*************** ; inputs: RegD is the number of cycles to wait ; outputs: none ; errors: RegD must be less or equal to 32767 Timer_Wait addd TCNT ;TCNT value at the end of the wait wait cpd TCNT ;RegD-TCNT<0 when RegD<Tcnt bpl wait rts The following function will wait a fixed number of 0.01 sec intervals using the previous function. ;************ Timer_Wait10ms*************** ; time delay ; inputs: RegY is the number of 10ms to wait ; outputs: none ; errors: RegY=0 will wait 655.36 sec Timer_Wait10ms ldd #CYCLES10MS ;this constant depends on speed of your microcontroller bsr Timer_Wait dbne Y,Timer_Wait10ms rts In general, using cycle-counting (for-loops) for delays has the problem of conditional branches and data-dependent execution times. If an interrupt were to occur during a cycle-counting delay, then the delay would be inaccurate using the cycle-counting method. In the above method, however, the timing will be very accurate, even if an interrupt were to occur while the microcomputer was waiting. In more sophisticated systems, using timer interrupts provide a more flexible and even more accurate mechanism for microcomputer synchronization. Interrupt synchronization will be used in Labs 6 through 10. A linked-list solution may not run the fastest, or occupy the fewest memory bytes, but it is a structured technique that is easy to understand, easy to implement, easy to debug, and easy to upgrade.

Page 23: EE319K Laboratory Manual - Trillworks...Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 1 valvano@mail.utexas.edu 3/9/2010 EE319K Laboratory Manual Univ of Texas at Austin,

Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 23

[email protected] 3/9/2010

The basic approach to this lab will be to first develop and debug your system using the simulator. During this phase of the project you will run with a fast TCNT clock (TSCR2=0). After the software is debugged, you will interface actual lights and switches to the 9S12, and run your software on the real 9S12. During this phase of the project you will run with a slow TCNT clock (TSCR2=$07). As you have experienced, the simulator requires more actual time to simulate 1 cycle of the microcomputer. On the other hand, the correct simulation time is maintained in the TCNT register, which is incremented every cycle of simulation time. The simulator speed depends on the amount of information it needs to update into the windows. Unfortunately, even with the least amount of window updates, it would take a long for the simulator to process the typical 3 minutes it might take for a “real” car to pass through a “real” traffic intersection. Consequently, the cars in this traffic intersection travel much faster than “real” cars. In other words, you are encouraged to adjust the time delays so that the operation of your machine is convenient for you to debug and for the TA to observe during demonstration. Part a) Build an I/O system in TExaS with the appropriate names and colors on the lights and switches. Use Port P for the seven outputs and Port T for the three inputs. Think about which ports you will be using in part d), so that you simulate the exact system you will eventually plan to build. Part b) Design a finite state machine that implements a good traffic light system. Include a graphical picture of your finite state machine showing the various states, inputs, outputs, wait times and transitions. Part c) Write and debug the assembly code that implements the traffic light control system. During the debugging phase with the TExaS simulator, you can run with a fast TCNT clock (TSCR2=$00). In simulation mode, capture a sequence of four to six screen shots showing the operation when cars are present on both roads. Part d) After you have debugged your system in simulation mode, you will implement it on the real board. Use Port P for the seven outputs and Port T for the input inputs. EE319K_DP512_Artist.sch is a starter file you should use to draw your hardware circuit diagram using the program PCB Artist. The first step is to interface three push button switches for the sensors. You can implement positive logic or negative logic switches. Do not place or remove wires on the protoboard while the power is on. Build the switch circuits and test the voltages using a digital voltmeter. You can also use the debugger to observe the input pin to verify the proper operation of the interface. The next step is to build six LED output circuits. Build the system physically in a shape that matches a traffic intersection, so the TA can better visualize the operation of the system. You will use the PP7 LED in addition to the 6 external LEDs you will build on your protoboard. Look up the pin assignments in the 7406 data sheet. Be sure to connect +5V power to pin 14 and ground to pin 7. You can use the debugger to set the direction register to output. Then, you can set the output high and low, and measure the three voltages (input to 7406, output from 7406 which is the LED cathode voltage, and the LED anode voltage). Part e) Debug your combined hardware/software system on the actual 9S12 board. When using the real 9S12, you should run with a slow TCNT clock (TSCR2=$07). Demonstration During checkout, you will be asked to show both the simulated and actual 9S12 systems to the TA. The TAs will expect you to know how the Timer_Wait function works, and know how to add more input signals and/or output signals. An interesting question that may be asked during checkout is how you could experimentally prove your system works. In other words, what data should be collected and how would you collect it? If there were an accident, could you theoretically prove to the judge and jury that your software implements the FSM? What type of FSM do you have? What other types are there? How many states does it have? In general, how many next-state arrows are there? Explain how the linked list is used to implement the FSM. Explain the mathematical equation used to calculate the address of the next state, depending on the current state and the input. Be prepared to write software that delays 1 second without using the timer (you can use a calculator and manual). How do you prove the delay will be 1 second? Explain the difference between the blt and blo instructions. List some general qualities that would characterize a good FSM. Deliverables 1) A sequence of screen shots showing the system running in simulation mode with cars coming on both roads 2) Circuit diagram (with your name and date). Use PCB Artist or you may hand draw it so it looks like Fig. 2.1 3) Drawing of the finite state machine 4) Assembly listing of your final program

Page 24: EE319K Laboratory Manual - Trillworks...Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 1 valvano@mail.utexas.edu 3/9/2010 EE319K Laboratory Manual Univ of Texas at Austin,

Page 24 Introduction to Embedded Systems: Interfacing to the Freescale 9S12

03/09/10

Your I/O window may look slightly different from these examples (e.g., you are free to assign signals to different bits within output Port P and input Port T.)

___________________________________________________________________________________

___________________________________________________________________________________

___________________________________________________________________________________

Page 25: EE319K Laboratory Manual - Trillworks...Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 1 valvano@mail.utexas.edu 3/9/2010 EE319K Laboratory Manual Univ of Texas at Austin,

Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 25

[email protected] 3/9/2010

Lab 5. LCD Device Driver Preparation Read Sections 7.1, 7.2, 7.3, 7.4, 8.4, and 10.1 Download the data sheets for the LCD display http://users.ece.utexas.edu/~valvano/Datasheets/LCDOptrex.pdf http://users.ece.utexas.edu/~valvano/Datasheets/LCD.pdf http://users.ece.utexas.edu/~valvano/Datasheets/LCDHD44780.pdf

HD44780.RTF program included with the TExaS example files. Purpose

This lab has these major objectives: 1) to interface an LCD interface that can be used to display information on the embedded system; 2) to use post-increment indexed addressing to access strings; 3) to learn how to design implement and test a device driver; 4) to learn how to allocate and use local variables on the stack; 5) to use fixed-point numbers to store non-integer values. System Requirements Please interface the LCD to the 9S12DP512 using the connections shown in Figure 5.1. This configuration employs 4-bit data mode, which requires fewer I/O pins but necessitates a more complex communication protocol. The examples in the book and in HD44780.RTF employ 8-bit mode. Many microcontrollers have a limited number of pins, therefore you will interface the LCD using 4-bit data mode, which requires only 6 output pins of the 9S12. This lab will use “blind cycle” synchronization, which means after the software issues an output command to the LCD, it will blindly wait a fixed amount of time for that command to complete. For 16-pin LCD devices pins 15 and 16 should be left not connected. Pins 15 and 16implement a back light allowing the display to operate in the dark, but this feature will not be used in this lab. The LCD is physically configured as 16 characters in one row, but internally the device is configured as 2 rows of 8. The left-most 8 characters exist at addresses $00 $01 $02 $03 $04 $05 $06 and $07. The right-mode 8 characters exist at addresses $40 $41 $42 $43 $44 $45 $46 $47. In particular, the ASCII character at LCD address $07 is physically adjacent to the character at LCD address $40. The objective of this lab is to develop a device driver for the LCD display. A device driver is a set of functions that facilitate the usage of an I/O port. In particular, there are three components of a device driver. First component is the description of the driver. If the software were being in C, then this description would have been the function prototypes for the public functions, which would have been placed in the header file of the driver, e.g., the LCD.H. Since this driver will be developed in assembly, your descriptions are placed in the comments before each subroutine. It is during the design phase of a project that this information is specified. In this lab, you are required to develop and test these seven public functions (notice that public functions include LCD_ in their names)

Figure 5.1. One possible circuit diagram that interfaces the LCD to the 9S12DP512. ;---------------------LCD_Open--------------------- ; initialize the LCD display, called once at beginning ; Input: none ; Output: none ; Registers modified: CCR ;---------------------LCD_Clear--------------------- ; clear the LCD display, send cursor to home ; Input: none ; Outputs: none ; Registers modified: CCR ;---------------------LCD_OutChar--------------------- ; sends one ASCII to the LCD display ; Input: RegD (call by value) letter is 8-bit ASCII code

Page 26: EE319K Laboratory Manual - Trillworks...Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 1 valvano@mail.utexas.edu 3/9/2010 EE319K Laboratory Manual Univ of Texas at Austin,

Page 26 Introduction to Embedded Systems: Interfacing to the Freescale 9S12

03/09/10

; Outputs: none ; Registers modified: CCR ;-----------------------LCD_GoTo----------------------- ; Move cursor (set display address) ; Input: RegD is display address is 0 to 7, or $40 to $47 ; Output: none ; errors: it will check for legal address ; ---------------------LCD_OutString------------- ; Output character string to LCD display, terminated by a NULL(0) ; Inputs: RegD (call by reference) points to a string of ASCII characters ; Outputs: none ; Registers modified: CCR ;-----------------------LCD_OutDec----------------------- ; Output a 16-bit number in unsigned decimal format ; Input: RegD (call by value) 16-bit unsigned number ; Output: none ; Registers modified: CCR ; -----------------------LCD_OutFix---------------------- ; Output characters to LCD display in fixed-point format ; unsigned decimal, resolution 0.001, range 0.000 to 9.999 ; Inputs: RegD is an unsigned 16-bit number ; Outputs: none ; Registers modified: CCR ; E.g., RegD=0, then output ″0.000 ″ ; RegD=3, then output ″0.003 ″ ; RegD=89, then output ″0.089 ″ ; RegD=123, then output ″0.123 ″ ; RegD=9999, then output ″9.999 ″ ; RegD>9999, then output ″*.*** ″ The second component of a device driver is the implementation of the functions that perform the I/O. If the driver were being developed in C, then the implementations would have been placed in the corresponding code file, e.g., LCD.C. When developing a driver in assembly, the implementations are the instructions and comments placed inside the body of the subroutines. In addition to public functions, a device driver can also have private functions. This interface will require a private function that outputs to commands to the LCD (notice that private functions do not include LCD_ in their names). ;--------------- outCsrNibble ------------------ ; sends 4 bits to the LCD control/status ; Input: RegA is 4-bit command, in bit positions 3,2,1,0 of RegA ; Output: none outCsrNibble 1) E=0, RS=0 2) 4-bit DB7,DB6,DB5,DB4 = nibble (shifting the data to match your interface) 3) E=1 4) E=0 (latch 4-bits into LCD) ;---------------------outCsr--------------------- ; sends one command code to the LCD control/status ; Input: RegA is 8-bit command to execute ; Output: none 0) save any registers that will be destroyed by pushing on the stack 1) outCsrNibble(most significant nibble of command) 2) outCsrNibble(least significant nibble of command) 3) blind cycle 90 us wait 4) restore the registers by pulling off the stack An important factor in device driver design is to separate the policies of the interface (how to use the programs, which is defined in the comments placed at the top of each subroutine) from the mechanisms (how the programs are implemented,

Page 27: EE319K Laboratory Manual - Trillworks...Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 1 valvano@mail.utexas.edu 3/9/2010 EE319K Laboratory Manual Univ of Texas at Austin,

Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 27

[email protected] 3/9/2010

which is described in the comments placed within the body of the subroutine.) Possible algorithms for the seven functions are as follows LCD_Open 0) save any registers that will be destroyed by pushing on the stack 1) initialize timer Timer_Init() 2) wait 20ms allowing the LCD to power up (can skip this step in TExaS) 3) set direction register(s) so that all pins are output signals to the LCD 4) outCsrNibble($03) (DL=1 8-bit mode) 5) blind cycle 5ms wait 6) outCsrNibble($03) (DL=1 8-bit mode) 7) blind cycle 100us wait 8) outCsrNibble($03) (DL=1 8-bit mode) 9) blind cycle 100us wait (not called for, but do it anyway) 10)outCsrNibble($02)(DL=0 4-bit mode) 11)blind cycle 100 us wait 12)outCsr($06) // I/D=1 Increment, S=0 no displayshift 13)outCsr($0C) // D=1 displayon, C=0 cursoroff, B=0 blink off 14)outCsr($14) // S/C=0 cursormove, R/L=1 shiftright 15)outCsr($28) // DL=0 4bit, N=1 2 line, F=0 5by7 dots 16)restore the registers by pulling off the stack LCD_OutChar(8-bit ASCII character) 0) save any registers that will be destroyed by pushing on the stack 1) E=0, RS=1 2) 4-bit DB7,DB6,DB5,DB4 = most significant nibble of data 3) E=1 4) E=0 (latch 4-bits into LCD) 5) 4-bit DB7,DB6,DB5,DB4 = least significant nibble of data 6) E=1 7) E=0 (latch 4-bits into LCD) 8) blind cycle 90 us wait 9) restore the registers by pulling off the stack LCD_Clear 0) save any registers that will be destroyed by pushing on the stack 1) outCsr($01) // Clear Display 2) blind cycle 1.64ms wait 3) outCsr($02) // Cursor to home 4) blind cycle 1.64ms wait 5) restore the registers by pulling off the stack LCD_OutString(pointer to null-terminated ASCII string) 0) save any registers that will be destroyed by pushing on the stack 1) read one character from the string 2) increment the sting pointer to the next character 3) break out of loop (go to step 6) if the character is NULL(0) 4) output the character to the LCD by calling LCD_OutChar 5) loop back to step 1) 6) restore the registers by pulling off the stack LCD_GoTo(8-bit DDaddr) 0) save any registers that will be destroyed by pushing on the stack 1) go to step 3 if DDaddr is $08 to $3F or $48 to $FF 2) outCsr(DDaddr+$80) 3) restore the registers by pulling off the stack LCD_OutDec(16-bit n) (recursive implementation) (you must use symbolic binding for the local variable) 1) save registers by pushing, allocate local variable n on the stack 2) set n with the input parameter passed in RegD 3) if(n >= 10){ LCD_OutDec(n/10); n = n%10;

Page 28: EE319K Laboratory Manual - Trillworks...Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 1 valvano@mail.utexas.edu 3/9/2010 EE319K Laboratory Manual Univ of Texas at Austin,

Page 28 Introduction to Embedded Systems: Interfacing to the Freescale 9S12

03/09/10

} 4) LCD_OutChar(n+$30); /* n is between 0 and 9 */ 5) deallocate variable, restore registers by pulling LCD_OutFix(16-bit num) (you must use symbolic binding for the local variables) 0) save any registers that will be destroyed by pushing on the stack 1) allocate local variables letter and num on the stack 2) initialize num to the input parameter, which is the integer part 3) if number is less or equal to 9999, go the step 6 4) output the string ″*.*** ″ calling LCD_OutString 5) go to step 19 6) perform the division num/1000, putting the quotient in letter, and the remainder in num 7) convert the ones digit to ASCII, letter = letter+$30 8) output letter to the LCD by calling LCD_OutChar 9) output ′.′ to the LCD by calling LCD_OutChar 10)perform the division num/100, putting the quotient in letter, and the remainder in num 11)convert the tenths digit to ASCII, letter = letter+$30 12)output letter to the LCD by calling LCD_OutChar 13)perform the division num/10, putting the quotient in letter, and the remainder in num 14)convert the hundredths digit to ASCII, letter = letter+$30 15)output letter to the LCD by calling LCD_OutChar 16)convert the thousandths digit to ASCII, letter = num +$30 17)output letter to the LCD by calling LCD_OutChar 18)output ′ ′ to the LCD by calling LCD_OutChar 19)deallocate variables 20)restore the registers by pulling off the stack The third component of a device driver is a main program that calls the driver functions. This software has two purposes. For the developer (you), it provides a means to test the driver functions. It should illustrate the full range of features available with the system. The second purpose of the main program is to give your client or customer (e.g., the TA) examples of how to use your driver. Here is a 9S12DP512 example test program, assuming a positive logic switch is connected to Port T bit 0 (PT0). PP7 as always will be a heart beat showing the software is running. org $4000 main lds #$4000 bclr DDRT,#$01 ;PT0 digital input bset DDRP,#$80 ;PP7 digital output, heartbeat to LED jsr LCD_Open ;***Your function that initializes the LCD*** cli start jsr LCD_Clear ;***Your function that clears the display*** ldd #Welcome jsr LCD_OutString ;***Your function that outputs a string*** ldx #TestData brset PTT,#$01,* ;wait for switch release ;**wait 10ms for switch to stop bouncing** brclr PTT,#$01,* ;wait for switch touch loop ldaa PTP eora #$80 ;heartbeat staa PTP jsr LCD_Clear ;***Your function that clears the display*** ldd 0,x jsr LCD_OutDec ;***Your function that outputs an integer*** ldd #$40 ;Cursor location of the 8th position jsr LCD_GoTo ;***Your function that moves the cursor*** ldd 2,x+ jsr LCD_OutFix ;***Your function that outputs a fixed-point***

Page 29: EE319K Laboratory Manual - Trillworks...Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 1 valvano@mail.utexas.edu 3/9/2010 EE319K Laboratory Manual Univ of Texas at Austin,

Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 29

[email protected] 3/9/2010

brset PTT,#$01,* ;wait for switch release ;** wait 10ms for switch to stop bouncing ** brclr PTT,#$01,* ;wait for switch touch cpx #TestDataEnd bne loop bra start Welcome fcc "Welcome " fcc " " ;32 spaces fcc "to 319K!" fcb 0 TestData fdb 0,7,34,117,5432,7890,9999,10000,21789,65535 TestDataEnd Procedure

The basic approach to this lab will be to first develop and debug your system using the simulator. During this phase of the project you will use the TExaS debugger to observe your software operation. After the software is debugged, you will run your software on the real 9S12. There are many functions to write in this lab, so it is important to develop the device driver in small pieces. One technique you might find useful is desk checking. Basically, you hand-execute your functions with a specific input parameter. For example, using just a pencil and paper think about the sequential steps that will occur when LCD_OutDec or LCD_OutFix processes the input 9876. Later, while you are debugging the actual functions on the simulator, you can single step the program and compare the actual data with your expected data. Part a) One by one each of the subroutines should be designed, implemented and tested. Successive refinement is a development approach that can be used to solve complex problems. If the problem is too complicated to envision a solution, you should redefine the problem and solve an easier problem. If it is still too complicated, redefine it again, simplifying it even more. You could simplify LCD_OutFix 1) implement the variables in global variables (rather than as local variables on the stack) 2) ignore special cases with illegal inputs 3) implement just one decimal digit During the development phase, you implement and test the simpler problem then refine it, adding back the complexity required to solve the original problem. You could simplify LCD_OutDec in a similar fashion. In simulation mode, capture two screen shots of the I/O window showing the proper operation of the system (e.g., Welcome and 5432). Your LCD_OutDec and LCD_OutFix functions must use local variables with binding. Part b) Using PCB Artist (or hand drawn if you want), draw the hardware circuit diagram. The starter file for this class is called EE319K_DP512_Artist.sch and can be found at http://users.ece.utexas.edu/~valvano/Starterfiles/. You can check out a LCD display from the second floor lab. Please only check out one LCD per group. If you choose to interface in a manner different than Figure 5.1, have a TA approve your design. Build the interface using the circuit diagram. Please double check your connections before applying power. The LCD display will be used for Labs 5, 6, and 7, so do not dismantle the LCD interface until after Lab 7. You will have to return the LCD back to the second floor after Lab 7. If you wish to purchase your own LCD, the exact device is part number we are using is LCD-100 purchased at www.allelectronics.com. However, this software will work for virtually any LCD display with a HD44780 controller. Inexpensive LCD displays can also be purchased at www.bgmicro.com. Part c) This lab is sufficiently complex that it should be first debugged on the TExaS simulator. Although this LCD physically looks like 16 characters by 1 row, internally it is configured as 8 characters by 2 rows. To simulate this LCD in TExaS, we will define a 16 by 2 LCD. The first 8 characters of the first row of the TExaS LCD will map into the first 8 characters (left most) of the real LCD. The first 8 characters of the second row of the TExaS LCD will map into the second (right most) 8 characters of the real LCD. Even though we will not actually be connecting R/W to PAD0, we will attach R/W=PAD0 in TExaS, so that line will be simulated as a 0. The “Busy cleared after 37us/1.54ms” option allows you to test the timing aspect of the LCD interface (the blind cycle waits). Once the system is debugged on the simulator, download and debug it on the real 9S12. Students can borrow a LCD from the 2nd floor ECE lab checkout desk. You may want to checkout also a 10k or 20k pot to adjust the contrast, as shown as P2 in Figure 5.1. As always, please do not plug or unplug parts with the power on. If the system runs in the simulator, but not on the real board, check these things. 0) Check the wiring, pin 1, power, and ground. 1) Verify your real board software running (the heartbeat LED should be flashing). 2) There is a contrast potentiometer on LCD pin 3; try adjusting the pot to the middle of its range; 3) Try increasing the blind cycle delays; 4) You

Page 30: EE319K Laboratory Manual - Trillworks...Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 1 valvano@mail.utexas.edu 3/9/2010 EE319K Laboratory Manual Univ of Texas at Austin,

Page 30 Introduction to Embedded Systems: Interfacing to the Freescale 9S12

03/09/10

can single step through the LCD code (step over the delay functions) and look at the LCD signals with your voltmeter. Remember the 9S12 runs at 24 MHz in LOAD mode and 8 MHz in RUN mode. Please DON’T rely on information passed on by other students in the class; follow the instructions in the lab manual or consult the TAs if you have doubt.

Figure 5.2. One possible way to interface the LCD in TExaS. Demonstration (both partners must be present, and demonstration grades for partners may be different)

You will also be required to demonstrate the proper operation on the actual 9S12. During demonstration to the TA, you will run your system on the simulator and show the binding, allocation/initialization, access and deallocation of the local variables. Each time a function is called, an activation record is created on the stack, which includes parameters passed on the stack (none in this lab), the return address, and the local variables. You will be asked to create a stack window and identify the activation records created during the execution of LCD_OutDec. TAs may ask you questions on LCD interfacing, and programming. What is the difference between post and pre-increment modes of addressing? What do the E, RS and RW signal lines on the LCD signify? What does blind cycle synchronization mean in the context of communication with the LCD? Explain the voltage divider principle as it applies to the potentiometer used to adjust LCD contrast. The TA will ask to see your implementation local variables and ask you to explain the four step process (binding, allocation/initialization, access and deallocation). You should be able to draw stack pictures.

Deliverables 1) Two screen shots showing the system running in simulation mode (e.g., Welcome and 5432) 2) Circuit diagram, printout using PCB Artist with your name and date (or hand drawn if you want), 3) Assembly source code of your final program (device driver plus main program that tests the system) Hints 1) In simulation mode, you will get three warnings during LCD initialization “LCD hardware is 2-line, but software initialized it to 1 line”. You can ignore these warnings. 2) It will be important to pass data into your functions in Register D; this way you will be able to call your functions from C code later in Labs 6, 7 and 8.

Page 31: EE319K Laboratory Manual - Trillworks...Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 1 valvano@mail.utexas.edu 3/9/2010 EE319K Laboratory Manual Univ of Texas at Austin,

Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 31

[email protected] 3/9/2010

Lab 6. Real-Time Position Measurement System Preparation Read Sections 9.1, 9.2, 9.4, 9.6.1, 9.6.2, 11.1, 11.4, and 12.3.1 See OC example in TExaS See TUT3 example in TExaS Purpose

This lab has these major objectives: 1) an introduction to sampling analog signals using the ADC interface; 2) the development of an ADC device driver; 3) learning data conversion and calibration techniques; 4) the use of fixed-point numbers; 5) the development of an interrupt-driven real-time sampling device driver; and 6) the development of a software system involving a mixture of assembly and C. System Requirements You will design a position meter. Your software will use the 10-bit ADC. A linear slide potentiometer (Bourns SSHA20B20300) converts position into resistance (0 ≤ R ≤ 20 kΩ). The full scale range of position may be anywhere from 1.5 to 2 cm. You will use an electrical circuit to convert resistance into voltage (Vin). Since the potentiometer has three leads, one possible solution is shown in Figure 6.1. The 9S12 ADC will convert voltage into a 10-bit digital number (0 to 1023). Your software will calculate position from the ADC sample as a decimal fixed-point number. The position measurements will be displayed on the LCD using the LCD device driver developed in the last lab. A periodic interrupt will be used to establish the real-time sampling. The main program will be written in C and the I/O device drivers will be written in assembly language. The device drivers should be in separate files: lcd.asm, adc.asm, oc.asm, and pll.asm.

Figure 6.1. Possible circuit diagram of the sensor interface (use your ohmmeter on the sensor to find pin numbers 1,2,3). The left of Figure 6.2 shows the data flow graph of this system. Dividing the system into modules allows for concurrent development and eases the reuse of code. The right of Figure 6.2 shows the call graph.

PositionSensor

Voltage0 to +5V

ADChardware

ADCdriver

ATD0DR00 to 1023

OCISR

Sample0 to 1023

OChardware

LCDdisplay

LCDdriver

Position0 to 1.5 cm

main

Fixed-point0 to 1.500ASCII

Mailbox0 to 1023

main

OChardware

OC

LCDhardware

LCDdriver

ADChardware

ADCdriver

Figure 6.2. Data flow graph and call graph of the position meter system. You should make the position resolution and accuracy as good as possible. The position resolution is the smallest change in position that your system can reliably detect. In other words, if the resolution were 0.01 cm and the position were to change from 1.00 to 1.01 cm, then your device would be able to recognize the change. Resolution will depend on the

Page 32: EE319K Laboratory Manual - Trillworks...Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 1 valvano@mail.utexas.edu 3/9/2010 EE319K Laboratory Manual Univ of Texas at Austin,

Page 32 Introduction to Embedded Systems: Interfacing to the Freescale 9S12

03/09/10

amount of electrical noise, the number of ADC bits, and the resolution of the output display software. Considering just the errors due to the 10-bit ADC, we expect the resolution to be about 2cm/1024 or about 0.002 cm. Accuracy is defined as the absolute difference between the true position and the value measured by your device. Accuracy is dependent on the same parameters as resolution, but in addition it is also dependent on the stability of the transducer and the quality of the calibration procedure. Long-term drift, temperature dependence, and mechanical vibrations can also affect accuracy.

In this lab, you will be measuring the position of the armature (the movable part) on the slide potentiometer. Due to the mass of the armature and the friction between the armature and the frame, the position signal has a very low frequency response. We estimate the bandwidth of the position signal to range from 0 to 2 Hz. According to the Nyquist Theorem, we need a sampling rate greater than 4 Hz. Consequently, you will create a system with a sampling rate of 5 Hz. You will sample the ADC exactly every 0.2 sec and calculate position using decimal fixed-point with Δ of 0.001 cm. You should display the results on the LCD, including units. In general, when we design a system we choose a display resolution to match the expected measurement resolution. However in this case the expected measurement resolution is 0.002 cm, but the display resolution is 0.001 cm. This increased display resolution will make it easier to visualize hardware and software errors. An output compare interrupt will be used to establish the real-time periodic sampling.

Nyquist Theorem: If fmax is the largest frequency component of the analog signal, then you must sample more than twice fmax in order to faithfully represent the signal in the digital samples. For example, if the analog signal is A + B sin(2πft + φ) and the sampling rate is greater than 2f, you will be able to determine A, B, f, and φ from the digital samples. Valvano Postulate: If fmax is the largest frequency component of the analog signal, then you must sample more than ten times fmax in order for the reconstructed digital samples to look like the original signal to the human eye when plotted on a voltage versus time graph.

When a transducer is not linear, you could use a piece-wise linear interpolation to convert the ADC sample to position (Δ of 0.001 cm.) The 9S12 assembly language tbl and etbl instructions are efficient mechanisms to perform the interpolation. The etbl.RTF assembly program included with TExaS is an example of a piece-wise linear interpolation using the etbl instruction. In this example, there are two small tables Xtable and Ytable. The Xtable contains the ADC results and the Ytable contains the corresponding positions. The ADC sample is passed into the lookup function. This function first searches the Xtable for two adjacent of points that surround the current ADC sample. Next, the function uses the etbl instruction to perform a linear interpolation to find the position that corresponds to the ADC sample. You are free to implement the conversion in any acceptable manner, however the conversion will be written in C. The ADC converter on the 9S12 is a successive approximation device with a conversion time on the order of several μsec. You need to enable the ADC in ATD0CTL2. To enable the ADC, you will set ATD0CTL2=$80. You can define the number of ADC conversions (1 to 8) in a sequence using ATD0CTL3. For this lab, you will only need a single conversion, so you can set the control bits S8C S4C S2C S1C in ATD0CTL3 equal to 0001 respectively. In particular, you will set ATD0CTL3=$08. Bit 7 of ATD0CTL4 determines if the ADC operates with 8 bits or 10 bits. You will clear bit 7 to specify 10-bit precision. The remaining 7 bits of ATD0CTL4 specify the ADC clock, which will determine the time to perform an ADC conversion. If the 9S12DP512 were running at 8 MHz, you should set ATD0CTL4=$03. At this setting, the ADC will be clocked at 1 MHz, and the ADC conversion time will be equal to 14 μs. However, in this lab we will be running the 9S12DP512 at 24 MHz, therefore you could set ATD0CTL4=$05, the ADC will be clocked at 2 MHz, and the ADC conversion time will be equal to 7 μs. In summary, the ADC initialization should set ATD0CTL2=$80 turns on ADC ATD0CTL3=$08 specifies ADC sequence will perform one conversion ATD0CTL4=$05 specifies 10-bit mode, and 7us conversion time Writing to the ADC Control register (ATD0CTL5) begins a conversion. The ADC chip clocks itself. To perform a right-justified ADC conversion of channel 2, you should write a $82 to ATD0CTL5. After the first sample is complete, CCF0 is set and the result can be read out of the first result register, ATD0DR0. After the entire sequence has been converted, the SCF bit is set. In summary, the ADC conversion of channel 2 requires the following actions 1) ATD0CTL5=$82 starts the ADC, channel 2 2) Read ATD0STAT1 and look at bit 0 (CCF0) 3) Loop back to step 2 over and over until CCF0 is set (7us) 4) Read the 10-bit result in ATD0DR0

Page 33: EE319K Laboratory Manual - Trillworks...Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 1 valvano@mail.utexas.edu 3/9/2010 EE319K Laboratory Manual Univ of Texas at Austin,

Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 33

[email protected] 3/9/2010

Figure 6.3. Hardware setup for Lab 6, showing the LCD and slide pot. A 10 kΩ or 20 kΩ potentiometer shown on the protoboard is used to adjust the contrast of the LCD. Procedure The basic approach to this lab will be to first develop and debug your system in simulation mode. During this phase of the project you will use the TExaS simulator to observe your software operation. After the software is debugged, you will run your software on the real 9S12. The analog signal connected to the microcomputer comes from a position sensor, such that the analog voltage ranges from 0 to +5V as the position ranges from 0 to Pmax, where Pmax may be any value from 1.5 to 2 cm. First, you will use output compare interrupts to establish 5 Hz sampling. In particular, the ADC should be started exactly every 0.2 sec. Second, the OC ISR will store the 10-bit ADC sample in a global variable and set a flag. Read Section 12.3.1 in the book to see how a Mailbox can be used to pass data from the background into the foreground. Third, the main program will convert the ADC sample (0 to 1023) into a 16-bit unsigned decimal fixed-point number, with a ∆ of 0.001 cm. Lastly, you will use your LCD_OutFix function from the previous lab to display the sampled signal on the LCD. Include units on your display. Your main program will follow the sequence as shown in the flowchart of Figure 12.2 and timing in Figure 12.3 of the book. Part a) There are many ways to build a transducer. Your design will require cutting, gluing, and soldering, see Figure 6.3. You begin by Xerox-copying a metric ruler. Next, cut out a piece of wood, cardboard, or plastic a little larger than the potentiometer. Glue the frame (the fixed part) of the potentiometer to this solid object. Glue the metric ruler on the frame but near the armature (the movable part) of the sensor. Attach a hair-line to the armature, which will define the position measurement. Solder three solid wires to the slide potentiometer. If you do not know how to solder, ask your TA for a lesson. There are soldering stations at the proctor desk in ACA labs.

Please review safety procedures with your instructor, or TA. Please wash your hands after handling the lead solder, please solder in a well ventilated area, and if you drop the soldering iron let it fall to the ground (don’t try to catch it). If you are

pregnant, please do not solder.

Label these three wires +5 (Pin3), Vin (Pin2), and ground (Pin1), as shown in Figure 6.1. The potentiometer may have places where it is nonlinear. The full scale range may be any value from 1.5 to 2.0 cm, depending on your potentiometer.

Be careful when connecting the potentiometer to the computer, because if you mistakenly reverse two of the wires, you can cause a short from +5V to ground.

Part b) Create a Metrowerks project with a main program in main.c and four assembly modules as shown in Figure 6.4.

Page 34: EE319K Laboratory Manual - Trillworks...Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 1 valvano@mail.utexas.edu 3/9/2010 EE319K Laboratory Manual Univ of Texas at Austin,

Page 34 Introduction to Embedded Systems: Interfacing to the Freescale 9S12

03/09/10

Figure 6.4. Metrowerks project window. In the lcd.asm file you will place your LCD driver developed in to Lab 5. You should double-check the wait times in the LCD routines to make sure the blind cycle waits are valid for the 24 MHz clock.You will add absentry pseudo ops for all public functions within this driver. This will allow other modules to call these functions. E.g., absentry LCD_Open absentry LCD_OutChar absentry LCD_Clear absentry LCD_GoTo absentry LCD_OutDec absentry LCD_OutFix absentry LCD_OutString absentry Timer_Wait10ms

Place this code in the pll.asm. If you call PLL_Init the system runs at 24 MHz in both RUN and LOAD modes. SYNR equ $0034 ; CRG Synthesizer Register REFDV equ $0035 ; CRG Reference Divider Register CRGFLG equ $0037 ; CRG Flags Register CLKSEL equ $0039 ; CRG Clock Select Register PLLCTL equ $003A ; CRG PLL Control Register absentry PLL_Init ;********* PLL_Init **************** ; Active PLL so the 9S12 runs at 24 MHz, WARNING: can not single step this in Metrowerks ; Inputs: none ; Outputs: none ; Errors: will hang if PLL does not stabilize PLL_Init movb #$02,SYNR ; 9S12DP512 OSCCLK is 16 MHz movb #1,REFDV movb #0,CLKSEL ; PLLCLK = 2 * OSCCLK * (SYNR + 1) / (REFDV + 1) movb #$D1,PLLCTL ; Clock monitor, PLL On, high bandwidth filter brclr CRGFLG,#$08,* ; wait for PLLCLK to stabilize. bset CLKSEL,#$80 ; Switch to PLL clock rts In the adc.asm file you will place your ADC driver as decribed in part c). You will add absentry pseudo ops for all public functions within this driver. This will allow other modules to call these functions. E.g., absentry ADC_Init absentry ADC_In2

Page 35: EE319K Laboratory Manual - Trillworks...Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 1 valvano@mail.utexas.edu 3/9/2010 EE319K Laboratory Manual Univ of Texas at Austin,

Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 35

[email protected] 3/9/2010

In the oc.asm file you will place your output compare 0 driver as decribed in parts f) and g). You will add absentry and xdef pseudo ops for all public functions within this driver. This will allow other modules to call these functions. E.g., xdef ADCMail xdef ADCStatus absentry OC0_Init You will add xref pseudo ops to allow this file to access public functions of other drivers. E.g., xref ADC_Init xref ADC_In2 Part c) Write two assembly subroutines: ADC_Init will initialize the ADC interface and ADC_In2 will sample the ADC channel 2. Return the 10-bit result as a 16-bit number in Register D. Write main program number 1, which tests these two ADC subroutines. In this system, there is no LCD, and there are no interrupts. Simulation mode in TExaS simulates the slide pot, execute IO->Analog… In simulation mode, capture a screen shot showing the microcomputer and IO windows that demonstrate the ADC software is functioning properly. Next, debug this system on the real 9S12 to show the sensor and ADC are operational. The first main program will look something like unsigned short Data; void PLL_Init(void); void ADC_Init(void); unsigned short ADC_In2(void); void main(void){ PLL_Init(); // E clock is 24 MHz in both RUN and LOAD modes ADC_Init(); // turn on ADC asm cli // enable debugger for(;;){ Data = ADC_In2(); // sample 10-bit channel 2 } } Part d) Write main program number 2, which you can use to collect calibration data. In particular, this system should first sample the ADC and then display the results as unsigned decimal numbers. In this system, this no mailbox, and there are no interrupts. You should use your LCD_OutDec developed in the previous lab. Collect five to ten calibration points and create a table showing the true position (as determined by reading the position of the hair-line on the ruler), the analog input measured with a digital voltmeter and the ADC sample. The full scale range of your slide pot may be different from the others, which will affect the gain (voltage versus position slope). Where you attach the paper ruler will affect the offset. Do not use the data in Table 6.1. Rather, collect your own data like the first three columns of Table 6.1.

Position Analog input ADC sample Fixed-point Output 0.000 cm 0.261 V 58 0 0.600 cm 1.845 V 416 613 0.900 cm 2.664 V 578 893 1.100 cm 3.221 V 699 1102 1.400 cm 4.014 V 870 1398

Table 6.1. Calibration results of the conversion from ADC sample to fixed-point. The second main program will look something like unsigned short Data; void PLL_Init(void); void ADC_Init(void); unsigned short ADC_In2(void); void LCD_Open(void); void LCD_GoTo(unsigned short position); void LCD_Clear(void); void LCD_OutDec(unsigned short number); void main(void){ PLL_Init(); // E clock is 24 MHz in both RUN and LOAD modes ADC_Init(); // turn on ADC LCD_Open(); asm cli // enable debugger for(;;){ LCD_Clear(); // clear display Data = ADC_In2(); // sample 10-bit channel 2 LCD_OutDec(Data);

Page 36: EE319K Laboratory Manual - Trillworks...Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 1 valvano@mail.utexas.edu 3/9/2010 EE319K Laboratory Manual Univ of Texas at Austin,

Page 36 Introduction to Embedded Systems: Interfacing to the Freescale 9S12

03/09/10

Timer_Wait10ms(20); // wait about 200ms } } Part e) Use this calibration data to write a function in C that converts a 10-bit binary ADC sample into a 16-bit unsigned fixed-point number. The input parameter (10-bit ADC sample) to the function will be passed by value, and your function will return the result (integer portion of the fixed-point number). Table 6.1 shows some example results; this data is plotted on the right. You are allowed to use a linear equation to convert the ADC sample into the fixed-point number. For example,

Position = (constant1*Data)/constant2 + constant3; // DO NOT USE 1.7271 105.37, MEASURE YOUR OWN Please consider overflow and dropout during this conversion. The third main program will look something like unsigned short Data; // 10-bit ADC unsigned short Position; // 16-bit fixed-point 0.001 cm void PLL_Init(void); void ADC_Init(void); unsigned short ADC_In2(void); void LCD_Open(void); void LCD_GoTo(unsigned short position); void LCD_Clear(void); void LCD_OutString(char *pt); void LCD_OutDec(unsigned short number); void LCD_OutFix(unsigned short integerPart); void main(void){ PLL_Init(); // E clock is 24 MHz ADC_Init(); // turn on ADC LCD_Open(); LCD_Clear(); asm cli // enable debugger for(;;){ LCD_GoTo(0); // move to home Data = ADC_In2(); // sample 10-bit channel 2 Position = Convert(Data); // you write this C function LCD_OutFix(Position); Timer_Wait10ms(20); // wait about 200ms } } Part f) Write an assembly subroutine: OC0_Init will initialize the output compare system to interrupt at exactly 5 Hz (every 0.2 second). Use the simulator to test these functions. When debugging your code in TExaS it will be more convenient to run with a shorter OC interrupt period, e.g., 10 to 50ms. 1) disable interrupts to make the initialization atomic (set I bit in CCR) 2) enable the timer and an output compare channel, make PP7 an output (there is an LED on this pin) 3) arm output compare 4) specify when the first output compare interrupt will be 5) initialize the mailbox (clear its flag signifying no data is available) In general, one must enable interrupts (clear I bit in CCR) in order for OC interrupts to occur. It is good style however to finish all initializations, then enable interrupts from the high-level main program. In particular, you do not want the OC ISR to call ADC_In2 before the main program calls ADC_Init. Part g) Write an assembly output compare interrupt handler that samples the ADC and enters the data in the mailbox. Use the simulator to test these functions. Using the interrupt synchronization, the ADC will be sampled at almost equal time intervals1. The PP7 LED must be used for debugging, and the flicker rate will help you in estimate the sampling rate. The interrupt service routine performs these tasks 1) acknowledge the output compare interrupt by clearing the flag that requested the interrupt 2) specify the time for the next interrupt 3) toggle PP7 (change from 0 to 1, or from 1 to 0) 4) sample the ADC 5) save the 10-bit ADC sample into the mailbox ADCMail 6) set the mailbox flag ADCStatus to signify new data is available 7) return from interrupt 1 More precisely, the output compare flag is set at exact time intervals. There is some variability in when the ISR runs depending on which instruction is being executed at the time when the flag is set.

Calibration

y = 1.7271x - 105.37R2 = 0.9998

0

500

1000

1500

0 200 400 600 800 1000

ADC input

Dist

ance

in 0

.001

cm

Page 37: EE319K Laboratory Manual - Trillworks...Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 1 valvano@mail.utexas.edu 3/9/2010 EE319K Laboratory Manual Univ of Texas at Austin,

Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 37

[email protected] 3/9/2010

You can place the following code at the end of your oc.asm file. The org and fdb pseudo-ops create the output compare 0 interrupt vector, and the section pseudo-op, places subsequent code in the usual EEPROM locations org $FFEE fdb TC0handler ;output compare 0 interrupt vector EEPROM: section Part h) Write main program number 4, which initializes the PLL, timer, LCD, ADC and output compare interrupts. After initialization, this main program (foreground) performs these five tasks over and over. 1) wait for the mailbox flag ADCStatus to be true 2) read the 10-bit ADC sample from the mailbox ADCMail 3) clear the mailbox flag ADCStatus to signify the mailbox is now empty 4) convert the sample into a fixed-point number (integer part is 0 to 2000) 5) output the fixed-point number on the LCD Next debug this system on the real 9S12.

Figure 6.5. First debug the system in the simulator. Part i) Use the system to collect another five to ten data points, creating a table showing the true position (xti as determined by reading the position of the hair-line on the ruler), and measured position (xmi using your device). Calculate average accuracy by calculating the average difference between truth and measurement,

Average accuracy (with units in cm) = ∑=

−n

1imiti xx

n1

True position xti

Measured Position xmi

Error xti - xmi

Table 6.2. Accuracy results of the position measurement system.

Page 38: EE319K Laboratory Manual - Trillworks...Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 1 valvano@mail.utexas.edu 3/9/2010 EE319K Laboratory Manual Univ of Texas at Austin,

Page 38 Introduction to Embedded Systems: Interfacing to the Freescale 9S12

03/09/10

Demonstration You will show the TA your program operation on the actual 9S12 board. The TA may look at your data and expect

you to understand how the data was collected and how the ADC and interrupts work. You should be able to explain how the potentiometer converts distance into resistance, and how the circuit converts resistance into voltage. Also be prepared to explain how your software works and to discuss other ways the problem could have been solved. What will you change in your program if the potentiometer were to be connected to a different ADC pin? How would you have configured the ADC for 8-bit mode instead of 10-bit mode? How would this system be different if the units of measurement were inches instead of cm? What’s your sampling rate? What do you mean by sampling rate? What is the ADC range, resolution and precision? What does it mean that the ADC conversion time is 7μs? How and why is it set to 7μs? How do you initialize OC interrupt? How can you change your sampling rate? Be prepared to prove what the sampling rate is using a calculator and the manual. Explain how, when an interrupt occurs, control reaches the interrupt service routine. How would you change your program to use a different output compare channel. Why is it extremely poor style to output the converted data to the LCD inside the OC ISR? Where is the interrupt vector located? What are the differences between an interrupt and a subroutine? What will happen if you increase your sampling rate a lot? At what point do you think your program will crash? What is the Nyquist Theorem? How does it apply to this lab?

Deliverables 1) A screen shot showing the ADC test running in simulation mode (part c) 2) Circuit diagram showing the position sensor and LCD, using PCB Artist (or hand drawn if you want), 3) Calibration data, like the first three columns of Table 6.1 (part d) 4) Final version of main program 4 with LCD, OC, ADC and PLL (parts c, e, f, g and h) 5) Accuracy data and accuracy calculation, Table 6.2 Hints 1) Debug this lab in parts: first in simulation mode, then on the real 9S12. If you combine two working systems (e.g., ADC and LCD), you should retest the system. 2) There are some teaching videos showing you how to set up Metrowerks and how to simulate Metrowerks on TExaS. There are lots of details in this lab, please ask your instructor or your TA if you are confused. 3) Use your voltmeter to measure the voltage at the ADC input 4) A useful debugging monitor is to count the number of interrupts (to see if the interrupts are occurring) 5) When running on the real 9S12, you can not use either scanpoints or breakpoints effectively in a real-time system like this, because it takes too long to service a scanpoint or breakpoint (highly intrusive). However, you can dump strategic variables into memory and view that data in a memory window. When debugging using Metrowerks, you can right click a Data window and set the Mode to Periodical. This causes the debugger update the window periodically (e.g., once a second.) However, anytime the PC fetches information from the real board, your 9S12 software must halt while the data is being transferred. Thus, Periodical mode will affect the real-time sampling. 6) It takes a long time for the LCD to initialize. It would be better to allow the LCD to finish initialization before starting the OC interrupt sampling. One way to do this is to execute cli only after all initializations are complete. 7) In simulation mode, slowly click on the top of slide pot in the IO window to move it up one 10-bit ADC resolution, and double click on the top of it to move it up a lot. Clicking on the bottom of the pot moves it down. 8) The fourth column of Table 6.1 is the software output, assuming a linear fit between ADC and position.

Page 39: EE319K Laboratory Manual - Trillworks...Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 1 valvano@mail.utexas.edu 3/9/2010 EE319K Laboratory Manual Univ of Texas at Austin,

Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 39

[email protected] 3/9/2010

Lab 7. Distributed Data Acquisition System Preparation Operation of the SCI in Sections 8.1 and 12.4 Fifo queues in Section 12.3. Look at TUT2 TUT4 examples in TExaS Purpose The objectives of this lab are: 1) to learn how the SCI works; 2) to employ a FIFO queue to buffer data; and 3) to study synchronization issues in a distributed data acquisition system. System Requirements You will extend the system from Lab 6 to implement a distributed system, see Figure 7.1. In particular, one 9S12 will sample the data at 5 Hz and a second 9S12 will display the results on its LCD. Basically the hardware/software components from Lab 6 will be divided and distributed across two 9S12 microcontrollers. Figure 7.2 shows the data flow graph of the distributed data acquisition system. The sensor is attached to computer 1, and the ADC (ADC_In2 function) in computer 1 generates a digital value from 0 to 1023. The output compare periodic interrupt in computer 1 establishes the real-time sampling at 5 Hz. You will send data from computer 1 to computer 2 using asynchronous serial communication (SCI1). Busy-wait synchronization on TDRE must be used in computer 1, and RDRF interrupt synchronization must be used on computer 2. You can choose any baud rate you wish, as long as both computers use the same rate. Students can borrow a 4-pin cable from the 2nd floor ECE lab checkout desk to use to connect the SCI1 ports of two 9S12 boards.

Figure 7.1. The 9S12 on the left measures position and the one on the right displays the results. Option 1. One way to send the 10-bit sample is to break it into two parts and transmit it as two 8-bit bytes. For example, let b9b8b7b6b5b4b3b2b1b0 be a 10-bit sample. One possibility is to transmit two bytes 011b9b8b7b6b5 and 010b4b3b2b1b0. This way the receiver can combine the two bytes back into a 10-bit sample without mistakenly switching the most significant and least significant parts. Also notice that all transmissions are printable ASCII, so the two parts of the system can be separately debugged in TExaS. The time to transmit one bit is called the bit time, which is 1 divided by the baud rate. Every 200 ms, two bytes will be transferred (a total of 20 bits). Choose a baud rate so that the time to transmit 20 bits is short compared to 200 ms. This will guarantee that both the transmit data register and the transmit shift register will be empty at the time each OC ISR is executed. Therefore, calling SCI_OutChar twice (busy-wait synchronization) will not actually have to wait, because the first data will be moved immediately into the transmit shift register and the second data can be loaded into the transmit data register (to be transmitted after the first frame is finished). With this protocol if you lose a transmission, then the receiver should discard the extra byte. In this scheme, it does not matter which computer starts first. Option 2. An alternate scheme to transmit 10-bit data on an 8-bit channel is to encode the data as a signed 8-bit difference from the previous data. The receiver starts with a 16-bit 0, each 8-bit signed data received is promoted to 16-bit signed and added to the previous value. One flaw in this protocol is if you lose a transmission, then an error will exist in all

Page 40: EE319K Laboratory Manual - Trillworks...Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 1 valvano@mail.utexas.edu 3/9/2010 EE319K Laboratory Manual Univ of Texas at Austin,

Page 40 Introduction to Embedded Systems: Interfacing to the Freescale 9S12

03/09/10

subsequent samples. However since each 10-bit sample is transmitted as only one 10-bit frame, this protocol will be twice as fast as the previous. In particular, this protocol implements 2-1 data compression, but you need to start the receiver first. If you implement a scheme that requires 3 or more SCI transmissions per sample, then the busy-wait synchronization in the transmitter will actually have to wait. If you were transmitting on a network, the protocol might need to include the destination address. Similarly, if you wanted to transmit other types of data, the protocol might include data type. If the channel were noisy, then extra frames could be added to the message to detect and correct errors. None of the features in the paragraph are required in this lab.

Figure 7.2. The SCI1 port is simulated by attaching the TxD to PS3 and the RxD to PS2. The I/O will be displayed in hex.

PositionSensor

Voltage0 to +5V

ADChardware

ADCdriver

ATD0DR00 to 1023

OCISR

Sample0 to 1023

OChardware

LCDdisplay

LCDdriver

Fixed-point0 to 1.500

Position0 to 1.5 cm

SCI1driver

SCI1hardware

main

SCI1driver

SCI1hardware

Computer 1

Computer 2

Data0 to 255

Frame0 to 255

Frame0 to 255

FIFO

Frame0 to 255

Data0 to 1023

Figure 7.3. Data flows from the sensor through the two microcontrollers to the LCD. The output compare timer is used to trigger the real-time sampling. Use the special serial cable to connect the two SCI1 ports. An RDRF interrupt will occur in computer 2 for every SCI frame received. The FIFO queue is used to pass data from the RDRF interrupt service routine (background on computer 2) to the main program running in the foreground on computer 2. Every two SCI interrupts will cause one 10-bit ADC sample to be put into the FIFO. If the average rate at which the ISR puts data into the FIFO is slower than the rate at which data can be sent to the LCD, then the FIFO will never become full. The main program in computer 2 will output the position on its LCD. Figure 7.4 shows a possible call graph of the system. Dividing the system into modules allows for concurrent development and eases the reuse of code.

Page 41: EE319K Laboratory Manual - Trillworks...Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 1 valvano@mail.utexas.edu 3/9/2010 EE319K Laboratory Manual Univ of Texas at Austin,

Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 41

[email protected] 3/9/2010

main1

OChardware

OC

SCI1hardware

SCI1driver

ADChardware

ADCdriver

SCI1hardware

SCI1driver

LCDhardware

LCDdriver

FIFO

Computer 1 Computer 2main2

Figure 7.4. A call graph showing the modules used by the distributed data acquisition system.

Think about what the baud rate means and how it is used. Can you find a mathematical relationship between the ADC sampling rate (assuming the 10-bit data is transmitted in two frames) and the slowest baud rate possible for the transmission SCI? For example if I reduce the ADC is sampling rate, I can also reduce the baud rate of the transmission SCI. Think about how the baud rate for the receiver is selected. Is there an advantage to setting the baud rate of the receiver SCI faster or slower than the baud rate of the transmitter? Assume that FIFO’s are deep enough to not affect the decision.

Procedure Computer 1 software tasks Part a) Write an assembly subroutine: SCI1_Init that will initialize the SCI1 transmitter in computer 1. 1) enable SCI1 transmitter (no interrupts) 2) set the baud rate Part b) Write an assembly subroutine: SCI1_OutChar for computer 1 that sends one byte using busy-wait synchronization on TDRE. Place all the SCI routines in a separate sci1.asm file. 1) Wait for TDRE in SCI1SR1 to be 1 2) Write a byte to SCI1DRL Part c) Modify the output compare interrupt handler from Lab 6 so that it samples the ADC at 5 Hz and sends the data to the other computer using SCI. The interrupt service routine performs these tasks 1) acknowledge the output compare interrupt by clearing the flag that requested the interrupt 2) specify the time for the next interrupt 3) toggle PP7 (change from 0 to 1, or from 1 to 0), heartbeat 4) sample the ADC 5) send the 10-bit data to the other computer (calls SCI1_OutChar twice) 6) increment a Counter, used as debugging monitor of the number of ADC samples collected and SCI frames sent 7) return from interrupt Part d) Write the main program for computer 1, which initializes the PLL, timer, ADC, SCI1, PP7, output compare interrupts, and enables interrupts. Notice the call graph in Figure 7.3. In particular, the main will initialize output compare, and the output compare will initialize ADC and SCI1. After initialization, this transmitter main program (foreground) performs a do-nothing loop. The ADC sampling and SCI transmissions in computer 1 occur in the output compare interrupt service routine running in the background. Debug the system in simulation mode first. Figure 7.5 shows the transmitter being debugged in simulation mode. Notice the five representations of the position signal (physical location of the armature of the slide pot, the 3.4V on PAD2, the $02C3 in global variable ADCData, the two 10-bit SCI frames on PS3 and the two $76 $43 frames in the TheCRT.RTF window. Just like Lab 6, you can increase the sampling rate during simulation mode to make it easier to debug. In simulation mode, capture a screen shot, like Figure 7.5, showing the microcomputer, IO, scope and TheCRT.RTF windows that demonstrate the ADC, OC interrupt, and SCI routines are functioning properly.

Page 42: EE319K Laboratory Manual - Trillworks...Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 1 valvano@mail.utexas.edu 3/9/2010 EE319K Laboratory Manual Univ of Texas at Austin,

Page 42 Introduction to Embedded Systems: Interfacing to the Freescale 9S12

03/09/10

Figure 7.5 Example screen shot showing the transmitter system in simulation mode.

To debug the transmitter on the real 9S12, you can place the ADC sample and the interrupt counter in a Data window, and then configure the window to be periodically updated every 1 second, as shown in Figure 7.6. The interrupt Counter should increase by 5 every second, and the 10-bit ADC sample should respond to changes in the slide pot.

Figure 7.6. Example screen shot showing the transmitter system using the Metrowerks debugger. Computer 2 software tasks Part e) Design, implement and test a C language module implementing a statically allocated FIFO queue. Place the fifo code in a separate fifo.c file. Add a fifo.h file that includes the prototypes for the functions. The FIFOs in the Figure 12.10 and Program 12.4 operate on 8-bit data. However, you must put and get 16-bit words. In other words, every two SCI interrupts will cause one 16-bit data, containing the 10-bit ADC sample, to be put into the FIFO Allocate 4 words, meaning the FIFO will be able to hold up to 3 16-bit data. Use the simulator to test these functions. The software design steps are 1) Define the names of the functions, input/output parameters, and calling sequence. Type these definitions in as comments that exist at the top of the functions. 2) Write pseudo-code for the operations, see Figure 12.10. Type the sequences of operations as comments that exist within the bodies of the functions. 3) Write C code to handle the usual cases. I.e., at first, assume the FIFO is not full on a put, not empty on a get, and the pointers do not need to be wrapped. 4) Write a main program in C to test the FIFO operations. An example main program is listed below. The example test program assumes the FIFO can hold up to 3 elements. This main program has no SCI, no LCD and no interrupts. Simply make calls to the three FIFO routines and visualize the FIFO before, during and after the calls. Debug either in the TExaS or on Metrowerks. In this example, Put and Get return a true if successful, Put takes a call by value input, and Get takes a return by reference parameter. You are free to design the FIFO however you wish. 5) Iterate steps 3 and 4 adding code to handle the special cases.

Page 43: EE319K Laboratory Manual - Trillworks...Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 1 valvano@mail.utexas.edu 3/9/2010 EE319K Laboratory Manual Univ of Texas at Austin,

Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 43

[email protected] 3/9/2010

#include “fifo.h” int PutStatus[7]; // entries 3 and 6 should be false, others true int GetStatus[7]; // entries 0 and 6 should be false, others true unsigned short GetData[7]; // entries 1 2 3 4 5 should be 1 2 3 7 8 void main(void){ Fifo_Init(); // this assumes 4 elements allocated, max size is 3 asm cli // for debugger for(;;){ GetStatus[0] = Fifo_Get(&GetData[0]); // should fail, empty PutStatus[0] = Fifo_Put(1); // should succeed, 1 PutStatus[1] = Fifo_Put(2); // should succeed, 1 2 PutStatus[2] = Fifo_Put(3); // should succeed, 1 2 3 PutStatus[3] = Fifo_Put(4); // should fail, 1 2 3 full GetStatus[1] = Fifo_Get(&GetData[1]); // should succeed, 2 3 GetStatus[2] = Fifo_Get(&GetData[2]); // should succeed, 3 PutStatus[4] = Fifo_Put(7); // should succeed, 3 7 PutStatus[5] = Fifo_Put(8); // should succeed, 3 7 8 PutStatus[6] = Fifo_Put(9); // should fail, 3 7 8 full GetStatus[3] = Fifo_Get(&GetData[3]); // should succeed, 7 8 GetStatus[4] = Fifo_Get(&GetData[4]); // should succeed, 8 GetStatus[5] = Fifo_Get(&GetData[5]); // should succeed, empty GetStatus[6] = Fifo_Get(&GetData[6]); // should fail, empty } } The left side of Figure 7.7 shows the FIFO being debugged using TExaS in simulation mode, and the right side shows the debugging window in Metrowerks. You should let the program run multiple times through the loop.

Figure 7.7. Example screen shot showing the FIFO test program in TExaS and in Metrowerks. Part f) Write a subroutine: SCI1_Init that will initialize the SCI1 receiver in computer 2. 1) clear a global error count, initialize the 16-bit FIFO (calls Fifo_Init) 2) enable SCI1 receiver (arm interrupts for RDRF) 3) set the baud rate to match computer 1 In general, one must enable interrupts (clear I bit in CCR) in order for SCI1 interrupts to occur. It is good style however to finish all initializations, then enable interrupts from the high-level main program.

Page 44: EE319K Laboratory Manual - Trillworks...Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 1 valvano@mail.utexas.edu 3/9/2010 EE319K Laboratory Manual Univ of Texas at Austin,

Page 44 Introduction to Embedded Systems: Interfacing to the Freescale 9S12

03/09/10

Part g) Write a RDRF interrupt handler that receives data from the other computer and puts them into a FIFO queue. Every two SCI interrupts will place one 16-bit data into the FIFO. The number of lost samples will be maintained in the global error count. The interrupt service routine performs these tasks 1) acknowledge the interrupt by clearing the flag which requested the interrupt 2) read the data received from SCI1DRL If it is the high 5 bits 3a) store in a private global variable If it is the low 5 bits 3b) toggle PP7 (change from 0 to 1, or from 1 to 0) 4b) reconstruct 10-bit data and put it into the FIFO queue (calls C program Fifo_Put) 5b) increment a global error count if the FIFO fills up (but don’t loop back) 6b) increment a Counter, used as debugging monitor of the number of SCI frames received 7) return from interrupt Write an assembly subroutine: SCI1_InData for computer 2 that receives one 10-bit data (as a 16-bit parameter). Place all the SCI routines in a separate sci1.asm file. Place all the SCI1 routines in a separate sci1.asm file. This driver is similar to but not identical to the routines in computer 1. 1) Call Fifo_Get over and over until data is returned 2) Return the 16-bit data Part h) Design a main program for computer 2 that reads data from the FIFO, converts it to fixed-point, and displays the measurement using the same LCD routines developed in Lab 5 and used in Lab 6. The main program in this data acquisition system performs these tasks 1) initialize PLL, FIFO, LCD, PP7, SCI, and enable interrupts 2) calls SCI1_InData, which will wait until new data arrives 3) convert sample to fixed-point (same as Lab 6) 4) output the result as a fixed-point number (same as Lab 6) with units 5) repeat steps 2,3,4 over and over Debug the system in simulation mode first. Figure 7.8 shows the receiver being debugged in simulation mode. To simulate a SCI input, you simply type two hexadecimal codes into the TheCRT.RTF window each followed by the Enter key. Notice the four representations of the position signal (the $70,$40 typed in the TheCRT.RTF window, two 10-bit SCI frame on PS2, the 512 in the global variable Data, and the 0.779 cm displayed on the LCD. In simulation mode, capture a screen shot, like Figure 7.7, showing the microcomputer, IO, scope and TheCRT.RTF windows that demonstrate the SCI interrupt, the FIFO, and LCD the routines are functioning properly. (I had to halt the simulation in between typing in TheCRT.rtf window in order to get both SCI frames to be visable in one scope trace).

Figure 7.8. Example screen shot showing the receiver system in simulation mode.

Page 45: EE319K Laboratory Manual - Trillworks...Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 1 valvano@mail.utexas.edu 3/9/2010 EE319K Laboratory Manual Univ of Texas at Austin,

Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 45

[email protected] 3/9/2010

Figure 7.9. Example screen shots showing the transmitter on the left and the receiver on the right.

To debug the distributed system on the real 9S12, use two PC computers close enough together so you can connect the 9S12s with the special cable, yet run Metrowerks on both computers. You can place strategic variables (e.g., ADC sample, interrupt counter) in the Memory debugging windows on both PCs, and then configure the data to be periodically updated every 1 second as shown in Figure 7.9. If you start the receiver first, the two interrupt Count’s should be approximately equal, and the data on both computers should respond to changes in the slide pot. (5% extra credit) Part i) In this section you will estimate the maximum sampling rate. The limitation of computer 1 will be the time it takes to transmit 20 bits on the SCI. The limitation of computer 2 will be the time it takes to display one measurement on the LCD (e.g., if you move the LCD cursor rather than clearing the display, it will run faster). Change the output compare interrupt period in computer 1 so that it is close to but larger (slower) than the time for computer 1 to transmit one measurement and the time it takes computer 2 to display one measurement. Experimentally, verify the system can operate properly at this sampling rate (show the FIFO never gets full). Next, change the output compare sample period so that it is close to but smaller (faster) than these two times. Experimentally, determine want happens when you try to sample too fast (it doesn’t work, explain what happens and why). Without actually doing it, describe two changes to the system you could do so that the sampling rate could be increased beyond this limit. Hint: changing the size of the FIFO will not affect the maximum sampling rate. Demonstration

You will show the TA your program operation on the two 9S12 boards. Also be prepared to explain how your software works and to discuss other ways the problem could have been solved. How do you initialize SCI? How do you input and output using SCI? What is the difference between busy-wait and interrupt synchronization? What synchronization method does the transmitter SCI use? What synchronization method does the receiver SCI use? What sets RDRF (TDRE) and when is it set? What clears RDRF (TDRE) and when is it cleared? What does PLL do? Why is the PLL used? There is a FIFO in this system. There are lots of FIFO code in the book and on the web that you are free to use, but you are responsible for knowing how the FIFO works. What does it mean if the FIFO is full? Empty? What should your system do if the FIFO is full when it calls PUT? Why? What should your system do if the FIFO is empty when it calls GET? Why? Deliverables 1) A screen shot showing the ADC, ViewBox, and SCI output running in simulation mode (part d), like Figure 7.5 2) Two circuit diagrams: one for computer 1 and one for computer 2. The position sensor is connected to computer 1 and the LCD is connected to computer 2. 3) A screen shot showing the SCI interrupts, and LCD output running in simulation mode (part h), like Figure 7.8 4) Final versions of the software in the two computers Warnings: You can not single step PLL code in Metrowerks because the debugger modifies the registers you are trying to set. It will crash. You can not single step SCI code in Metrowerks because the debugger steals your data. In particular, any software that accesses with a read or write to either SCI1DRL or SCI1SR1 can not be single-stepped in Metrowerks. If you do, data will be lost. Remember SCI1DRL is two registers at the same address. This entry can not be observed properly in either the TExaS or the Metrowerks debugger.

Page 46: EE319K Laboratory Manual - Trillworks...Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 1 valvano@mail.utexas.edu 3/9/2010 EE319K Laboratory Manual Univ of Texas at Austin,

Page 46 Introduction to Embedded Systems: Interfacing to the Freescale 9S12

03/09/10

Figure 7.10. Physical drawing of the Tech Arts Adapt9S12DP512 board.. Notice in Figure 7.10 that SCI0 is the 9-pin DB9 connector (J4 on the board) we attach to the PC for debugging, and that SCI1 is the 4-pin connector right above it (labeled J2 on the board). We use a special cable to connect the 4-pin RS232 SCI1 ports between the two computers (see Figure 7.1). This cable can be borrowed from the 2nd floor ECE lab checkout desk. You will need to return this cable and the LCD after Lab 7 is complete. 9S12 Computer 1 9S12 Computer 2 1 RxD ------ black ------------------------- yellow ------ 3 TxD 2 Ground -- green ------------------------- green ------- 2 Ground 3 TxD ----- yellow ------------------------ black ------- 1 RxD 4 NC 4 NC If you wished to connect SCI1 to a personal computer, you could build this cable. You would need a 4-pin female header (All Electronics part number CON-244) and a 9-pin female DP9 header (All Electronic part number DB-9S). Three wires must be connected in the cable, they are: 9S12 J2 COM port on a PC 1 RxD ------------------------------------------ 3 TxD 2 Ground -------------------------------------- 5 Ground 3 TxD ------------------------------------------ 2 RxD Hints 1) Place the ISR vectors at the end of the file containing the ISR. This lab uses SCI1. The SCI1 interrupt vector is located at $FFD4. The examples in the book and in TUT4 use SCI0, which has its vector at $FFD6. 2) In simulation mode, slowly click on the top of slide pot once in the IO window to move it up one 10-bit ADC resolution, and double click on the top of it to move it up a lot. Clicking on the bottom of the pot moved it down. 3) Double check you are downloading the transmitter software onto the 9S12 with the position sensor (left computer in Figure 7.1) and the receiver software onto the 9S12 with the LCD (right computer in Figure 7.1). Please return the LCD and serial cable when you are finished with Lab 7. If you do not return either of these two items we will drop your overall grade in EE319K one letter grade.

Page 47: EE319K Laboratory Manual - Trillworks...Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 1 valvano@mail.utexas.edu 3/9/2010 EE319K Laboratory Manual Univ of Texas at Austin,

Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 47

[email protected] 3/9/2010

Lab 8. Digital Piano using a Digital to Analog Converter Preparation Read Sections 11.1, 11.2, and 11.3, starter file OC_DP512.zip

Download http://users.ece.utexas.edu/~valvano/Starterfiles/Dac.xls Purpose There are three objectives for this lab: 1) to learn about DAC conversion; 2) to understand how digital data stored in a computer could be used to represent sounds and music; 3) to study how the DAC can be used to create sounds. System Requirements Most digital music devices rely on high-speed DAC converters to create the analog waveforms required to produce high-quality sound. In this lab you will create a very simple sound generation system that illustrates this application of the DAC. Your goal is to create an embedded system that plays three notes (a digital piano with three keys). The first step is to design and test a 4-bit DAC, which converts 4 bits of digital output from the 9S12 to an analog signal. You are free to design your DAC with a precision more than 4 bits. You will convert the binary bits (digital) to an analog output using a simple resistor network. During the static testing phase, you will connect the DAC analog output to your voltmeter and measure resolution, range, precision and accuracy. During the dynamic testing phase you will connect the DAC output to headphones, and listen to sounds created by your software. It doesn’t matter what range the DAC is, as long as there is an approximately linear relationship between the digital data and the speaker current. The performance score of this lab is not based on loudness, but sound quality. The quality of the music will depend on both hardware and software factors. The precision of the DAC, external noise and the dynamic range of the speaker are some of the hardware factors. Software factors include the DAC output rate and the complexity of the stored sound data. You can create a 3k resistor from two 1.5k resistors. You can create a 6k resistor from two 12k resistors,

6812bit3

bit2

bit1

bit0

statictesting

Voutvoltmeter

I out

speaker

6812bit3

bit2

bit1

bit0

dynamictesting

Figure 8.1. DAC allows the software to create music.

The second step is to design a low-level device driver for the DAC. Remember, the goal of a device driver is to separate what the device does (general descriptions of DAC_Init and DAC_Out) from how it works (implementations of DAC_Init and DAC_Out). The third step is to design a low-level device driver for the three keys of the piano. For example, if you could create public functions Piano_Init and Piano_In, where Piano_In returns a logical key code for the pattern of keys that are pressed. You may design this driver however you wish, but the goal is to abstract the details how it works (which port, which pin) from what it does (which key pressed). The fourth step is to organize the sound generation software into a device driver. You will need a data structure to store the sound waveform. You are free to design your own format, as long as it uses a formal data structure. Compressed data occupies less storage, but requires runtime calculation. Although you will be playing only three notes, the design should allow additional notes to be added with minimal effort. For example, if you could create public functions Sound_Init and Sound_Play(note), where the parameter note specifies the frequency (pitch) of the sound. For example, calling Sound_Play(Off) makes it silent and calling Sound_Play(C) plays the note C. A background thread within the sound driver implemented with output compare will fetch data out of your music structure and send them to the DAC. The last step is to write a main program that links the modules together creating the digital piano.

The loudness of the tone is determined by the amplitude of the wave, and the pitch is defined as the frequency of the wave, as shown in Figure 8.2. Table 8.1 contains frequency values for the notes in one octave.

Page 48: EE319K Laboratory Manual - Trillworks...Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 1 valvano@mail.utexas.edu 3/9/2010 EE319K Laboratory Manual Univ of Texas at Austin,

Page 48 Introduction to Embedded Systems: Interfacing to the Freescale 9S12

03/09/10

period

loudness

pitch = 1/period

Figure 8.2. Definition of loudness and pitch. If you output a sequence of numbers to the DAC that form a sine wave, then you will hear a continuous tone on the speaker, as shown in Figure 8.3. The measured data was collected using a 4-bit DAC with a range of 0 to +5 V. The plot on the left was measured with a digital scope (without the speaker attached). The plot on the left shows the frequency response of this data, plotting amplitude (in dB) versus frequency (in kHz). This measured waveform is approximately 2.7+2.3sin(2π440 t) volts. The two peaks in the spectrum are at DC and 440 Hz. Notice that the magnitude of DC component is 20*log(2.7) or about 9 dB and the magnitude of the 440 Hz component is 20*log(2.3) or about 7 dB.

ms0.0 1.0 2.0 3.0 4.0 5.0

V

-5-4-3-2-1012345

23Dec2006 10:18

kHz

0.0 0.5 1.0 1.5 2.0 2.5 3.0

-50-40-30-20-10

01020

23Dec2006 10:18

Figure 8.3. A 440Hz sine wave generates a pure tone with note A. The plot on the right is the Fourier Transform(frequency spectrum dB versus kHz) of the recorded data plotted on the left.

Note frequency C 523 Hz B 494 Hz Bb 466 Hz A 440 Hz Ab 415 Hz G 392 Hz Gb 370 Hz F 349 Hz E 330 Hz Eb 311 Hz D 294 Hz Db 277 Hz C 262 Hz

Table 8.1. Fundamental frequencies of standard musical notes. The frequency for ‘A’ is exact. The frequency of each note can be calculated by multiplying the previous frequency by12 2 . You can use this method to determine the frequencies of additional notes above and below the ones in Table 8.1. There are twelve notes in an octave, therefore moving up one octave doubles the frequency. Figure 8.4 illustrates the concept of instrument. You can define the type of sound by the shape of the voltage versus time waveform. Brass instruments have a very large first harmonic frequency.

Page 49: EE319K Laboratory Manual - Trillworks...Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 1 valvano@mail.utexas.edu 3/9/2010 EE319K Laboratory Manual Univ of Texas at Austin,

Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 49

[email protected] 3/9/2010

period

Figure 8.4. A waveform shape that generates a trumpet sound. The tempo of the music defines the speed of the song. In 2/4 3/4 or 4/4 music, a beat is defined as a quarter note. A moderate tempo is 120 beats/min, which means a quarter note has a duration of ½ second. A sequence of notes can be separated by pauses (silences) so that each note is heard separately. The envelope of the note defines the amplitude versus time. A very simple envelope is illustrated in Figure 8.5. The 9S12 has plenty of processing power to create these types of waves.

330 Hz 523 Hz

0.5s 0.5s 1.0s

330 Hz

Figure 8.5. You can control the amplitude, frequency and duration of each note (not drawn to scale). The smooth-shaped envelope, as illustrated in Figure 8.6, causes a less staccato and more melodic sound. This type of sound generation may be difficult to produce in real-time on the 9S12. You do not need to create envelopes in this lab.

330 Hz330 Hz 523 Hz

0.5s 0.5s 1.0s

Figure 8.6. The amplitude of a plucked string drops exponentially in time. A chord is created by playing multiple notes simultaneously. When two piano keys are struck simultaneously both notes are created, and the sounds are mixed arithmetically. You can create the same effect by adding two waves together in software, before sending the wave to the DAC. Figure 8.7 plots the mathematical addition of a 262 Hz (low C) and a 392 Hz sine wave (G), creating a simple chord. You do not need to create chords in this lab assignment.

-2

-1

0

1

2

0 0.005 0.01 0.015 0.02Time (sec)

Soun

d A

mpl

itude

Figure 8.7. A simple chord mixing the notes C and G.

Page 50: EE319K Laboratory Manual - Trillworks...Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 1 valvano@mail.utexas.edu 3/9/2010 EE319K Laboratory Manual Univ of Texas at Austin,

Page 50 Introduction to Embedded Systems: Interfacing to the Freescale 9S12

03/09/10

Different from Labs 6 and 7, you must write the entire code in C. In addition, if you perform the extra credit, it too should be implemented in C. Procedure Part a) Draw the circuit required to interface the DAC to the 9S12. Design the DAC converter using a simple resistor-adding technique. Use resistors in a 1/2/4/8 resistance ratio. Select values in the 1.5 kΩ to 12 kΩ range. For example, you could use 1.5 kΩ, 3 kΩ, 6 kΩ, and 12 kΩ. Notice that you could create double/half resistance values by placing identical resistors in series/parallel. It is a good idea to email your design to your TA and have him/her verify your design before you build it. You can solder 24 gauge solid wires to the jack to simplify connecting your circuit to the headphones. You should ground pin 1 on the headphone jack, and connect the DAC output to either pin 2 or pin 3. Sound will therefore be heard on one channel of the headphones. Draw interface circuits for three switches, which will be used for the piano keyboard.

Figure 8.8. A bottom-view mechanical drawing of the stereo jack (connect pin 1 to ground and pin 3 to the DAC output). Part b) Write the C language device driver for the DAC interface. Include at least two functions that implement the DAC interface. For example, you could implement the function DAC_Init() to initialize the DAC, and the function DAC_Out to send a new data value to the DAC. Place all code that accesses the DAC in a separate DAC.c code file. Add a DAC.h header file with the prototypes for public functions. Part c) Begin with the static testing of the DAC. You will write a simple main program to test the DAC. You are free to debug this system however you wish, but you must debug this module separately. You could initially debug your software in TExaS using the DC motor I/O device. This module allows you to connect a DAC to an output port. You can select the precision of the DAC (4 bits in this case). You can visualize the generated waveform on the scope by selecting the D/A output. Figure 8.9 shows the TExaS dialog to interface the DAC to PP3,2,1,0. You can single step this program, comparing digital Data to the analog voltage at the Vout without the speaker attached (i.e., left side of Figure 8.1). #include "DAC.h" unsigned char Data; // 0 to 15 DAC otput void main(void) { PLL_Init(); DAC_Init(); EnableInterrupts; for(;;) { DAC_Out(Data); Data = 0x0F&(Data+1); } }

Page 51: EE319K Laboratory Manual - Trillworks...Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 1 valvano@mail.utexas.edu 3/9/2010 EE319K Laboratory Manual Univ of Texas at Austin,

Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 51

[email protected] 3/9/2010

Using Ohm's law and fact that the digital output voltages will be approximately 0 and 5 V, make a table of the theoretical DAC voltage and as a function of digital value (without the speaker attached). Calculate resolution, range, precision and accuracy. Complete Table 8.2 and attach it as a deliverable.

Bit3 bit2 bit1 bit0 Theoretical DAC voltage Measured DAC voltage 0

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

Table 8.2. Static performance evaluation of the DAC.

Figure 8.9. Use the DC motor feature to simulate a simple DAC (you must connect the tachometer input to an unused ADC pin, even though you are not using the tachometer).

Page 52: EE319K Laboratory Manual - Trillworks...Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 1 valvano@mail.utexas.edu 3/9/2010 EE319K Laboratory Manual Univ of Texas at Austin,

Page 52 Introduction to Embedded Systems: Interfacing to the Freescale 9S12

03/09/10

Figure 8.10 shows the static testing of the DAC module using TExaS. In this phase of the testing there are no timer functions, and no interrupts. You can use Step and StepOver to debug the system statically.

Figure 8.10. A screen shot in simulation mode showing the static testing of the DAC. Part d) Design and write the piano keyboard device driver software. These routines facilitate the use of the three piano keys. Include at least two functions that implement the piano keyboard interface. For example, you could implement the function Piano_Init() to initialize the switch inputs, and the function Piano_In that returns a logical key code for the pattern of switches that are pressed. Place all code that directly accesses the three switches in a separate Piano.c code file. Add a Piano.h header file with the prototypes for public functions. Figure 8.10 shows the three switches connected to PP4 PP5 and PP6, but you are free to interface them to any I/O pins. Part e) Design and write the sound device driver software. The input to the sound driver is the pitch of the note to play. Output compare interrupts will be used to set the time in between outputs to the DAC. Add minimally intrusive debugging instruments to allow you to visualize when interrupts are being processed. Include at least two functions that implement the sound output. For example, you could implement the function Sound_Init() to initialize the data structures, calls DAC_Init, and initializes the output compare interrupt. You could implement a function Sound_Play(note) that starts sound output at the specified pitch. Place all code that implements the waveform generation in a separate Sound.c code file. Add a Sound.h header file with the prototypes for public functions. Figure 8.11 shows a sine wave generated by a 4-bit DAC simulated in TExaS.

Figure 8.11. The 4-bit DAC is used to create a sin wave using TExaS. Part f) Write a main program to implement the three-key piano. Make PP7 a heartbeat. Document clearly the operation of the routines. Figure 8.12 shows a possible data flow graph of the music player. Debug the system either in TExaS or using the real 9S12 with an oscilloscope. Either capture a screen shot (like Figure 8.11) or use the print screen feature of the real oscilloscope to capture the waveform generated by your digital piano. When no buttons are pressed, the output will be quiet. When Button 1 is pressed, output a sine wave at one frequency. When Button 2 is pressed, output a sine wave at a second

Page 53: EE319K Laboratory Manual - Trillworks...Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 1 valvano@mail.utexas.edu 3/9/2010 EE319K Laboratory Manual Univ of Texas at Austin,

Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 53

[email protected] 3/9/2010

frequency. When Button 3 is pressed, output a sine wave at a third frequency. Only one button will be pressed at a time. The sound lasts until the button is released.

Pianointerface

Soundinterface

DACinterfacemainPush

buttonsDAC

hardware

Sin waveTable

Figure 8.12. Data flows from the memory and the switches to the speaker. Figure 8.13 shows a possible call graph of the system. The call graph on the right is one possible way to implement the extra credit. Dividing the system into modules allows for concurrent development and eases the reuse of code.

main

Sounddriver

Switchhardware

Pianodriver

Speakerhardware

DACdriver

OChardware

main

Sounddriver

Switchhardware

Pianodriver

Speakerhardware

DACdriver

OChardware

Musicdriver

Figure 8.13. A call graph showing the three modules used by the music player. Demonstration

You should be able to demonstrate the three notes. Be prepared to explain how your software works. You should be prepared to discuss alternative approaches and be able to justify your solution. The TA may look at your data and expect you to understand how the data was collected and how DAC works. In particular, you should be able to design a DAC with 5 to 10 bits. What is the range, resolution and precision? You will tell the TA what frequency you are trying to generate, and they may check the accuracy with a frequency meter or scope. TAs may ask you what frequency it is supposed to be, then ask you to prove it using calculations. Just having three different sounding waves is not enough, you must demonstrate the frequency is proper and it is a sinewave (at least as good as you can get with a 4-bit DAC). To check it is a sine wave you can run it on the simulator and attach a DAC and scope (Figure 8.10), or you could use a real oscilloscope. Many students come for their checkout with systems that did not operate properly. You may be asked OC interrupt and DAC questions. If the desired frequency is f, and there are n samples in the sine wave table, what OC interrupt period would you use.

This lab mentions 32 samples per cycle. Increasing the DAC output rate and the number of points in the table is one way of smoothing out the “steps” that in the DAC output waveform. If we increase the number of samples from 32 to 64 to 128 and so on, keeping the DAC precision at 4-bit, will we keep getting a corresponding increase in quality of the DAC output waveform? Deliverables 1) Circuit diagram showing the DAC and any other hardware used in this lab, PCB Artist (or hand drawn)

2) Software Design Draw pictures of the data structures used to store the sound data If you organized the system different than Figure 8.12 and 8.13, then draw its data flow and call graphs 3) A screen shot showing the IO and scope running in simulation mode (part f) like Figure 8.11, or a printout generated from data collected using a real oscilloscope, like Figure 8.3.

4) Measurement Data Show the theoretical response of DAC voltage versus digital value (part c, Table 8.2) Show the experimental response of DAC voltage versus digital value (part c, Table 8.2) Calculate resolution, range, precision and accuracy 5) Final version of the music playing software (intermediate testing software is not required)

Page 54: EE319K Laboratory Manual - Trillworks...Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 1 valvano@mail.utexas.edu 3/9/2010 EE319K Laboratory Manual Univ of Texas at Austin,

Page 54 Introduction to Embedded Systems: Interfacing to the Freescale 9S12

03/09/10

Extra Credit. Extend the system so that is plays your favorite song (a sequence of notes, set at a specific tempo and includes an envelop like Figure 8.5). Your goal is to play your favorite song. It doesn’t matter how long the song is; what matters is the organization is well-done using appropriate data structures that is easy to understand and easy to adapt for other songs. One possible approach is to use two output compare interrupts. A fast output compare ISR outputs the sinewave to the DAC (Figures 8.3, 8.11). The rate of this interrupt is set to specify the frequency (pitch) of the sound. A second slow output compare ISR occurs at the tempo of the music. For example, if the song has just quarter notes at 120, then this interrupt occurs every 500 ms. If the song has eight notes, quarter notes and half notes, then this interrupt occurs at 250, 500, 1000 ms respectively. During this second ISR, the frequency of the first ISR is modified according to the note that is to be played next. Compressed data occupies less storage, but requires runtime calculation. On the other hand, a complete list of points will be simpler to process, but requires more storage than is available on the 9S12. The fourth step is to organize the music software into a device driver. Although you will be playing only one song, the song data itself will be stored in the main program, and the device driver will perform all the I/O and interrupts to make it happen. You will need public functions Play and Stop, which perform operations like a cassette tape player. The Play function has an input parameter that defines the song to play. If you complete the extra credit (with input switches that can be used to play and stop), then the three-key piano functionality still must be completed. In other words, the extra credit part is in addition to the regular part. You interface more switches (which you can get from checkout) or you could use combinations of 2 or 3 switches to activate the Play and Stop operations

Some web links about music Simple Music Theory http://library.thinkquest.org/15413/theory/theory.htm Free sheet music http://www.8notes.com/piano/

Figure 8.14. A song being played with a harmony and melody (see two peaks in the spectrum)..

Page 55: EE319K Laboratory Manual - Trillworks...Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 1 valvano@mail.utexas.edu 3/9/2010 EE319K Laboratory Manual Univ of Texas at Austin,

Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 55

[email protected] 3/9/2010

Lab 9. TExaS Robots 1.84 Preparation, for the latest information, check http://users.ece.utexas.edu/~valvano/EE319K TRobots ("TExaS-Robots") is a 9S12 programming competition. Unlike arcade type games that require human inputs controlling some object, all strategy in TRobots must be complete before the actual game begins. Game strategy is condensed into a 9S12 program that you design and write. Your software controls a robot tank, see Figure 1, whose mission is to seek out, track, and destroy other robots, each running a different program. Each robot is equally equipped, and from 2 to 50 robots may compete at one time. As a game is simulated, events are displayed graphically in real-time. Multiple simulations will be run in order to eliminate the random occurrences, and the best programmers will be crowned as the team with the largest total score.

Figure 1. Robots have two tracks and one cannon mounted on a turret. TRobots consists of multiple 9S12-based virtual robots, and a battlefield display. The TRobots programs can be created by any 9S12 assembler or compiler, and the machine codes (S19 records) are run by the TRobots simulator. The robot programs are run in parallel, giving each robot the same number of 9S12 bus cycles. The virtual robot includes hardware features to scan for opponents, move, turn, fire cannons, position sensing, and direction sensing. After the 9S12 programs are assembled/compiled, the S19 records are loaded into separate robots. Robots moving, missiles flying and exploding, and status information are displayed on the screen in real-time during the battle.

512

1023

256

768

y

0 512 1023256 768x

N

SEW

Figure 2. The battlefield is a 1024 by 1024 meter square. North is up.

The battlefield, as shown in Figure 2, has a wall surrounds the perimeter, so that a robot running into the wall will incur damage and loose points. There is an option that causes the tank to bounce off the wall upon a collision. This semester in EE319K, the wall-bounce option will not be enabled. The tank however will bounce off other tanks. The lower left corner has the coordinates x = 0, y = 0; the upper right corner has the coordinates x = 1023 m, y = 1023 m. The four life-packs are at various places; look in the logFile.txt file to see their exact locations in ADC units. The life-packs are about 50 meters by 50 meters. The maximum health is 100%.

Page 56: EE319K Laboratory Manual - Trillworks...Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 1 valvano@mail.utexas.edu 3/9/2010 EE319K Laboratory Manual Univ of Texas at Austin,

Page 56 Introduction to Embedded Systems: Interfacing to the Freescale 9S12

03/09/10

Robots are represented on the field by two characters of their S19 object code files, which must be one letter A to Z followed by one digit 0 to 3. The S19 files (extension .s19 or .sx) must be loaded into the S19 directory, which must be a subdirectory of the directory that holds the game engine, TRobots.exe. The number of robots in the competition is determined by the existence of object code files: A0.s19, B0.s19, C0.s19, D0.s19, … Z0.s19, A1.s19, B1.s19… Z3.s19, which are located in the S19 directory. For collision purposes, each robot has a bounding-box that is about 4 meters wide, 5 meters long, and 3 meters high as shown in Figure 3. Robot positions are reported as the center of the box, which is the center of rotation if one track is moved forward, while the other track is moved backwards. The robot heading is the direction of the left and right tracks, defined as degrees North of East. The turret heading is relative to the robot. E.g., a turret heading of 0 means the turret is facing in the same direction as the tank.

Figure 3. There are two headings of interest. In this picture, the robot heading is about 340º, and the turret heading is about 45º. The offensive weapon is the cannon, which is mounted on a rotating turret. Missiles are fired in the direction of the turret. Transmitting a frame out the serial port fires a missile. The data value sent determines the launch angle of the missile, thus affecting the firing distance. There are an unlimited number of missiles that can be fired, but because of the serial baud rate, there is a maximum rate at which the cannon can be fired. Since the turret can rotate independently from the robot direction, it can fire any direction, regardless of robot heading. The scanner is a laser ranging device that scans in three sectors (front, left, and right). The scanner is located on the gun turret, therefore senses enemy robots in the same direction as missiles will be fired. The scanner has four possible sensing angles, as shown in Table 1 and Figure 4, controlled by the two bits PM5 and PM4. The left/front/right directions are relative to the turret. The values returned by the 10-bit ADC are binary fixed-point with a distance resolution of 0.25 m.

PM5 PM4 Resolution Left Scanner Front Scanner Right Scanner 0 0 5o +7.5o to +2.5o +2.5o to -2.5o -7.5o to -2.5o 0 1 10o +15o to +5o +5o to -5o -5o to -15o 1 0 30o +45o to +15o +15o to -15o -15o to -45o 1 1 120o +180o to +60o +60o to -60o -60o to -180o

Table 1. You can set dynamically set the scanner sensing angles.

Figure 4. There are four possible sensing angles for the scanner. The front is aligned with the turret (not to scale).

3 0o

f r ont

l e ft right

12 0o

f r o n t

l e f t r i g h t

10o

front

left right

5 o front

l e f t r i g ht

Page 57: EE319K Laboratory Manual - Trillworks...Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 1 valvano@mail.utexas.edu 3/9/2010 EE319K Laboratory Manual Univ of Texas at Austin,

Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 57

[email protected] 3/9/2010

There are three stepper motors that control the robot. One stepper motor controls the left track, and a second stepper motor controls the right track. These two motors cause the robot to turn or move. A third stepper motor rotates the gun turret. Each stepper interface requires four output bits from the computer. The motors can be independently stepped forwards using a full-step sequence (5,6,10,9,...) or a half-step sequence (5,4,6,2,10,8,9,1,...). Forward stepping causes the robot to move forward. The motors can be also be stepped backwards using a full-step sequence (9,10,6,5,...) or a half-step sequence (1,9,8,10,2,6,4,5,...). Backward stepping causes the robot to move backward. The robot will turn about its center (without translation) if one track is stepped forward and the other is stepped backward. Each motor has 5 possible motions (full-step forward, half-step forward, none, half-step backward and full-step backward.) Since each motor is independent, there are 25 possible robot motions. The smallest distance that the robot can be moved is 0.125 meter. The smallest angle that the robot can rotate is 1.5o. In the following figures, the gray arrows represent the robot position and heading before the command, and the black arrow shows the net motion caused by the command. The gray circle is the center of the robot before the command. The command notation describes the left and right stepper actions, as listed in Table 2. For example, (F,h) means make the left motor move a full step forward at the same time as making the right motor move a half step backward.

Code Stepper motor action F full step forward H half step forward 0 no change on this stepper h half step backward f full step backward

Table 2. There are five possible stepper motor actions. The legal actions are shown in Figure 5. For example, if the four-bit stepper output is currently 10, and you change it to 6, then the motor will perform a full-step backwards, shown as bold in the figure. Be careful when mixing full-step and half-step commands. For example, changing the stepper output from 1 to 8 is illegal. Outputting illegal stepper commands will cause robot damage. For example, writing 0 (%0000) is an illegal operation.

H H H H H H HH

5 4 6 2 10 8 9 1

h h h h h h h h

F F F F

f f ff

Figure 5. A state graph showing the legal stepper motor actions. The first four commands are simple translations, without rotation, as shown in Figure 6.

(H,H) (F,F) (h,h) (f,f)

Figure 6. To move the robot in a straight line step both motors together in the same direction.

Page 58: EE319K Laboratory Manual - Trillworks...Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 1 valvano@mail.utexas.edu 3/9/2010 EE319K Laboratory Manual Univ of Texas at Austin,

Page 58 Introduction to Embedded Systems: Interfacing to the Freescale 9S12

03/09/10

The second four commands are simple rotations, without translation, as shown in Figure 7. A counter-clockwise (CCW) rotation adds to the robot compass heading, while a clockwise (CW) rotation decreases the value of the heading. A collision is possible after a pure rotation because the simulation checks for overlapping volumes. The four full-step motions listed in Table 3 are sufficient to develop a good TRobot solution.

(F,f) (H,h) (f,F) (h,H)

Figure 7. To rotate the robot step the track motors in opposite directions.

Command Left track Right track Δθ (ο) Δx (m) Robot motion (F,F) full-step forward full-step forward 0 0.5 forward (f,f) full-step backward full-step backward 0 -0.5 backward (F,f) full-step forward full-step backward -6 0 turn CW (f,F) full-step backward full-step forward 6 0 CCW

Table 3. These four full-step commands are sufficient to move the robot. It takes 15 (F,f) commands to turn the robot 90ο. The four half-step motions are listed in Table 4. It takes 30 (H,h) commands to turn the robot 90ο.

Command Left track Right track Δθ (ο) Δx (m) Robot motion (H,H) half-step forward half-step forward 0 0.25 little forward (h,h) half-step backward half-step backward 0 -0.25 little backward (H,h) half-step forward half-step backward -3 0 little CW (h,H) half-step backward half-step forward 3 0 little CCW

Table 4. The half-step commands provide finer control of the robot. There are a total of sixteen commands that cause a combined rotation and translation. Figure 8 shows four of these more complex movements. The white circle is the pivot point of a motion that involves both a translation and a rotation. The combined motions are listed in Table 5. The simulation first rotates the robot by the amount shown in Table 4, then it translates robot in the direction of the new heading.

(H,0)

pivot

(F,0) (F,h) (H,f)

Figure 8. Four of the sixteen commands that result in both a rotation and a translation.

Page 59: EE319K Laboratory Manual - Trillworks...Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 1 valvano@mail.utexas.edu 3/9/2010 EE319K Laboratory Manual Univ of Texas at Austin,

Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 59

[email protected] 3/9/2010

Command Left track Right track Δθ (ο) Δx (m) Robot motion (F,h) full-step forward half-step backward -4.5 0.125 tiny forward, CW (H,f) half-step forward full-step backward -4.5 -0.125 tiny back, CW (h,F) half-step backward full-step forward 4.5 0.125 tiny forward, CCW (f,H) full-step backward half-step forward 4.5 -0.125 tiny back, CCW (F,H) full-step forward half-step forward -1.5 0.325 little forward, little CW (H,F) half-step forward full-step forward 1.5 0.325 little forward, little CCW (f,h) full-step backward half-step backward 1.5 -0.325 little back, little CCW (h,f) half-step backward full-step backward -1.5 -0.325 little back, little CW (F,0) full-step forward none -3 0.25 turn CW about right (0,F) none full-step forward 3 0.25 turn CCW about left (f,0) full-step backward none 3 -0.25 turn CCW about right (0,f) none full-step backward -3 -0.25 turn CW about left (H,0) half-step forward none -1.5 0.125 little CW about right (0,H) none half-step forward 1.5 0.125 little CCW about left (h,0) half-step backward none 1.5 -0.125 little CCW about right (0,h) none half-step backward -1.5 -0.125 little CW about left

Table 5. There are sixteen commands that result in both a rotation and a translation. A third stepper motor controls the angle of the gun turret. Forward steps rotate the turret CCW, while backward steps rotate the turret CW, as shown in Figure 9 and Table 6. The turret angle is relative the robot heading. The absolute turret angle is the sum of the robot heading and the turret angle.

(F) (H) (f) (h)

Figure 9. A third stepper motor independently controls the turret angle. It takes 36 (F) commands to rotate the turret a complete 360 o

Command Stepper motor action Change in turret angle (F) full step forward +10o (H) half step forward +5o (h) half step backward -5o (f) full step backward -10o

Table 6. The third stepper controls the turret angle. Analog status parameters provide feedback to your software, indicating results of the sensors and scanners. The status of your robot includes the percent damage, the location on the battlefield, the heading of the robot, and the heading of the gun turret. There are three laser range scanners to determine the distance to the closest enemy robot. These sensors and scanners are interfaced to the ADC. A robot is considered dead when the health drops to 0%. A collision occurs when the bounding boxes of two objects overlap. Damage to health is inflicted as follows:

1% - collision caused by another robot running into you. 5% - collision into another robot or into a wall. 10% - a missile hitting your robot. 10% - a software bug or illegal stepper output.

Robot-robot collisions will cause the two robots to bounce, changing directions after the impact. This semester, we will run with the mode that a robot hitting a wall will not bounce. Damage is cumulative; however, a robot does not loose any

Page 60: EE319K Laboratory Manual - Trillworks...Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 1 valvano@mail.utexas.edu 3/9/2010 EE319K Laboratory Manual Univ of Texas at Austin,

Page 60 Introduction to Embedded Systems: Interfacing to the Freescale 9S12

03/09/10

mobility, or fire potential at high damage levels. In other words, a robot at 1% health performs equally well as a robot with no damage. There are four life-packs (circular targets) in the battlefield. Rolling over the pack grants you a 50% increase in health, but each pack may be used only once per run. The maximum health is 100%. The life-pack triggers are 50m by 50m squares. For purposes of the competition, a score is maintained, separate from the health 20 point bonus when one of your missiles hits other robot (and bonus points for shooting a missile that kills a tank) 1 point penalty for launching a missile 5 point penalty when your robot is hit by a missile 5 point penalty when your robot has a collision. There are bonus points for staying alive for the entire battle (see the Trobot.ini file for details) A robot-robot collision causes both robots to loose points, but the robot initiating contact looses more health. Analog sensors connected to 9S12DP512 PAD0 to PAD7 The numbers in parentheses are 10-bit right-justified ADC values. Channel 0: Current x-position of the center of robot (the pivot point). Near 0V (0) means the robot hit the West wall. Near 5V (1023) means the robot hit the East wall. See Figure 2. Available in both TExaS and TRobots. Channel 1: Current y-position of the center of robot (the pivot point). Near 0V (0) means the robot hit the South wall. Near 5V (1023) means the robot hit the North wall. See Figure 2. Available in both TExaS and TRobots. Channel 2: Current compass heading of the robot. The compass system is oriented so that due East (right) is 0V, 1.25V (256) is North, 2.5V (512) is West, 3.75V (768) is South. Just a little bit South of East is 5V (1023). See Figure 10. Available in both TExaS and TRobots. Channel 3: Current heading of the turret/cannon relative to the robot. The heading is defined so that straight ahead (same direction as the robot is 0V, 1.25V (256) is to the left, 2.5V (512) is directly behind, 3.75V (768) is to the right. Just a tiny bit to the right is 5V (1023). Available only in TRobots. Channel 4: Results of the left scanner is the range to closest enemy robot within a cone-shaped volume to the left of the canon. 5V (1023) means no enemy robot within 256 meters. 2.5V (512) means 128 meters to the enemy robot. Available only in TRobots. Channel 5: Results of the front scanner is the range to closest enemy robot within a cone-shaped volume in the direction of cannon turret heading. 5V (1023) means no enemy robot within 256 meters. 2.5V (512) means 128 meters to the enemy robot. Available only in TRobots. Channel 6: Results of the right scanner is the range to closest enemy robot within a cone-shaped volume to the right of the canon. 5V (1023) means no enemy robot within 256 meters. 2.5V (512) means 128 meters to the enemy robot. Available only in TRobots. Channel 7: Current robot damage. 5V (1023) means full life and 0V (0) means dead. Available only in TRobots. It is possible to sample all 8 sensors with one 9S12 command using 8-channel sequence length and multiple channel mode. However, the continuous ADC sampling mode is not supported. 384 256 128 \ | / \ | / 512 --- x --- 0 / | \ / | \ 640 768 896 Figure 10. Compass directions are measured in degrees North of East. Two Stepper Motors Control Robot Motion PT7-PT4 Right Track Stepper Motor PT3-PT0 Left Track Stepper Motor Sensor Resolution PM5-PM4 00,01,10,11 is 5, 10, 30, 120 degrees respectively

Page 61: EE319K Laboratory Manual - Trillworks...Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 1 valvano@mail.utexas.edu 3/9/2010 EE319K Laboratory Manual Univ of Texas at Austin,

Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 61

[email protected] 3/9/2010

Turret Control PM3-PM0 Gun Turret Direction Stepper Motor Gun Control PS1 serial port, send a serial output frame to shoot a missile (horizontal speed set in Trobot.ini file) baud rate (see Trobot.ini file), 1 start, 8-bit data, 1 stop frame protocol 8-bit data specifies the missile vertical speed 0 to 255, (50 for hitting tanks close in, 255 for far away) Each semester we change the missile speed, which affects the missile firing distance. Let Distance be the distance to target from sensor. Let Fire be the value sent to the SCI_OutChar. I suggest you experiment with the factor in the following equation. Luckily, the perfect value for factor is not necessary. Fire = factor*Distance Programming limitations The 9S12DP512 memory map and the following list of I/O ports are simulated. RTI and eight output compare interrupts are allowed; other interrupts are not allowed. The E clock is 25 MHz and cannot be changed. DDRM: equ $0252 ; Port M Data Direction Register 6 bits DDRT: equ $0242 ; Port T Data Direction Register PTM: equ $0250 ; Port M I/O Register 6 bits PTT: equ $0240 ; Port T I/O Register TIOS: equ $0040 ; Timer Input Capture/Output Compare Select TCNT: equ $0044 ; Timer Count Register TSCR1: equ $0046 ; set bit 7=1 to enable TCNT TFLG1: equ $004E ; Main Timer Interrupt Flag 1 TIE: equ $004C ; Timer Interrupt Enable Register TC0: equ $0050 ; Timer Output Compare Register 0 TC1: equ $0052 ; Timer Output Compare Register 1 TC2: equ $0054 ; Timer Output Compare Register 2 TC3: equ $0056 ; Timer Output Compare Register 3 TC4: equ $0058 ; Timer Output Compare Register 4 TC5: equ $005A ; Timer Output Compare Register 5 TC6: equ $005C ; Timer Output Compare Register 6 TC7: equ $005E ; Timer Output Compare Register 7 SCI0BD: equ $00C8 ; 16-bit SCI0 Baud Rate Register SCI0CR2: equ $00CB ; SCI0 Control Register 2 SCI0DRL: equ $00CF ; SCI0 Data Register Low SCI0SR1: equ $00CC ; SCI0 Status Register 1 ATD0CTL0: equ $0080 ; ATD0 Control Register 0 ATD0CTL1: equ $0081 ; ATD0 Control Register 1 ATD0CTL2: equ $0082 ; ATD0 Control Register 2 no interrupts, no fast clear ATD0CTL3: equ $0083 ; ATD0 Control Register 3 ATD0CTL4: equ $0084 ; ATD0 Control Register 4 ATD0CTL5: equ $0085 ; ATD0 Control Register 5 no SCAN mode ATD0DR0: equ $0090 ; ATD0 Conversion Result Register 0 ATD0DR1: equ $0092 ; ATD0 Conversion Result Register 1 ATD0DR2: equ $0094 ; ATD0 Conversion Result Register 2 ATD0DR3: equ $0096 ; ATD0 Conversion Result Register 3 ATD0DR4: equ $0098 ; ATD0 Conversion Result Register 4 ATD0DR5: equ $009A ; ATD0 Conversion Result Register 5 ATD0DR6: equ $009C ; ATD0 Conversion Result Register 6 ATD0DR7: equ $009E ; ATD0 Conversion Result Register 7 ATD0STAT0: equ $0086 ; ATD0 Status Register 0 ATD0STAT1: equ $008B ; ATD0 Status Register 1 Enhanced 9S12DP512 Memory map Internal RAM $0800-$3FFF ; 14 KiB globals and stack Internal RAM $3800-$3807 ; debug RAM (visible on battle screen) Shared RAM $8000-$BFFF ; 16 KiB shared space with other robots (not active) Internal EEPROM $4000-$7FFF,$C000-$FFFF ; 32 KiB for constants and program

Page 62: EE319K Laboratory Manual - Trillworks...Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 1 valvano@mail.utexas.edu 3/9/2010 EE319K Laboratory Manual Univ of Texas at Austin,

Page 62 Introduction to Embedded Systems: Interfacing to the Freescale 9S12

03/09/10

Stack overflow and stack underflow will cause memory errors. The PLL loop can not be altered to change the bus cycle time. Table 7 shows the complete list of 9S12 simulation faults (bugs in your software) that can occur. Each fault will cause a 10% loss of health. 10 op code failure 11 Port E is read only 12 PORTAD is read only 13 ADR's are read only 14 ATD0STAT is input only 15 ATD0CTL2 bits 6-1 are not implemented 16 ATD0CTL3 FIFO mode is not implemented 17 ATD0CTL5 scan mode not implemented 18 SCI0BDH bits 7,6,5 not implemented 19 Only SCI0CR1=0 mode implemented 20 TCIE, ILIE, RWU, SBK not implemented 21 SCI0SR1 is read only 22 SCI0SR2 is read only 23 SCI 9-bit data mode not implemented 24 SCI receiver not implemented 25 Track stepper motor fault 26 Turret stepper motor fault 27 Lost data, write to TDR when TE=0 28 Lost data, write to TDR when TDRE=0 29 Read from unimplemented I/O port 30 Write to unimplemented I/O 31 Read from uninitialized RAM 32 Read from uninitialized External RAM 33 Read from unprogrammed EEPROM 34 Read from unprogrammed ROM 35 Read from undefined address 36 Write to EEPROM 37 Write to ROM 38 Write to undefined address 39 Executed unimplemented opcode 40 Executed unimplemented indexed mode 41 SCI baud rate mismatch 42 TCNT is read only 43 Tank is outputting to the track steppers too fast. Table 7. Each time of these program errors occur there will be a 10% loss of health.

Esc Menu Space Pause/Resume Arrow keys Camera Position PageUp PageDown Camera Angle F1 Help F5 Change Screen Resolution F6 Screenshot F7 Toggle camera mode F8 Switch to next player F12 Toggle sound/music F11 Abort this run, and start another run F10 Exit

Table 8. Hot keys available during TRobot simulation.

Page 63: EE319K Laboratory Manual - Trillworks...Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 1 valvano@mail.utexas.edu 3/9/2010 EE319K Laboratory Manual Univ of Texas at Austin,

Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 63

[email protected] 3/9/2010

Purpose of Lab The overall goal of Lab 9 is to combine the various programming and interface components learned in this class into

one embedded system. The problem is complex enough that a successful solution will require organizational skills. In particular, there may be low-level tasks such as moving, turning, sensing and firing. There may be mid-level tasks such a risk-assessment, fighting and fleeing. The overall game strategy is obviously a high-level task. The strategy involves accumulating the most points while battling against your classmates. You will program this all in C or a mixture of C and assembly language. Procedure Part a) Download the latest version of TRobots. Find a computer with DirectX 9.0c or later, unzip the package and test the system. You can determine the DirectX version by executing DxDiag from the command line. Initially you can compile in Metrowerks and simulate in TExaS. After initial debugging you will use the TRobot simulator to run the battle.

http://users.ece.utexas.edu/~valvano/EE319K There are two S19 folders in the TRobot directory; the folder named S19 will be used in the competition, and the folder named Lab9S19 will be used only for initial testing. Double click the TRobots.exe application and watch an example battle typical of what will happen in the competition. Quit TRobots and exchange the folder names S19 and Lab9S19, and run TRobots again. Tank B0 is not very smart. Quit TRobots and open the four files (B0.uc, B0.io, and B0.plt) in TExaS. Compile the project in Metrowerks, copy the sx file into the S19 folder and run the system within TExaS. You should observe the same stupid behavior of the tank as you saw in TRobots. Part b) Form a group. You may work alone, or in a group of two. Email your TAs the names of all group members. You do not have to have the same TA but you do have to have the same professor. They will email you back a code name, which will consist of one letter (A-Z) followed by one number (0,1,2,3). For example, if you are team X1, you will create your solution as Metrowerks project X1. Your object code will be renamed X1.sx. Part c) You may begin development and testing with your tank and one just other tank, running completely within TExaS. The other tank will not move and will be placed out of the way in a corner. You will write commands that allow the tank to move forward, backward, turn CW and turn CCW with as fast a speed as allowed by the TRobot simulator. All outputs to the PTT stepper must occur in the background using interrupts. You will write a main program that initializes the system and demonstrates the ability of your low level software to execute the four low-level movements. Don’t write the software as one complex operation, but design it in such a way to execute individual movement and turning commands. Each of the four commands will take a parameter (e.g., forward 10 steps, turn CW 90 degrees), but you are free to implement any syntax/format for the parameter as you wish. There is an example (Trobot_9S12DP512) that will run completely within TExaS. Rename this project to match your team name. Do your development in stages (e.g., first sensing, then turning, and finally moving). For each stage, perform your initial development and debugging within TExaS. When you have pieces of code that work in the TExaS simulator, test them again in the TRobot environment. Observe the registers and memory locations $3800-$3807, using the stop breakpoint to test and debug your program within TRobots. It is not necessary to demonstrate this initial testing. In other words, this entire procedural step is optional. Part d) Program submission. Lab 9 submissions for all EE319K are due by 10pm Tuesday 5/4. You must zip your Metrowerks project and upload it to Blackboard. For example, if you are team X1, then name your project X1. Make sure it compiles in Metrowerks. Please upload just one version. Great confusion and sadness will occur if you submit two copies of your program. Part e) Final Contest The contests for the MWF2 class will be Wednesday 5/5 and the contest for the TTh2 and TTh3:30 classes will be Thursday 5/6: Note: there will be about the same number robots in the battlefield. The grading scale for Lab9 is as follows 100 >50% scoring rank and software has good structure and style. 90 >50% scoring rank and software has poor style. 85 25-50% scoring rank and software has good structure and style. 75 25-50% scoring rank and software has poor style. 75 0-25% scoring rank and software has good structure and style. 50 0-25% scoring rank and software has poor style. The Trobot.ini file allows you to change many parameters of the battle. The parameters are grouped into three categories. The first category simply affect on-screen displays and have no effect on the actual battle conditions. The student is free to adjust these parameters however they wish. The tanks are numbered A0,B0,C0… For example, Player=27; specifies the chase camera follows tank B1. The camera view can be adjusted during the game, but the Camera parameter specifies the initial view. The Show parameters determine whether or not that particular variable is visible on the screen during battle. There are two fonts available for the display. BigFont=1 is appropriate for the in-class competition, however BigFont=0

Page 64: EE319K Laboratory Manual - Trillworks...Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 1 valvano@mail.utexas.edu 3/9/2010 EE319K Laboratory Manual Univ of Texas at Austin,

Page 64 Introduction to Embedded Systems: Interfacing to the Freescale 9S12

03/09/10

is appropriate for debugging on your personal computer. If you set your tank to the player, then the simulation will halt every time your software executes a stop instruction. You can restart simulation by pressing the space bar. During the competition, all initial positions will be random, and no tank will be allowed to stop the simulation. These first few line illustrate how to explicitly set the initial position of tanks C0 and B0 // To explicitly position a tank, set both StartX and StartY between 50 to 973. Player=2; // Tank C0 StartX=128; // starting X position of C0, in map units 0 to 1023 StartY=256; // starting Y position of C0, in map units 0 to 1023 StartDir=512; // starting tank direction, 256=90deg, 512=180deg, 768=270deg StartTurret=256; // starting turret direction, 256=90deg, 512=180deg, 768=270deg // Since they are not specified, StartDir and StartTurret will be zero. Player=1; // Tank B0 is has cameras attached StartX=507; // starting position of B0 StartY=507; Camera=4; // 5=panoramic spin, 4=manual, 2=orbit player, 0=1st person ShowX=1; ShowY=1; ShowDir=1; ShowTurret=1; ShowLeft=0; ShowCenter=1; ShowRight=0; ShowHealth=1; ShowPC=1; ShowRegX=1; ShowRegY=1; Show3800=1; Show3802=1; Show3804=1; Show3806=1; ShowScore=1; BigFont=0; // 0 is little font, 1 for large green font PauseBetweenGames=0; // execute all simulations without pausing StopWillPause=1; // executing stop will pause for the Player Tank CreateLogFile=1; // save results in logFile.txt The second set of parameters will be determined by the instructor, but you can adjust these parameters during initial debugging for your convenience. However, the values of these parameters will be set by the instructor. NumberOfBattles=16; // competition consists of 16 battles BattleTime=200; // each battle runs for 200 ms simulation time

This third set of parameters is determined by the instructors of the course and should not be modified by the student. One parameter the instructor can modify is the MissileSpeed. The missile speed affects both the speed and range of a missile. A nonzero value stored into the parameter MinStepTime forces the tank to wait in between outputs to the track stepper motors. If the tank tries to move too fast, it will throw “43” errors and loose 10% health for each violation (motors burn up). A MinStepTime value of 0 means there is no speed limit. The BaudRate specifies the SCI baud rate, thus it determines the maximum rate at which the tank can fire. You should output to both track steppers simultaneously, because after writing to PTT, you have to wait another MinStepTime cycles before you can write to PTT again. Refer to the actual Trobot.ini for the exact parameters to be used this semester. WallBounce=0; // tanks do not bounce off walls MissileSpeed=30; // initial velocity of missiles (5 to 100) MinStepTime=300; // minimum bus cycles between outputs to track steppers BaudRate=20000; // SCI rate in bits/sec

Page 65: EE319K Laboratory Manual - Trillworks...Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 1 valvano@mail.utexas.edu 3/9/2010 EE319K Laboratory Manual Univ of Texas at Austin,

Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 65

[email protected] 3/9/2010

How to develop C programs Metrowerks/Tech Arts 9S12DP512 board First, you need to install Metrowerks CodeWarrior for HC(S)12. You can go to http://users.ece.utexas.edu/~valvano/S12C32.htm for directions on how to download and install Metrowerks. Download instructions and starter projects from my web site at http://users.ece.utexas.edu/~valvano/metrowerks/

A) To open an existing Metrowerks project 1) Start Metrowerks CW12 2) Execute File->Open, navigate to an existing *.mcp file, and click "OK" 3) Skip part B), go to part c)

B) How to configure create a new Metrowerks project 1) Start Metrowerks CW12 2) Execute File->New, click "Project" Tab

select "HC(S)12 New Project Wizard" specify the "Project name" verify its "Location", click "OK"

3) Select the derivative you want to use “MC9S12DP512”, click "Next"

4) Choose the set of languages supported select "C", click "Next"

Page 66: EE319K Laboratory Manual - Trillworks...Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 1 valvano@mail.utexas.edu 3/9/2010 EE319K Laboratory Manual Univ of Texas at Austin,

Page 66 Introduction to Embedded Systems: Interfacing to the Freescale 9S12

03/09/10

5) Do you want to create a setup for Processor Expert select "No", click "Next"

6) Select the OSEKturbo operating system select "No", click "Next"

7) Do you want to create a setup for PC-lint select "No", click "Next"

8) Select the startup code select "ANSI", click "Next"

9) Select the floating point format supported select "None", click "Next"

10) Which memory model should be used? select "Small" click "Next"

Page 67: EE319K Laboratory Manual - Trillworks...Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 1 valvano@mail.utexas.edu 3/9/2010 EE319K Laboratory Manual Univ of Texas at Austin,

Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 67

[email protected] 3/9/2010

11) Please choose the connections you want select "HCS12 Serial Monitor" click "Finish"

12) Left click datapage.c, (you do not need it) right click and select “Remove”

Metrowerks adds the file datapage.c, which is not needed. So, this file can be deleted from the project. 13) Create or copy program files *.c and *.h, place them into the "Sources" directory of your project

14) Add the necessary C files to project click on Sources in the "mcp" window, right click and execute "Add Files..." “click dot on” in the field associated all C source files under the "bug" icon 15) Change compiler/linker options click the right-most toolbar ICON called "Simulator settings" click "Compiler for HC12" choice click "Options" click "Output" tab select "Allocate CONST objects in ROM" and "Generate Listing File"

Page 68: EE319K Laboratory Manual - Trillworks...Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 1 valvano@mail.utexas.edu 3/9/2010 EE319K Laboratory Manual Univ of Texas at Austin,

Page 68 Introduction to Embedded Systems: Interfacing to the Freescale 9S12

03/09/10

click "Assembler for HC12" choice click "Options" click "Output" tab select "Generate a listing file"

click "Linker for HC12" choice click "Options" click "Output" tab select "Generate S-Record" and "Generate a map file"

C) How to run Metrowerks C code on the Real 9S12DP512 board

Do this once 1) Connect PC-COM1 to the 9S12DP512 DB9 connector, 2) Place the Run/Load switch on the 9S12DP512 board in LOAD mode 3) Connect power to 9S12DP512 board using the wall wart that came with the kit. 4) Touch the reset switch on the 9S12DP512 board

Page 69: EE319K Laboratory Manual - Trillworks...Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 1 valvano@mail.utexas.edu 3/9/2010 EE319K Laboratory Manual Univ of Texas at Austin,

Jonathan W. Valvano EE319K Spring 2010 Lab Manual Page 69

[email protected] 3/9/2010

For each edit/compile/run cycle for software that does not use SCI0 1) In Metrowerks, perform editing to source code 2) In Metrowerks, compile/Link/Load Execute Project->Debug 3) Click the green arrow in the debugger to start. Runs at 24 MHz. You can use SCI1 normally, like all other I/O. For each edit/compile/run cycle for software that does use SCI0 1) set the Run/Load switch to LOAD mode, push the reset button on the 9S12DP512 board 2) execute Project->Debug (compiles and downloads code to 9S12DP512) 3) quit MW debugger after programming is complete. Quitting the debugger will release the COM port. 4) start a terminal program (like HyperTerminal) specify proper COM port, no flow control, match the baud rate of your 9S12 software 5) set the Run/Load switch to RUN mode and push the reset button on the 9S12DP512 board.

The 9S12DP512 runs at 8 MHz if you do not modify the PLL. You can adjust the E clock rate by configuring the PLL, SCI baud rate is affected by the PLL. If the E clock frequency is EClk, and n is the least significant 13 bits of SCI0BD, then the baud rate is BaudRate = Eclk/16/n

6) when done, quit terminal program. Quitting the terminal program will release the COM port. To run in embedded mode 1) disconnect the serial cable if not needed 2) set the Run/Load switch to RUN mode, 3) apply power to the 9S12DP512 board

The 9S12DP512 runs at 8 MHz if you do not modify the PLL. You can adjust the E clock rate by configuring the PLL

Execute the function PLL_Init as shown in the book to execute at 24 MHz in both Run and LOAD modes.

9S12DP512

25

50

26

1

PAD11

PA3

PA0

PA6PA5PA4

PA1

PB7PB6PB5PB4PB3

PB0

PB2

PA7

PA2

PB1

PAD10PAD9PAD8

PE2PE4

PE1PE3

PJ1

PAD14

PK4

PK1PK0PJ0PJ7PJ6PM7PM6PM5

PK3

PK5PK7PE7Gnd +5

PK2

PAD15

PM3PM4

PAD13PAD12

PM2

PM0PM1

H29S12DP512

25

50

26

1

PAD3

PS1

PT5

PS5PS6PS7

PT6

PT4PT3PT2PT1PT0

PP5

PP7

PS4

PT7

PP6

PAD2PAD1PAD0

PP4PP3

PP1PP2

PP0

PAD6

PE0

PH0PH1PH2PH3PH4PH5PH6PH7

Reset*

PE1+5PS0GndGnd

PE7

PAD7

PE4PS2

PAD5PAD4

PS3

VRHVRL

H19S12DP512

25

50

26

1

AN03

TxD0

PT5

MOSISckSS*

PT6

PT4PT3PT2PT1PT0

PP5

PP7

MISO

PT7

PP6

AN02AN01AN00

PP4PP3

PP1PP2

PP0

AN06

XIRQ*

PH0PH1PH2PH3PH4PH5PH6PH7

Reset*

IRQ*+5RxD0GndGnd

PE7

AN07

EclkRxD1

AN05AN04

TxD1

VRHVRL

H19S12DP512

25

50

26

1

AN11

AD11

AD8

AD14AD13AD12

AD9

AD7AD6AD5AD4AD3

AD0

AD2

AD15

AD10

AD1

AN10AN09AN08

R/WEclk

IRQ*LSTRB*

PJ1

AN14

XA18

XA15XA14PJ0SCLSDAPM7PM6PM5

XA17

XA19ECS*

XCLKS*Gnd +5

XA16

AN15

PM3PM4

AN13AN12

PM2

RxCANTxCAN

H2DM912C32

20

40

21

1

CANL CANH

PE1

PT5PT4PT3PT2PT1PT0PM0PM1

PT7

PE0+5ResetGndVin

PT6

AN0

AN3

RXDTRGnd

AN2

AN4AN5AN6AN7PM5

PM2

PM4

TX

AN1

PM3

EE319K EE345L

Cut and trim a label to place between the 9S12 and the protoboard.