Top Banner
SECTE University Of Wollongong Commercial in Confidence Page 1 of 32 School Of Electrical, Computer & Telecommunications Engineering UOW ECTE333 Autumn Session Laboratory Notes (Annual Subject) Version: 2.5 This publication is copyright. The contents of this publication are strictly for the use of UOW, and should not be transmitted externally, unless otherwise authorised in writing. Copyright UOW
32
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: ECTE333_labnotes_2013

SECTE University Of Wollongong

Commercial in Confidence Page 1 of 32

School Of Electrical, Computer &

Telecommunications Engineering UOW

ECTE333

Autumn Session

Laboratory Notes

(Annual Subject)

Version: 2.5

This publication is copyright. The contents of this publication are strictly for the use of UOW, and should not be transmitted externally, unless otherwise authorised in writing. Copyright UOW

Page 2: ECTE333_labnotes_2013

SECTE Laboratory Notes

Commercial in Confidence Page 2 of 32

Document Owner: Laboratory Manager, SECTE

Author: Montse Ros

Approved By: Montse Ros

Approval Date: 04/03/2013

Document Control: Version Date Author Reason 1.0 30/01/07 Sasha Nikolic Update old procedures 1.1 01/02/07 Montse Ros Updating notes to comply with new Annual Subject

rules as well as some minor corrections and formatting changes throughout. Added Appendices.

2.0 22/02/08 Montse Ros Complete change of subject material incorporating change to Atmel AVR microcontroller and expansion to 6 smaller experiments. Added Appendices.

2.1a 27/02/09 Montse Ros Reduced to Experiments 1-3 for 2009. Experiments 4-6 to be added at a later date.

2.1b 31/03/09 Montse Ros Added Experiments 4-5 for 2009. Experiment 6 to be added at a later date.

2.1c 8/05/09 Montse Ros Added Experiment 6. Document finalised for 2009. 2.2 16/02/10 Montse Ros Removed references to Virtual Machines

Added new Experiment 6 for 2010 2.3 20/01/11 Montse Ros Changed content of some experiments 2.4 20/02/12 Montse Ros Replaced Lab4 with Hanoi experiment 2.5 04/03/13 Montse Ros Included information about use of Virtual machines in

Autumn of 2013

Page 3: ECTE333_labnotes_2013

SECTE Laboratory Notes

Commercial in Confidence Page 3 of 32

Table of Contents Introduction …………………………………………………….. 4 Assessment …………………………………………………….. 4 Resources …………………………………………………….. 5 Experiments Experiment 1 ……………………………………………… 9 Experiment 2 …………………………………………….... 14 Experiment 3 …………………………………………….... 17 Experiment 4 …………………………………………….... 19 Experiment 5 …………………………………………….... 22 Experiment 6 …………………………………………….... 24 Appendix A …………………………………………………….. 26 Appendix B …………………………………………………….. 27

Page 4: ECTE333_labnotes_2013

SECTE Laboratory Notes

Commercial in Confidence Page 4 of 32

Introduction

The ECTE333 Laboratory introduces students to the use of a microcontroller board, specifically the Atmel AVR STK500 Board. These experiments have been designed with the aim of familiarising the student with the tools available to program the STK500 board, and to allow the student to use the information they know about the microcontroller to solve various problems. The STK500 board provides access to all components of the Atmel AVR microcontroller. Programs are mainly written in Assembler Language and are compiled and downloaded using the AVR Studio software. Programs can also be written in the C programming language and compiled using the WinAVR software. Students can simulate almost every aspect of the AVR microcontroller on their home PCs by installing the AVR Studio software and using the emulation tools. The programs developed by students are downloaded to the STK500 board via an RS232 link for execution, so for hardware practise, students will require a serial port. This is not needed, as only simulation is required in the home experiments.

Assessment

Laboratory Schedule

Please check the subject timetable for practical times.

There will be no laboratory sessions in Week 1. All Laboratory sessions will be conducted in even weeks, starting from Week 2 with the Laboratory Exam during University Exam period. The experiments to be undertaken in each laboratory session are given in the table below:

Experiment Week (Even)

1 2 2 4 3 6 4 8 5 10 6 12

Lab. Exam University Exam Period

Laboratory Structure

There will be six experiments to be completed in the Autumn Session. A further six experiments will be completed in the Spring Session (see Spring Lab Notes).

Across the entire year, the laboratory components comprise 45% of the total assessment for ECTE333, as outlined on the subject outline. This is broken down into 20% assessment in Autumn and 25% assessment in Spring. Preparation and conduction of the Home Experiment for the laboratory is mandatory. Before the start of each laboratory session, the students must undertake a WebCT based quiz consisting of approximately 10 questions. Severe penalties will be awarded to students who do not complete this quiz before entering the room (see Subject Information Sheet for details). Proper preparation can be achieved by reading through the home experimental and making notes in your laboratory book of what is observed. Experiments should be completed before entering the laboratory. There is limited time for the laboratory sessions (1 hour to mark ~45 demonstrations), so it is important that time is not wasted asking questions that could have been answered prior to entering the lab.

Page 5: ECTE333_labnotes_2013

SECTE Laboratory Notes

Commercial in Confidence Page 5 of 32

There will be a Practical Test in the University Exam Period. This test will consist of writing a simple program in 60 minutes from scratch. This means the task is to be completed without using any listings of programs or files on any removable storage media, local hard disk or in network drives. A properly formatted laboratory notebook may be brought into and used in the test.

Laboratory Notebooks

The students should also maintain a laboratory logbook. This must be a hard cover book with page numbers and a place for an index. There must be an entry in the laboratory notebook for each laboratory session attended, dated and noting progress through the laboratory. This logbook will be inspected by the laboratory demonstrator after demonstrations and a grade will be given for each task recorded in the logbook. It is the responsibility of each student to ensure that the lab demonstrator views their laboratory notebook. Remember, your laboratory logbook is the main evidence of your progress – accordingly, your progress mark will be based on the progress evidence in your logbook. Thus, you should write down all activities in your experiments, including aims, methods, expected vs. actual outcomes and especially your observations and/or deductions. Also note it is the ONLY reference students may bring into the practical exam room with them.

Resources

Laboratory Essentials All software required for the laboratory is installed on the computers in the school's digital laboratory. This software is also freely available to students and can be obtained from the AVR webpage (http://www.elec.uow.edu.au/avr/ or follow the links from the school webpage http://www.elec.uow.edu.au/). The website contains details on the STK500 board as well as the AVR microcontroller and documentation on the use of the AVR Studio software. This site is intended to be the major source of documentation for this laboratory and can be accessed with any internet browser. Students should store their work on their network drives accessible with their school computer account. By doing this, students can access their work each week without the need to store everything on a floppy/USB disk or the hard disk of a particular lab computer. However, students should make their own backups onto a floppy/USB disk if they intend to work elsewhere, and as a general backup if the school network fails. Details about how Students can use their computer accounts from Windows are contained in the documentation on the website. You also require a School computer account to be able to print. The digital laboratory has two black and white laser printers. Printing to these printers is charged to your printing credit account at 10c per page. Each student is credited with some printing at the start of each session but you can increase your credit at any time by paying at the Faculty Office.

Windows 7 and VMWare Virtual Machines running Windows XP The PC’s in the School’s Laboratories have multiple operating systems installed on them and various virtual machines for the number of different subjects in the school. When you power up or reset the computers, you are presented with a boot manager screen. Some of you may already be familiar with this boot manager; it’s called Debian Grub. It’s the boot manager typically used to boot linux, but is also capable of booting many other operating systems. For the purpose of these laboratories, you should boot into Windows 7. As part of the boot-up process, a Windows Logon window will appear. You should use your School account logon and password (not your UOW/ITS account details). On the base PC Windows 7, you may find the newer version of Atmel AVR Studio 6 installed. DO NOT use this version for Autumn, as there is no supported simulator for the ATmega8515 chip in the newer software. The school is in the process of upgrading our AVR studio software, as such,

Page 6: ECTE333_labnotes_2013

SECTE Laboratory Notes

Commercial in Confidence Page 6 of 32

you will be using the old version (Studio 4) inside a Windows XP virtual machine for the ATmega8515 in Autumn, and the new version (Studio 6) on the base PC in Spring with the ATmega16. As various subjects require different machine setups, virtual machine software (VMWare) has been installed onto the digital lab computers. The AVR Studio 4 software for Windows XP is available on the Virtual Machine called “XP” in the digital laboratory (35.129). Starting a new virtual machine is as simple as opening up VMWare and selecting the relevant machine – a basic Windows XP machine can be found on D: drive. Once inside the virtual machine, students can operate as though in a normal Windows XP environment. The standard setup is shown in the figure below.

IN AUTUMN OF 2013, STUDENTS SHOULD USE AVR STUDIO 4 ON THE VIRTUAL MACHINE BECAUSE ATMEL STUDIO 6 DOES NOT SUPPORT SIMULATION OF THE ATMEGA8515.

The STK500 Board and AVR microcontroller The STK500 board is a development board for the study of and practice with AVR microcontrollers. The labs will only be using the one AVR slot, however this STK500 development board can accommodate a wide variety of AVR microcontrollers. A microcontroller is slightly different to a micro-processor. Generally, it is not as computationally sophisticated as a modern microprocessor, but it has many capabilities which make it ideal for embedded applications. The process of writing software for the AVR microcontroller is possibly very different to anything you may have experienced. Remember, you are writing software for a device designed to operate as an embedded controller and not a desktop computer. The C or Assembler code is written using the in-built editor in AVR Studio. After you have written your code, you need to compile and link it to produce a program that can be executed by the processor of the STK500 board, the Atmel

Page 7: ECTE333_labnotes_2013

SECTE Laboratory Notes

Commercial in Confidence Page 7 of 32

AVRmega8515. Code that runs on a PC, for example, cannot run on this board. Similarly, the code for this board will not execute on a PC. The STK500 board does not have an operating system like a PC does. Instead, it contains another microcontroller and associated hardware that assists in the downloading and running of your software. This communicates with the PC’s AVR Studio via the serial port. There is no operating system on your target microcontroller, either. The lack of operating system means that the software you write will have direct control over the hardware of the board. There is no “DOS Prompt” or “Desktop” to return to when your program completes. The AVR microcontroller is a small, yet powerful device. It provides you with a serial communications port, an analogue-to-digital comparator, digital inputs and digital outputs. The microcontroller is the sort of device you might find in an engine management unit of a modern motor vehicle, or a calculator or even a modem. The code that you will be writing is designed to explore the features of the processor as well as providing you with experience in writing in Assembler and C languages. The former is possibly a new language for most students. Since the AVR microcontroller forms the basis of all twelve laboratories in this annual subject, it is important that you come to terms with its capabilities and limitations as soon as possible. The AVR homepage provides you with a great deal of resources to make this task easier. There is an introductory tutorial and some sample programs available and several more documents that may be of use. You should familiarise yourself with these documents; your task will be made simpler if you do. The process of reading and familiarisation cannot be disregarded. If you wish to perform well in this subject, then you should take this task seriously.

Compiling and Assembling What is compiling and assembling? You will all be familiar with the process of compiling code on a PC, Macintosh, or UNIX based computer. When you write software for a microcontroller, such as that of the AVR, the process is not a whole lot different. The difference is that you are generating code that is to be executed on a processor that has a different instruction set to that of a PC. Hence the term cross compile. Before going on, a couple of definitions must be made. The following labs will include code written in both C and Assembly languages. Assembly language is a low level machine language. The instructions used when programming in this language depend on the target processor. C language is a higher level language- allowing a greater understanding of the code. Whichever language is used, the compiler and assembler must be used to produce an object file from the written code. The object file is converted to hexadecimal format and is downloaded to the program memory of the AVR and executed. The downloading and execution of a program are the subject of the first experiment. When you compile your code, there are several stages that the code passes through before you obtain an output ready for downloading and execution on the microcontroller. A simplified process (assuming you wrote your code in the C programming language) would be as follows: 1. The code is parsed by a pre-processor which removes white space, handles macro

substitutions and conditional compilation. 2. The output of the pre-processor is passed to a syntax and semantic analyser. The output of

this process is intermediate code for the next phase. 3. The next step is the code generator. This process produces the assembler code from your C

code. 4. The assembler code is then passed to an optimisation application which rearranges the code

to minimise the number of jumps in the code. This step can be bypassed, but is not recommended since the output of the code generator can often produce wasteful code.

5. The output of the optimiser is passed to the assembler. The assembler generates a machine readable output called an object file.

6. The object file is the passed to a linker application which takes your code and links it with any library functions that you may have used, such as “printf()”. The output of this process is another object file that contains the complete version of your source code.

Page 8: ECTE333_labnotes_2013

SECTE Laboratory Notes

Commercial in Confidence Page 8 of 32

7. The final object code is then passed to a hexadecimal code generator. This step takes the source object code and converts it to the hexadecimal code representation of the instructions that the processor executes. Embedded in this file are the addresses in memory that each byte needs to be located.

If you wrote your code using assembler, steps 5 to 7 would be appropriate.

Laboratories

Students are expected to enter the laboratories with all home experiment tasks completed. In order to receive an STK500 board, for use in the lab, students will need to provide their student card – it will be returned at the end of the lab upon return of the board. Students will be demonstrating their work during the allocated 1-hour timeslot and should notify the demonstrator when they are ready to be marked. Once marked, the students should pack up all associated hardware, return their board and may leave when all hardware at their workstation has been tidied up.

Page 9: ECTE333_labnotes_2013

SECTE Laboratory Notes

Commercial in Confidence Page 9 of 32

Experiment 1 – Introduction to the AVR

The aim of this first lab is to give you an introduction to the AVR studio environment and AVR microcontroller. There are two programs used in this lab. The first program shows you how information is read in and out from Ports. The second half extends this idea, by showing how you can interface the ports to the on-board LEDs. In this lab you will also learn how to set up the AVR Studio, build, simulate AVR programs and download compiled binary files to the Atmel AVR STK500 development board.

Home Experiment

Task 1 Install the AVR Studio on your computer or gain access to the labs to use the software package. The download link is available at the SECTE microcontroller site (http://www.elec.uow.edu.au/avr/). Also, read through the initial pages of these lab notes, especially the section under “Lab Essentials”. In particular, pay close attention to the information regarding the use of the virtual machine and AVR STUDIO 4.

… you should now be able to answer Pre-lab questions 1 & 2. Task 2 Open the Virutal machine called “XP” and then open AVR STUDIO 4. Create your first AVR project by following the “HOW-TO use AVR Studio for Assembler Programming” located at the SECTE microcontroller site. Follow the directions on that HOW-TO document exactly.

…you should now be able to answer Pre-lab questions 3 & 4. Task 3 Create a new Project and name it “Lab1-a”.

Add the following code to the project and build and simulate the code.

; ; Lab1-a assembler program ; .include "m8515def.inc" ; include the 8515 definition file .def temp = r16 ; define a temporary register ; ; Continually read in from PORTA and write out to PORTB ; RESET: ; Set the Data Direction Registers (DDRA & DDRB) ; (0's = inputs, 1's = outputs) ldi temp, 0x00 out DDRA, temp ldi temp, 0xFF out DDRB, temp LOOP: ; Now, we continually loop, reading PORTA, writing to PORTB in temp, PINA ; read in from PORTA's input pins

Page 10: ECTE333_labnotes_2013

SECTE Laboratory Notes

Commercial in Confidence Page 10 of 32

com temp ; complement value out PORTB, temp ; write out to PORTB rjmp LOOP ; jump back to LOOP

To build the code, head to the main toolbar and click on “Build” as shown below

You should get a similar build message to the one shown below:

Now to simulate the code, head to the “Debug” option in the main toolbar to start debugging:

Stepping through the debug option executes one line of code at a time. To step through the code hit the “F11” key. The debugging mode should open up to the left of the I/O view. The I/O view window allows you to display and edit all the peripheral and I/O memory values. Change the I/O View to Tree View in order to see all Ports at the same time.

Open Ports A and B before stepping through the rest of the code. Experiment with various values on PINA and observe the output at PORTB. The squares indicate the value in each of the registers. Filled represents 1 and clear represents 0. Clicking on the PINA squares will toggle the value.

Page 11: ECTE333_labnotes_2013

SECTE Laboratory Notes

Commercial in Confidence Page 11 of 32

You may also wish to have the Flat Register View mode selected to see what changes are happening to the registers. You may also view the values in Decimal. Right click on Value and choose the option Display as Decimal.

…you should now be able to answer Pre-lab questions 5-7. Task 4 Create a new project and call it “Lab1-b”. Add the following code into your project and simulate your code.

; ; Lab1-b assembler program ; .include "m8515def.inc" ; include the ATMEGA8515(L) definitions file .org $000 rjmp RESET .org $007 ; set start address to Timer 0 overflow rjmp ISRTIME ; jump if timer0 overflows .def outval = r16 ; labelling regisers .def temp = r17 ; .def counter = r18 ; RESET: ; Initialise the stack pointer (standard method) ldi temp,low(RAMEND) ; lower half out SPL,temp ldi temp,high(RAMEND) ; upper half out SPH,temp ; set up portb ser temp out DDRB, temp ; set all pins of PORTB as outputs ldi outval, 0xAA ; set to zero out PORTB, outval ; output to port B ; initialize timer 0 ldi temp, 0x05 out TCCR0, temp ; set timer 0 prescaling to lowest /1024 clr temp ; clear all bits out TCNT0, temp ; clear the timer ; setup timer 0's overflow interrupt in temp, TIMSK ; load Timer Interrupt Mask Register

Page 12: ECTE333_labnotes_2013

SECTE Laboratory Notes

Commercial in Confidence Page 12 of 32

sbr temp, 1<<TOIE0 ; set the timer 0 overflow interrupt enable bit out TIMSK, temp ; save Timer Interrupt Mask Register ldi counter, 0x04 sei ; enable interrupts LOOP: ; do nothing, just loop forever(waiting for timer0 overflow) rjmp LOOP ISRTIME: ; interrupt service routine ; is executed every 2^16 pre-scaled cycles dec counter cpi counter, 0x00 brne BACK com outval ; Toggle ODD and EVEN Pins out PORTB, outval ; output to port B ldi counter, 0x04 BACK: reti ; return from interrupt (different to normal return)

In order to simulate this code, many, many cycles are needed, as the first change of PORTB does not occur until the program is in its 1048588th cycle. Even running the program on “Autostep” (Alt+F5) will take over 17 hours. Viewing a change in output will require setting the debugger to “Run” (F5) which runs the program without updating the registers and I/O Tree. When you want to stop running, you can select “Break” (Ctrl+F5) and the registers will be updated. For example, in the cycle 1048581, PORTB still has the data 0xAA, however by cycle 1048589, the data has changed to 0x55.

…you should now be able to answer Pre-lab questions 8-10. Task 5: Questions… Answer the following questions in your lab book:

Describe what you see in Tasks 2 and 4 in the home experiment? What is the I/O view used for? How many modes are there to the I/O view? What is the register window used for? If the same program that takes over 17 hours to perform using the “Auto Step” feature, can be

performed using the “Run” command in less than 10 seconds, how much faster does it run? How fast do you expect the data changes on PORTB will happen on the hardware?

Lab Demonstration

Task 1 Connect the necessary power to the board and wire up the board. The STK500 board takes between 10V and 15V, so students should connect the black (ground) connector to ground and the yellow or white (15V) connector to the corresponding connections on the power board in the lab. DO NOT USE THE BLUE CONNECTOR (-15V) at all.

Page 13: ECTE333_labnotes_2013

SECTE Laboratory Notes

Commercial in Confidence Page 13 of 32

Make sure the STK500 is connected to the computer’s serial port with the 9-pin serial cable. Additionally, the STK500 board’s target area is where we select which of the 6 sockets our AVR micro is located in. Use the 6-pin cable connector to connect the ISP6PIN pins to the SPROG3 pins. The programs that were used in the home exercise used PORTA and PORTB. Thus, wire up the board so that pins in PORTA interface with the switches and the pins on PORTB interface with LEDs. Ask your demonstrator for a 10-pin wire connector if you do not have one. Be careful to connect the pin connectors correctly. Open up AVR Studio and load Project “Lab1-a”. To download the program to the board, do the following. Click on Tools -> Program AVR ->Connect or click on the small “AVR” chip icon.

In the dialog box choose COM1. Next hit connect and another dialog box appears. Here head to the program tab, choose the compiled hex file (click “…”) and place it as the input to the “Flash” option.

After choosing the hex file, hit the program button. Once done, demonstrate to your lab tutor. Ensure you are marked off for Task 1 before starting Task 2. Task 2 Repeat the process in Task 1, except this time create a new Project called “Lab1-b”. Demonstrate to your lab tutor when you are finished.

Page 14: ECTE333_labnotes_2013

SECTE Laboratory Notes

Commercial in Confidence Page 14 of 32

Page 15: ECTE333_labnotes_2013

SECTE Laboratory Notes

Commercial in Confidence Page 15 of 32

Experiment 2 – Familiarisation with the AVR internals

In this lab you will be shown an example of the operations a microcontroller may perform. There are three parts to this laboratory. The first part will require you to execute code, which reads two BCD numbers from a port. Then output the addition and product of the two numbers to other ports. The second part will require you to analyse the operation of the code. The final part will require you to modify the code so that the product function is replaced by a subtraction. Task 1 Examine the following assembly code.

; ; Lab2-a assembler program ; .include "m8515def.inc" ; include the ATMEGA8515(L) definitions file ; Some register definitions, using meaningful names .def BCD1 = r16 ; define register to store the first BCD value .def BCD2 = r17 ; define register to store the second BCD value .def temp = r18 ; use this register to store temporary values ; Define a label "reset". Jump here if you want to reset the program RESET: ; Setup PORTA as an input and PORTB and PORTC as outputs. ldi temp, 0b11111111 out DDRB, temp ; set all pins of PORTB as outputs out DDRC, temp ; set all pins of PORTC as outputs ldi temp, 0b00000000 out DDRA, temp ; set all pins of PORTA as inputs LOOP: ; Now we continuously run the program in a loop in temp, PINA ; Read the pin values of PORTA into register ; Extract BCD1 value (bits 0-3) com temp ; Invert the bits for use on hardware mov BCD1, temp ; Copy the value of temp into BCD1 andi BCD1, 0b00001111 ; Mask off the least-significant 4 bits ; Extract BCD2 value (bits 4-7) mov BCD2, temp ; Copy the value of temp into BCD2 andi BCD2, 0b11110000 ; Mask off the most-significant 4 bits swap BCD2 ; Swap the nibbles so that the 4 bits ; are in the correct position ; Add values and output to PORTB mov temp, BCD1 ; temp = BCD1 add temp, BCD2 ; temp = temp + BCD2 com temp ; Invert the bits for use on hardware out PORTB, temp ; Write the result of addition to PORTB ; Multiply values and output to PORTC mov temp, BCD1 ; temp = BCD1 mul temp, BCD2 ; r1,r0 = temp * BCD2 mov temp, r0 ; r0 lower byte (small numbers) com temp ; Invert the bits for use on hardware out PORTC, temp ; Write the result of the multiply to PORTC rjmp LOOP ; Jump back to start ; END of code

… you should now be able to answer Pre-lab questions 1 & 2.

Task 2 Once you have understood the assembly code add it to a project called “Lab2-a” in AVR Studio. This is done in the same way as Lab 1. If there are no errors in the code, start the simulation. A yellow arrow indicates the current line that is being executed.

Page 16: ECTE333_labnotes_2013

SECTE Laboratory Notes

Commercial in Confidence Page 16 of 32

We would like to confirm that the code operates as expected. In order to do this, we need to view the registers. Your I/O view pane should look like this:

The squares indicate the value in each of the registers. Filled represents 1 and clear represents 0. Clicking on the squares will toggle its value. Keep clicking “Step into” [F11] until you reach the following line

You should now notice that the values in DDRB and DDRC are all filled. This indicates that all pins in PORTB and PORTC are set as outputs.

Since we have reached the beginning of our loop we can observe the result of any input to PORTA. Click the boxes for the PINA register so that it looks like the following.

This is equivalent to inputting “10010110” into port A. This is also the BCD numbers “0110” and “1001” or in decimal “6” and “9”. However, remember the buttons on the development board are active-low. Hence, you will notice the program code compensates for this by inverting immediately after reading from the switches as well as inverting immediately before outputting to the LEDs. We would expect the addition to be “15” and the multiplication to be “54”. If you want to look at more registers like the program counter (PC) or status register (SREG) “view menu -> toolbars -> processor”.

Page 17: ECTE333_labnotes_2013

SECTE Laboratory Notes

Commercial in Confidence Page 17 of 32

Now step all the way to the last line of the code.

Now the ports should look as follows”

Check that these outputs are correct. Keep in mind that the LEDs are active-low too. Now try running the code with different inputs. AVR studio has an option to automatically step though your code “debug menu -> auto step”.

…you should now be able to answer Pre-lab questions 3-7. Task 3 Modify the code so that PORTC outputs the difference between the two BCD values instead of the multiplication. The instruction for subtraction is “SUB”. Build and simulate the code. Ensure that it operates as expected.

…you should now be able to answer Pre-lab questions 8-10. Task 4: Questions… Answer the following questions in your lab book:

What does the code from task 1 do, step-by-step? What should 10100110 on PORTA give you on PORTB and PORTC if using the code from task 1? What do the “swap” and “com” instructions do? Where is the result of “mul” stored in the code from task 1? Manually work through the code with input “11001000”. Make sure you show each step of the

process. Indicate how the values of each important register [PC, SREG, r16, r17, r18] changes. What changes did you make in the code in task 3? Assuming the input is “00111011”. What should the output on PORTC be for the code in task 3?

Lab Demonstration

Task 1 In this part of the lab you will need to demonstrate your code from task 3 of the home experiment (with the subtraction implemented) to the lab demonstrator. Load your code onto the flash of the ATMEGA8515 as described in lab 1. Make sure PORTB is plugged into the LEDs and PORTA is plugged into the switches.

o Input the numbers “3” and “4”, check that the output is “7” o Input the numbers “8” and “9”, check that the output is “17”

Now plug in PORTC to the LEDs

o Input the numbers “4” and “1”, check that the output is “3” o Input the numbers “8” and “8” check that the output is “0”

Once done, demonstrate to your lab tutor. Explain to the tutor the purpose of the following registers: PINA, PORTB, DDRC, PC, SREG. The tutor may ask you the function of some instructions in the code.

Page 18: ECTE333_labnotes_2013

SECTE Laboratory Notes

Commercial in Confidence Page 18 of 32

Experiment 3 – Writing your first Assembler programs

In this lab you will learn to load and read from registers and memory. There are two parts to this lab. The first part requires you to code a program that loads two variables in a register and performs a number of arithmetic and logical operations. The second part requires you to perform the same operations but instead of using the registers, the operations should be performed on two values stored in memory. The results are also written to memory. The AVR instruction set comes in very handy in this lab – be sure to keep it close at hand. Also understanding the code syntax provided in lab 1 and lab 2 will aid you in this lab.

Home Experiment

Task 1 Write a program that loads two values into registers, r16 and r17. Then perform a number of operations, storing the results in subsequent registers. Ensure that the values are stored in into new registers in each case. Follow this pseudo-code:

r16 <= 4 r17 <= 9 r18 <= r16 + r17 r19 <= r16 – r17 r20 <= r16 r17 r21 <= r16 AND r17 r22 <= r16 OR r17 r23 <= r16 XOR r17

Note that although you have access Registers 0 to 31, not all registers are available for use. Some registers are reserved for special usages. Registers 26 to 31 are reserved for index registers. Also note that some instructions can only be used on the upper half of the register file (registers 16+).

… you should now be able to answer Pre-lab questions 1-3. Task 2 Following the instructions provided in Lab 1, create a new project and name it “Lab3-a”. Add the code from Task 1 to the project and build and simulate it.

…you should now be able to answer Pre-lab questions 4 & 5. Task 3 In this task, you need to perform the same operations done in your program from Task 1, however this time your program should load the values from memory and store both the values and their results back into memory each time. The pseudo-code is given below. Note that the term “mem[0060]” denotes the memory location referenced by address 0x0060 (in hexadecimal).

r16 <= 4 r17 <= 9 mem[0x0060] <= r16 mem[0x0061] <= r17 mem[0x0062] <= r16 + r17 mem[0x0063] <= r16 – r17 mem[0x0064] <= r16 r17 mem[0x0065] <= r16 AND r17 mem[0x0066] <= r16 OR r17 mem[0x0067] <= r16 XOR r17

Students must NOT use any registers other than r16 and r17. Note that the result of each operation is stored in the corresponding memory address. This will require the operation (which will write to the first register) to be followed by an instruction to STORE the result to memory. Additionally, the original value will

Page 19: ECTE333_labnotes_2013

SECTE Laboratory Notes

Commercial in Confidence Page 19 of 32

also be overwritten, so a load from memory will also be needed. Students may wish to look up the LDS and STS instructions for further help.

… you should now be able to answer Pre-lab questions 6-8. Task 4 Create new project and name it “Lab3-b”. Add the code from Task 2 to the project and build and simulate it.

… you should now be able to answer Pre-lab questions 9 & 10. Task 5: Questions… Answer the following questions in your lab book:

What values do you expect to be stored in each of registers r18 through r23 for the first program? Did you obtain your expected values? Why were the registers used, starting from r16? Which instructions limit the use of the destination register? Was there any Carry, Negative or Overflow issues observed in the operations? Where were these reflected?

Lab Demonstration

This lab does not require the use of the STK500 boards. Task 1 Simulate your “Lab 3-a” project code functioning using the AVR studios. Once ready, demonstrate to your lab tutor. Ensure you are marked off for Task 1 before starting Task 2. Task 2 Repeat the process in Task 1, except this time for your Project called “Lab3-b”. Demonstrate to your lab tutor when you are finished.

Page 20: ECTE333_labnotes_2013

SECTE Laboratory Notes

Commercial in Confidence Page 20 of 32

Experiment 4 – Using the Stack

In this lab you will use your more advanced assembler programming skills to incorporate stack pointer usage, subroutines and recursion. As stack pointer usage requires students to understand the concepts of indirect and indexed addressing, it is recommended students understand the various addressing modes described at the beginning of the Instruction Set Manual.

Home Experiment

Background Theory – Tower of Hanoi The Tower of Hanoi is a mathematical puzzle than can either be solved by a simple equation, or by recursion. In this laboratory, we will implement two solutions for this puzzle. The puzzle begins with a stack of n increasingly sized discs around a peg, with two pegs vacant. The goal is to transfer the stack of discs from the first peg to the third peg following a set of rules. The start position and goal are shown here:

The rules for disc movement are as follows:

You can only move one disk at a time When picking up a disc, it must be the top disk of the stack. When placing a disc, it must be placed at the top of the destination stack. No disc can be placed on top of another disc with smaller size

Students should familiarise themselves with the problem – some small examples can be performed by hand and a simple internet search for the words “Hanoi”, “gif” and “animation” will show a few animated solutions created by third parties. So, now how to solve the problem? We are interested in the total number of moves required for any number (n) disks – the actual moves themselves aren’t necessary. The non-recursive solution is given by the expression:

(Sidenote: can you explain why?).

The recursive equation is given by the following formula, as a result of breaking down the larger problem �

into smaller problems – :

This can be explained easily using an example. Assuming the pegs are numbered left to right (P1, P2, P3), the problem of moving 4 discs from P1 to P3 can be summarised as:

Move smallest 3 discs from P1 to P2 Move biggest disc from P1 to P3 Move smallest 3 discs from P2 to P3

Page 21: ECTE333_labnotes_2013

SECTE Laboratory Notes

Commercial in Confidence Page 21 of 32

Task 1 In this task you will write a program to calculate the tower of Hanoi number using a for-loop within a subroutine. The C-code is provided. You are required to implement the program in assembly. The parameters and return values must be passed via the stack.

typedef unsigned char byte; // define 8-bit variable type int main(void) { byte result, num = 6; for(;;) { // Calculate the result of the Tower of Hanoi result = hanoi(num); } } byte hanoi(byte n){ // calculate 2^n-1 without the pow() function byte ret = 1; for(byte i = 1; i <= n; i++) { ret *= 2; } ret--; return ret; }

Read the C-code carefully to implement the correct functionality in assembler. An example assembler code template is given below. Be careful to initialise the stack before using it. That is, set the high and low values of the stack pointer to the correct memory address (RAMEND). In addition, be careful to keep note of the size of each register. We will assume no math library, so the “pow()” function will need to be calculated using a for-loop. The “ldd” instruction will be very useful in manipulating the stack values in this program. Additionally, multiplying by 2 can be done easily by using the “lsl” instruction. Look these up and understand how it to use them.

; ; Lab4-a assembler program ; .include "m8515def.inc" ; include the ATMEGA8515(L) definitions file .def num = r16 ; use this register to store ‘num’ .def result = r17 ; use this register to store ‘result’ RESET: *** Initialise the stack *** LOOP: ldi num, 0x06 ; this is our start number *** setup passing parameters on the stack *** rcall HANOI *** capture the return value from the stack *** rjmp LOOP ; Jump back to start HANOI: *** Add hanoi calculation *** ret ; END of code

Save your code in a project called “Lab4-a”.

… you should now be able to answer Pre-lab questions 1-3. Task 2 Simulate “Lab4-a” in AVR studio. Ensure that is works as required. Remember that all buttons and LEDs on the STK500 are active low. You can view the stack in AVR studio by using the memory viewer during simulation (view -> memory). You stack should be located at the end of the data memory (use the drop down menu in the top left to navigate to the data memory).

Page 22: ECTE333_labnotes_2013

SECTE Laboratory Notes

Commercial in Confidence Page 22 of 32

…you should now be able to answer Pre-lab questions 4 & 5. Task 3 Similar to task 1, write assembly code to implement the Hanoi solution with recursion. Again, the parameters and return values must be passed by stack. The C-code is provided:

typedef unsigned char byte; // define 8-bit variable type int main(void) { byte result, num = 6; for(;;) { // Calculate the result of the Tower of Hanoi result = hanoi(num); } } byte hanoi(byte n){ if(n <= 1) return n; else return ( 2*hanoi(n-1) + 1 ); }

The same assembly template as before may be used. It may help to write the Hanoi part of the c-code as a flow chart before attempting the assembly code.

…you should now be able to answer Pre-lab questions 6-8. Task 4 Simulate “Lab4-b” in AVR studio. Ensure that it works as expected. Look at the data memory in the simulation and observe how the stack is filled up.

…you should now be able to answer Pre-lab questions 9 & 10.

Page 23: ECTE333_labnotes_2013

SECTE Laboratory Notes

Commercial in Confidence Page 23 of 32

Task 5: Questions… Answer the following questions in your lab book:

Where can you store the stack in the ATMEGA8515L address space? What is the largest number that can be inputted into this program without the output overflowing? What should be done before using generic registers in a subroutine? How is “ldd” different to “ld”? How does the data memory change as the “rcall HANOI” instruction is executed? How does stack access change the data memory? What is one advantage of recursion? In task 4, how many bytes added to the stack each recursion (and what are they)? In task 4, what is the maximum number of recursions before the stack is full?

Lab Demonstration

This lab does not require the use of the STK500 boards. Task 1 Demonstrate your program calculating the Hanoi calculation of various values of n. Simulate your code and explain to your tutor what is added to the data memory when the “rcall HANOI” instruction is executed. Ensure you are marked off for Task 1 before starting Task 2. Task 2 Repeat the process in Task 1, except this time for your Project called “Lab4-b”. Demonstrate to your lab tutor when you are finished. Show your calculation of the maximum number of recursions possible.

Page 24: ECTE333_labnotes_2013

SECTE Laboratory Notes

Commercial in Confidence Page 24 of 32

Experiment 5 – Polling and Reacting to Interrupts

In this lab you will examine the use of digital IO with polling and external interrupts in the ATMEGA8515L. Often microcontrollers are required to respond to externally generated events, such as a high-to-low transition or a low-to-high transition on a pin. Microcontrollers can also respond to internally generated events such as timer overflows; however this will be covered in the Spring Session of the subject.

Home Experiment

Task 1 In this part, you are required to read input from a keypad on PORTB and output the value to a 7-segment display on PORTA. The keypad and display board’s data sheet is provided on the SECTE AVR website under Documentation “FM629 Digital IO Board”. It is essential that you read and understand this, as it provides you with the details to interface the board with your microcontroller. The easiest way to write a program that will interface with the keypad is to divide the keypad into rows and columns. Each column and row is then mapped to a Pin on one of the Ports. An example is shown below.

For instance if the number 5 is pressed this means Column 2 is electrically connected to Row 2. The easiest way to retrieve a number form the keypad is to tie the Rows to a pull up register and then set the columns sequentially to 0V using I/O pins on the microcontroller. If no keys are pressed then the row lines remain at the operating voltage. Any keys pressed pulls down the row line’s voltage to zero volts. By knowing which Column line was brought low, as well as which Row line reported 0V, you can determine which button was pressed. All necessary current-limiting resistors have already been added to the board. When connecting to the keypad, the following layout of bits is observed:

Bit number: 7 6 5 4 3 2 1 0

Purpose: unused Col1 Col2 Col3 Row1 Row2 Row3 Row4

Notice that Column bits are to be used as outputs and Row bits are to be read as inputs. Once the keypad keys are mapped (i.e. in rows and columns) you can then store the pressed value in a register. The column

Page 25: ECTE333_labnotes_2013

SECTE Laboratory Notes

Commercial in Confidence Page 25 of 32

bits can be written - and the row bits read - using the same port (PORTB), as long as the necessary bits are set to either input or output. Think carefully about what value to load into the DDRB register. An example for checking if the ‘1’ button has been pressed is given below. This will need to be modified to check for all buttons, but students are recommended to get one button working first!

; checking Column 1, Row 1 through PORTB ldi temp, 0b10111111 ; set a mask with only column1 to 0 out PORTB, temp ; output to PortB nop ; one nop delay inherent in AVR circuitry nop ; second nop delay to ensure correct values in temp, PINB ; now we can check ‘temp’ for which row = 0 andi temp, 0b00001111 ; just righthand nibble cpi temp, 0b00000111 ; compare with ....0111 (Row1=0) brne ELSEWHERE ; branch if not equal, to ELSEWHERE ... ; do something!

This value will then be sent to the 7-segment display. As you will be controlling each individual LED in the 7-segment LED display, you will need to be conscious of the order of pins and will need to develop masks for each number on the display. For example, the number “1” only requires two LEDs: b and c.

Bit number: 7 6 5 4 3 2 1 0

Purpose: DP g f e d c b a

Given the layout and connector pin assignments above, the following two masks are recommended:

; set 7-segment display labels .equ ZERO = 0b00111111 .equ ONE = 0b00000110

Students should generate the masks for the remaining numbers and can create their own designs for keys * and #. Students should note that the 7-segment LED display is active high. This means that writing a ‘1’ to an I/O port pin will light the corresponding LED. Write a program to input from a keypad on Port B and output to a 7-segment display on Port A, based on the explanations above and the datasheet on the website. The following is an example assembler program to provide a structure:

; ; Lab5-a assembler program ; .include "m8515def.inc" ; set 7-segment display labels *** setup all labels *** RESET: *** set up Direction Registers *** LOOP: *** Probe Keypad for button pressed *** *** Output value to LEDs *** rjmp LOOP

Page 26: ECTE333_labnotes_2013

SECTE Laboratory Notes

Commercial in Confidence Page 26 of 32

Task 2 Add the code you have written in Task 1 to a project named “Lab5-a”. Build and simulate the code. You will be able to fully debug your program in AVR Studio simply by toggling the port pins to simulate what the hardware will do.

… you should now be able to answer Pre-lab questions 1-5. Task 3 Write your program to implement the flow chart below. You will need to use interrupts to increment a counter every time there is a rising OR a falling edge on external interrupt 0. Additionally, you will increment the counter by 16 whenever there is a rising edge on external interrupt 1. This counter will be continuously outputted to PORTB.

Initialise Interrupt Vectors

InitialiseStack

Continually output Counter

to PORTB

RESET

LOOP

org $0000

Increment counter by 1

Increment counter by 16

Triggered by EXTINT1 (rising

edge only)

Counter = 0

Setup/Enable Interrupts

The following is an example assembler program to provide a structure:

; ; Lab5-b assembler program ; .include "m8515def.inc" *** Initialise interrupt vectors *** RESET: *** Initialise the stack pointer *** *** set up & enable interrupts *** LOOP: *** continuously output port B (don’t forget active-low LEDs!) *** rjmp LOOP EXTINT0: *** add some code here *** reti EXTINT1: *** add some code here *** reti

Task 4 Add the code you have written in Task 3 to a project named “Lab5-b”. Build and simulate the code. Look up the ATmega8515 User Manual to find out which Ports and which Pins are used for the external interrupts.

Page 27: ECTE333_labnotes_2013

SECTE Laboratory Notes

Commercial in Confidence Page 27 of 32

When you have found this information, you will be able to fully debug your program in AVR Studio simply by toggling those Port pins.

…you should now be able to answer Pre-lab questions 6-10. Task 5: Questions… Answer the following questions in your lab book:

What masks are going to be necessary in order to probe the keypad, one column at a time? When probing the keypad by reading in PINB, how can you look at individual bits? If a short 1-or-2 cycle delay is required, which instruction can be used to perform no operation? Which pins are used for EXTINT0 and EXTINT1 interrupts? What port are they on? What memory locations are the interrupt vectors for EXTINT0, EXTINT1 and RESET? What is the command to enable interrupts? How does the hardware react to Interrupts? Describe all steps that happen once an interrupt is

triggered.

Lab Demonstration

Task 1 Connect the necessary connections (i.e. keypad and 7-segment display) using port connectors and power to the ATMEL board. Download the program binary to the board and demonstrate the functioning code to your lab tutor before proceeding to the next part. Task 2 Connect the necessary connections using port connectors and power to the ATMEL board. You can use the standard 10-pin connector cable for generating the interrupts – even if you will only be using two pins on that port. These can be connected to the switches – remember that the switches are active-low! Download the program binary to the board and demonstrate the functioning code to your lab tutor.

Page 28: ECTE333_labnotes_2013

SECTE Laboratory Notes

Commercial in Confidence Page 28 of 32

Experiment 6 – Interfacing to Memory

In this lab, you will interface to a simple memory board, created from nothing but flip-flops and logic gates. It is highly recommended that students download and read the FM662 memory board datasheet on the website and understand its operation.

Home Experiment

Task 1 Write a program to store numbers to the memory locations FF00-FF03 as implemented by the memory board. Your program should begin by storing 4 different values to each of the four address locations. Your program will need to continually read switches SW0-3 on the AVR board, and output the value from the corresponding memory address. The table below shows this in clearer detail:

User input Outcome

User presses SW0 The value stored in address 0xFF00 is visible on the LEDs

User presses SW1 The value stored in address 0xFF01 is visible on the LEDs

User presses SW2 The value stored in address 0xFF02 is visible on the LEDs

User presses SW3 The value stored in address 0xFF03 is visible on the LEDs

It is recommended that students use polling on PortD pins 0-3, and output to LEDs using PortB. However students may use any means at their disposal to complete the experiment. Please also consider that many of the Ports will be occupied with connections to the memory board.

… you should now be able to answer Pre-lab questions 1-7. Task 2 Create a new project and name it “Lab6”. Add the code from Task 1 to the project and build and simulate it.

…you should now be able to answer Pre-lab questions 8-10. Task 3: Questions… Answer the following questions in your lab book:

Which ports are used for the address & data busses when expanding AVR memory? Which port pins are necessary for RD, WR & ALE? When reading in values from a Port, how can you look at individual bits? Which two bits are used to select 1 of the 4 available external memory locations? Which FM662 memory board IC (Integrated Circuit) is the decoder/demultiplexer which selects the

desired location? (part number commencing with ‘74’)

Lab Demonstration

Task 1 Connect the necessary connections (i.e. AVR board to memory board) using port connectors and power to the ATMEL board. You may have to be creative with your use of 10-pin, 2-pin or 1-pin connectors based on availability in the class. Download the program binary to the board and demonstrate the functioning code to your lab tutor.

Page 29: ECTE333_labnotes_2013

SECTE Laboratory Notes

Commercial in Confidence Page 29 of 32

Appendix A: (I/O) Register Summary

* taken from the Atmel AVR 8515 User Manual

Page 30: ECTE333_labnotes_2013

SECTE Laboratory Notes

Commercial in Confidence Page 30 of 32

Appendix B: Instruction Set Summary

* taken from the Atmel AVR 8515 User Manual

Page 31: ECTE333_labnotes_2013

SECTE Laboratory Notes

Commercial in Confidence Page 31 of 32

Appendix B: Instruction Set Summary (cont)

* taken from the Atmel AVR 8515 User Manual

Page 32: ECTE333_labnotes_2013

SECTE Laboratory Notes

Commercial in Confidence Page 32 of 32

Appendix B: Instruction Set Summary (cont)

* taken from the Atmel AVR 8515 User Manual