mic engineering practice - imperial college london · mic engineering practice ... xbee oem rf...

16

Upload: hahuong

Post on 08-Jun-2018

219 views

Category:

Documents


0 download

TRANSCRIPT

MIC Engineering Practice

EEE & ISE Second Year Electronics Laboratory

D:20121009101956+01'00'

Equipment

ATmega88PA 8-bit AVR microcontroller FTDI UM232R USB-to-serial development module Plugboard Shared ZigBee network controller node and server Small lightbulb XBee OEM RF module on a breakout board

Aims

This activity has a very ambitious deliverable: the implementa-tion of a wireless frequency/voltage/current measuring device.With small changes it could be used, for example, to monitorpower consumption of home electrical appliances. The de-sign includes an AVR AtMega processor. Programming willbe in both Python and C. Writing embedded system softwarein C allows low-level control of the hardware while being muchquicker to write than assembler. In addition you will use anXBee wireless module which uses the sophisticated ZigBee(based on the IEEE 802.15.4 standard) wireless networkingprotocol for low power wireless devices.

The design of this deliverable requires a lot of infrastructureso you will take some short-cuts to enable completion withinthe timetabled sessions. All construction will be on plug-boardto save time, much of the necessary software is given to youas sample code, the ZigBee controller and associated softwarehas already been implemented one controller will be sharedby all the wireless endpoints. All of this is documented on theMIC web-pages and so will be available should you need toreuse part of this design in future project work.

Objectives

After completion of this experiment students will be ableto:-

Prototype electronic systems using plugboard.

Use microcontroller on-chip peripherals: timers, analogueto digital converters and communication ports.

Congure and use serial devices with high-level AT-Commands.

Implement wireless networks with XBee ZigBee modules Design and analyse simple analog interface circuits forembedded systems

Debug hardware and software in embedded systems

Timetable

The experiment is divided up into 4 sessions, roughly corre-sponding to the 4 timetable slots that are available to com-plete it. However, some sessions may take longer than others.Therefore proceed to the next session immediately once youhave completed the previous one fully, or you are likely tooverrun. The four sessions are as follows:-

1. Communication2. Microcontroller Interface3. Embedded Programming4. Networking

To create the wireless frequency/voltage/current measuringdevice, you will spend the rst session conguring the com-

munication of the wireless XBee module. Any serial data thatgoes into the module will be sent to a server module in the lab-oratory, which will forward the data to your computer. Themicrocontroller cannot measure the frequency/voltage/cur-rent of a device directly. Therefore the second session willconsist of analysing the signals to be measured, and designingpassive networks to scale these signals for measurement bythe microcontroller.

The third session will involve the embedded programming ofthe microcontroller in C, to measure and send the data to theXBee module. The fourth session will involve programmingthe networked client application in Python to receive the dataand convert it into sensible values.

EEE & EIE Second Year Electronics Laboratory 1

The Design

IMPORTANT. This lab will require you to access information

provided in the full datasheets which can be found linked on

the MIC handout page. These are PDF documents which will

have navigation links displayed on the LHS of the PDF. If not:

right mouse click on open document in web browser! display

navigation buttons! click second from top of the 4 buttons.

You will need navigation links to nd relevant sections of the

AVR88 datasheet in particular, since it is long.

Key to handout questions:

Q. Questions to help you achieve a working deliverable.

Q* Questions to help your more advanced understanding ofthe design.

Q** Dicult questions for open-ended analysis.

1 Communication

1.1 Introduction

In this rst session, you will connect the wireless XBee moduleup to a computer via a USB adapter module. This connectionwill allow to you to congure and debug the XBee module us-ing programs on the PC before eventually it is controlled byAVR microcontroller. This project will be prototyped on aplug-board, this allows you to make changes easily and pro-vides sucient performance for this application.

In this session you will use the following modules:-

FTDI UM232R USB-to-serial development module. Pro-vides a UART (serial) interface for a computer over USB.

XBee radio-frequency module. Uses the ZigBee/IEEE802.15.4 standard. Operates within the ISM 2.4 GHzfrequency band.

The XBee module is expensive, and has been placed on abreakout board to protect the inputs and provide two statusLEDs. Since the board power derives from the PC USB con-nection, make sure that you carefully check the whole circuit,and particularly the continuity of all power connections, beforeconnecting your circuit to the computer.

1.2 Plugboard Construction

You should be familiar with plug-boards, and the way pinholeswithin them are connected. While creating this prototype, re-member to keep your wires short and neat, and to make gooduse of the dierent colours of wire available to make debug-ging easier. This prototype will be powered from the USB buson the computer, providing a maximum direct current of 500

mA at 5 V. The rst step should be to connect the power railstogether, so modules can be connected to them in a neaterfashion. An example of how this could be done is shown inthe gure 1.

Figure 1: An example of how to connect the power rails atthe edge of the plugboard together.

Important Note: please read Appendix D before attemptingto remove a wrongly placed module or chip. Place the FTDImodule into the side plug-board with its pins straddling themiddle and the USB connector facing the edge. Leave a smallamount of room and place the XBee module in the board. Anexample layout is shown in gure 2 with the XBee breakoutboard positioned in order to avoid covering any more socketsthan necessary.

FTDI ModuleAtMega88

(mountng positon when used in later sectons)

USB

Xbee Module

1 7

pin 24

pin 1

Plugboard (grey areas indicate holes with vertical connections)

Figure 2: An example layout of the FTDI module and XBeebreakout board.

Using data from Appendix C, connect to the plugboard powerand ground rails you connected earlier. Remember that wewant all modules to be powered from the +5V Vcc USB out-put, rather than the low-current regulated +3.3V pins alsoavailable on the FTDI module. This is because the XBeebreakout board contains its own separate +3.3v voltage regu-lator.

1.3 Connecting the XBee module

UART stands for Universal Asynchronous Receiver/Transmit-ter and is a device used for bidirectional two-wire serial com-munications. The XBee & FTDI modules can communicatein this way. The FTDI module is controlled by USB drivers onthe PC which create a virtual COM port for its UART serialcommunication.

2 MIC Engineering Practice

Two wires are needed to connect the transmitter (TX) ofeach module to the receiver (RX) on the other. Connect theFTDI and XBee modules together. gure 3 explains the pinson the XBee breakout board. Pins 5-7 are used for uploadingnew rmware to the XBee module, and will not be used inthis engineering practice. The green LED on the right of theboard indicates wireless packets being sent, while the yellowLED indicates the module's wireless connection status. Asteady light indicates that the module is connecting, whilea ashing light indicates that it is connected to the ZigBeenetwork coordinator, or server.

1 7

XBee

Pin Purpose

1 Ground

2 TX

3 5 V input

4 RX

5 Reset

6 No connection

7 3.3 V output

Figure 3: The pin numbering on the XBee breakout boards.

Conrm that the FTDI and XBee modules are correctly con-nected (Appendix C), then plug one end of the USB cableinto a PC and the other into the FTDI module. The FTDIwill emulate a serial port on the PC, which under MicrosoftWindows is known as a COM port. The USB bus also provides5v power to the XBee module (and later the microcontroller)via the FTDI module Ground and 5v outputs, so through-out this experiment you will not need to supply power to anycomponents externally.

To read and write from the PC over the serial communica-tions link you have created, you need a serial terminal appli-cation. A guide is included on MIC website (`PC communica-tions setup with Termite') with instructions on how to do thiswith the laboratory machines, using the latest version of thefree application Termite. (The built-in windows application- hyperterm - is decient and should not be used).

1.4 Recap

The system you have now built and will test is summarised inFigure 4.

1.5 Debugging

One common problem when using complex hardware and soft-ware, as in this experiment, is debugging. At every stagewhere you rst connect up everything what should you do ifthe system does not work? In the next subsection you will

Xbee module

FTDI module

PC

Termite application

+5v

TX

RX

GND

USB

Plugboard

COM port

Figure 4: System schematic for session 1

setup the conguration of the XBee module. If the setupcommands don't work as stated (no OK response) you havean error - somewhere! This is quite likely. This handout in-cludes help on how to perform test and debug of the hardwarecircuit used in this section as Appendix A.

1.6 XBee Conguration

The state diagram for the XBee module is shown in the g-ure 5.

Transmit

Idle

Sleep Receive

Command

Figure 5: The state transition diagram from the XBee data-sheet.

Once started the XBee module remains within the `Idle' state.To congure the XBee module we need it in the `Command'state. Set up Termite as specied in `PC communicationssetup with Termite', connect it to the correct COM port, waitapproximately a second, press F1 to send three + charactersin quick succession without a terminating newline, and thenpause again for another second or so. This is called an escapesequence, it brings the XBee module to the command state. Ifsuccessful, the letters `OK' should appear on screen. From hereyou can begin to experiment with the `XBee Command Refer-ence Table' provided on the handout web page. This providesa series of AT-commands to debug and congure the XBee

EEE & EIE Second Year Electronics Laboratory 3

AT Check to see if the XBee moduleis responding

! OK ATID Get current PAN ID using the ID

command! 3332 The current PAN ID ATID 0EE2 Set a new PAN ID of 0x0EE2! OK ATID Check that the module received

the new PAN ID! 0EE2 ATWR Write the change to ash memory

on the module! OK

Table 1: An example of how to change the PAN ID of theXBee module. ` ' indicates a command you send to themodule, while `!' indicates a response from the module.

module. If no valid commands are sent in a user-denableperiod, the module returns to the `Idle' state. AT-commandswere originally used to operate dial-up modems. This methodof in-band signalling was used to reduce the number of pinsrequired for communication.

Q* What prevents a continuous stream of datafrom accidentally triggering the escape sequence,and thus placing the XBee module in `Command'mode?

For example to change the PAN ID (Personal Area NetworkIDentication), which identies the local wireless network towhich the module will try to connect, the following instruc-tions would be performed in the `Command' state, with theassociated responses, shown in table 1.

Summarised, the syntax for AT-commands is as fol-lows.

AT prex + ASCII command + (Optional) Space +

(Optional) Hexadecimal parameter + Enter

To read the value of a command, you omit the parameter.Conrm that the serial port is congured correctly, enter`Command' mode and record the serial number (or MAC ad-dress (Media Access Control)) of your XBee module. Thisserial number is 64-bits long, which is longer than the param-eter length of 32-bits, hence it's split into two commands. Ifyou look at the data-sheet, the upper 32-bits can be found bytyping ATSH, while the lower 32-bits can be found by typingATSL.

To proceed with the experiment, set the PAN ID to the 16-bithexadecimal value displayed on the MIC handout web page andthe destination address to the 64-bit hexadecimal value 00000000 0000 0000. Ensure that `join notication' is enabled

(ATJN1), so the ZigBee coordinator is informed when yourdevice joins the wireless network.

1.7 XBee Communication Testing

For this engineering practice, a single XBee module has beencongured within the laboratory to act as a server. This willact as a networked serial terminal. Any data sent to it fromyour XBee module will be forwarded to the client console appli-cation called micclient.py available from the skeleton codedownload on the laboratory website.

Start the client software up from a command window, notethat mac must be replaced by the 16 hexadecimal charactersof your MAC address.

python micclient.py mac

Congure your windows so that you can see both Termiteand the output window of MICClient simultaneously. Set theXBee to the `Idle' state by exiting the `Command' state andproceed to type a random test string. With luck, this shouldappear on the client window. Your random string is beingsent from your laboratory computer, through a wireless link,then a wired connection back to your computer, as seen ingure 6.

XBee ModuleZigBee Device

XBee ModuleZigBee

Coordinator

MIC ClientMIC Server

UART (USB)

ZigBee (2.4 GHz)

UAR

T (U

SB)

TCP/IP (Ethernet)

Remote Shared Server Laboratory Computer

Serial Terminal

Figure 6: The data-path for serial communications over thewireless network.

Q*. Looking at the server output, is your randomtest string sent in a single packet? With referenceto the XBee datasheet, what additional data is sentwith each packet? How does the value of the `pack-etization timeout' aect what is sent?

Now you have congured and tested your Xbee write the con-guration to the ash memory of the module so it will beavailable in your future work. Make a note of the Zigbeemodule number in case it gets swapped - if this happens youmay need to recongure it.

4 MIC Engineering Practice

1.8 Session 1 Deliverables

You should have the Xbee and FTDI modules connected andworking on a plugboard. You should have congured the XBeefor PAN ID, ATJN1. You should have recorded the MACaddress of your module, and also its number (so you can detectif somone else swaps it!). You will need this information inthe last session.

You should have been able to run the client application (youdo not however need to understand the code). You should beable to send data, using Termite, via your XBee module tothe server and receive it using the client software.

Having nished this rst section, which normally takes lessthan one lab session, please immediately start Section 2. theexperiment as a whole is quite long and you will appreciatemore time at the end to test the programming.

2 Microcontroller Interface

2.1 Introduction

In this session we will look carefully at how to interface ana-log signals to a microcontroller. The XBee module includesits own microcontroller on-board which in theory could alsobe used to conduct measurements, however this implementsthe ZigBee protocol and in practice a two-processor designin which an external microcontroller communicates with theXBee module is nearly always preferred.

The Atmel ATmega88PA is an 8-bit AVR microcontroller,with a built-in programmable ash and various peripheral de-vices. We will be using the PDIP (Plastic Dual In-line Pack-age) form of this microcontroller for easy mounting on plug-board other versions are available for more compact imple-mentation on a PCB.

The work to be completed is:

Examine the passive device whose power usage you willbe monitoring.

Design the analog circuits to interface circuit current, fre-quency, and voltage to the microcontroller pins for mea-surements.

Implement the circuit on the plug-board. Test the completed circuit with a `sample' microcon-troller hex (compiled program) le which outputs digi-tised samples over the microcontroller serial port.

For this session, the XBee module will not be used. Keepit on the bread-board to protect its pins, but disconnect theTX and RX wires between it and the FTDI module. Notethat the FTDI module will be used to provide power to theATmega88PA microcontroller in the same way as it did to the

XBee module in session 1. For the nal part of the session,the sample hex le output will be sent to the FTDI moduleand can then be viewed on a PC using Termite.

2.2 Passive Device Characteristics

For this activity the passive device to monitor will be a light-bulb, powered by a function generator. To measure the cur-rent owing through the bulb, a Current Sensing Resistor(CSR) should be used as shown in gure 7. To use the reso-lution of the ADC circuitry on the microcontroller eectively,we need to analyse what voltages we can expect to mea-sure.

1 Ω

Bulb Voltage CSR Voltage

Figure 7: An example light-bulb circuit with a Current SensingResistor (CSR).

Instead of using mains voltage, we will use a function gen-erator to emulate a low-voltage, sinusoidal mains frequencypower supply at 50 Hz and maximum amplitude with no DCbias. (This will typically be 12 Vpp, or 4VRMS, however eachsignal generator varies). Connect the bulb as a load to thefrequency generator. IMPORTANT NOTE, for this section,and throughout the lab:

The signal generator is connected directly to the lightbulbhas shown in gure 7 and is (usually) set to its maximumoutput voltage.

The signal generator output will be less than its no load20V due to loading by the lightbulb. This is not a prob-lem.

The signal generator is NOT connected to the microcon-troller or FTDI VCC. If you do this you will surely breakit.

The microcontroller and FTDI ground connection willhowever be connected to ground in gure 7.

The other circuit components: FTDI, Xbee and AVR,are all powered from the USB supply to the FTDI. Thismeans their +5v or Vcc power rails are connected as aretheir ground rails.

the lightbulb circuit should not be altered from that givenin gure 7.

You must assume voltages in range 0.5VRMS - 4VRMS,current in the range drawn by the lightbulb between thesevoltages, and frequency in the range 40Hz - 400Hz. Your

EEE & EIE Second Year Electronics Laboratory 5

nal deliverable should operate correctly throughout thisrange.

Use an oscilloscope to quickly measure the maximum and min-imum of the sinusoidal voltage and current of the light-bulb(Note: the voltage across the CSR gives the current throughthe light-bulb) .

2.3 ADC and Comparator Interface De-

sign

There are three statistics that we wish to record using the mi-crocontroller: current, frequency and voltage. To measure thecurrent and voltage you should use the Analogue-to-DigitalConverter (ADC) internal peripheral of the micro-controller.This comprises a single 10-bit successive approximation ADCwith a sample/hold circuit, whose input is connected via ananalogue multiplexer to any one of multiple input pins.

An ADC will perform analog to digital conversion over a givenspecied voltage range, e.g. 0-1v. The digital output for agiven voltage is scaled so that (in this case) 1v representsthe maximum possible (unsigned) output and 0 the minimumunsigned output. Thus for a 10 bit ADC these digital valueswould be 1023 and 0 respectively. For the ADC to work asingle reference voltage Vref is used inside the microcontrollerwhich provides the top of the specied range for all ADCmeasurements. Vref is software selectable to be connectedto be one of: Vcc, an internal xed reference voltage (seedatasheet for value) or an external pin which can with suitableexternal circuit provide a custom reference voltage value. Thereference voltage Vref (whichever is selected) thus denes thetop end of the voltage range. The bottom end is always,for most microcontrollers, zero. This is called single-ended

voltage measurement, it is also possible to use double-endedvoltage measurement in which there are two input pins and it isthe dierential voltage between these pins which is measured,but not using the AtMega88 ADC.

The microcontroller also has an internal analogue comparator

available for use. This provides a digital output of 0 or 1according to whether the voltage between its two input pinsis positive or negative. If one pin is attached to a xed externalreference voltage (not to be confused with the ADC Vref) theother provides a digital threshold function. You will learn laterhow to use this to measure frequency.

Microcontrollers are relatively fragile devices, therefore it isimportant to protect their input circuitry. The I/O pins of theATmega88PA have clamping diodes, which protect againstvoltages higher than the supply voltage to the microcontroller.We are powering the device with a 5 V supply, therefore pinshave a possible maximum tolerance range of 0 5 V. Be-cause high currents in the clamp diodes will break them andthe the device this means that currents from voltage sources

potentially above 5V or below ground must be limited to 1mAmaximum.

Hence you will need to match the voltages you measure to thecharacteristics of the microcontroller. Measurements must besingle-ended, referenced to ground. You may assume the sig-nals to be measured are symmetrical, so it is only necessaryfor you to measure the positive half, although you must takecare as above that negative signal excursions do not break thedevice. The possible voltage range you are measuring mustbe scaled so that it lies in the ADC range (0 - Vref). Notealso that if you are able to use more of the (0 - Vref) rangethe digital output will be more accurate, because quantisationerror is less. Finally, using a small measurement range, witha low Vref value, will lead to input noise error voltage fromdigital signals in the microcontroller being larger. These re-quirements together will determine how you scale the inputs.To make your design task easier we have given you a suggestedcircuit in Figure 8 which supplies the necessary external volt-ages for both the comparator reference pin and the two ADCinput pins. The comparator voltage input can be driven fromthe same signal a one of the ADC inputs, thus saving externalcomponents. It is suggested that you use this circuit, withsuitable calculated values. You are free to change the circuit,giving reasons, but this should be attempted only after theentire experiment is working, if you have time.

Bulb

AC

To micro-controller

GND

+5v

CSR 1Ω

R2

R3 R5

R6

D1

R4

Figure 8: Analog interface circuitry

Q. For the ADC to work, a single reference volt-age needs to set for the top of the voltage scale forall ADC measurements. What voltages, from thedatasheet, can be used?

6 MIC Engineering Practice

Q*. Given your choice of reference voltage and theresolution of the ADC, what input voltage does asingle binary bit represent? (Refer to your DigitalElectronics 2 notes if you don't know how to cal-culate this). What integer values will the microcon-troller report for the maximum voltages across thebulb and the CSR?

Q. What is the purpose of R2? What is the mini-mum allowed value for R2. How does this change ifyou assume that due to bad wiring the CSR resistormight become disconnected?

Q. What is an estimate of the minimum allowedvalue of R3 || R4?. How does this change if you as-sume that due to bad wiring the CSR resistor mightbecome disconnected? Are there any other factorsthat would make a very large or small value for theseresistors undesirable?

Q* Is D1 required?. How does D1 aect your cir-cuit's design and accuracy? What would be the con-sequence of moving D1 to the output of the R3/R4potential divider?

Q. R5/R6 provide a reference for the comparatorreference input. This cannot be zero because thecomparator will not work well with inputs very closeto either supply. What factors aect the value youwould choose for this voltage. What factors af-fect the minimum and maximum desirable value ofR5||R6 - note that this can be chosen independentlyof the voltage.

Q* Throughout the circuit design consider whetheryour resistor values need to be precise, or if impre-cise what are the aects of error. (Normally, analogciruits can be designed such that a 10% error in anyresistor is permissable, and laboratory available val-ues may therefore be used). Distinguish betweenresistors precisely known but not able to be preciselychosen, and resistors imprecisely known. You shouldassume that all lab resistors have 2% tolerance, fur-ther accuracy can be got through manual measure-ment.

2.4 Hardware Implementation

You should now have a complete diagram of the circuit sur-rounding your microcontroller. Before implementing, it mightbe wise to check with a demonstrator that your design issound.

To implement the nal design you should have already re-moved the serial link between the XBee module and the FTDI

module. Keep the XBee module on the plug-board for safe-keeping. Place the microcontroller in the centre of the plug-board.

Wire up both power supplies and ground to the microcon-troller, and implement your circuits. Include a decoupling ca-pacitor to reduce power supply noise between the input volt-age pin and the ground pin of the microcontroller. Attach theFTDI to the microcontroller via the TXD and RXD pins in asimilar way as before. This allows you to use the PC to test& debug the microcontroller serial output and program themicrocontroller with your custom rmware.

To program the microcontroller, you must also to include a re-set circuit. Implement the circuit as shown in gure 9.

FTDI Module

AtMega88 micro-

controller DTR RESET

10k 100k

+5v

33nF

Figure 9: The reset circuitry required for reprogramming themicrocontroller.

A `sample microcontroller hex le' is available from the MICwebsite, should you wish to test your hardware implementa-tion with a functional executable. Follow the instructions insection 2.5 to program the microcontroller with this hexadec-imal le.

2.5 Using the Bootloader

The ATmega88PA microcontroller uses a bootloader, whichhas already been installed on the chip for you. The bootloaderallows you to program the chip without any external hardware,other than the reset circuit you built earlier from gure 9, usingthe serial port.

Once you have compiled your code into a hexadecimalrmware image, you load it onto the microcontroller usingan application called AVRdude. This is a command line appli-cation, and the below procedure is used to program the AT-mega88PA. Before you can continue, you must download andextract the required les (`skeleton microcontroller C code')you will be using for the rest of this lab.

To upload your compiled rmware image (hex le) to the de-vice, a small commandlet has been written to make it easierfor you. Launch a terminal window (cmd.exe) and changeinto the default directory inside the archive you extracted.Inside that you will nd micprog.cmd and a micsample.hexrmware image. An example of a console window sessionto do this is shown in listing 1. Do the same, substituting

EEE & EIE Second Year Electronics Laboratory 7

the paths for wherever you extracted your `Skeleton Micro-controller C Code' and COM3 for your serial port (Note: thenumber of the serial port can change, use the `PC commu-nications setup with Termite' guide if you need to check youhave the correct value).

C:\ >h :H:\ > cd l a b s \MICH:\ l a b s \MIC>cd d e f a u l tH: \ l a b s \MIC\ d e f a u l t >micp rog COM3 micsamp le . hex

Listing 1: An example console session to write the rmwareto the microcontroller. The paths and serial port shown canbe dierent.

The micprog.cmd script is a wrapper around the followingAVRdude command, shown below. If you are writing thermware from your own machine, use the following com-mand.

avrdude -D -p m88 -c arduino -P COM3 -b 19200-v -U flash:w:micsample.hex

The ATmega88PA must be reset in order to prepare the boot-loader each time you program, this is done using the resetcircuity specied in section 2.4 and gure 9 which is activatedby AVRdude. If you get a `sync' error, this circuit has failed.You should try connecting and reconnecting the FTDI USBlead, if this does not work then the problem is one of:

the connections betwen FTDI and AVR, including theRESET circuit

a broken AVR88 chip.

2.6 Section 2 Deliverables

At the end of this session you should have designed and im-plemented on plugboard a circuit to interface the lightbulbmeasurements to the AtMega. You should have successfullydownloaded and run a hex le containing a sample programwhich sends characters out from the AtMega UART, and re-ceived those characters via Termite on the PC.

3 Embedded Programming

3.1 Introduction

This section focuses on the embedded software, or rmwareside of the ATmega88PA microcontroller. Along with theactual processor, the microcontroller contains a number ofperipherals including an ADC which we will be using to takeour measurements. It also includes a programmable serial

UART (Universal (synchronous and) Asynchronous serial Re-ceiver and Transmitter) for you to use to send data to theXBee module.

Upon completion of this session you will have a working mea-surement system, taking readings from the light-bulb and out-putting these using the serial port peripheral. The XBee mod-ule provides a transparent wireless link, allowing you to simplyreplace the FTDI module with the XBee module to make thesystem wireless. However in this session, we will not use theXBee module, and instead see the results from the microcon-troller using a serial terminal such as Termite.

The majority of the code is provided, so the focus of yourwork will be to decide how the peripherals should be operated,and congure them appropriately.

In this session you will:-

Learn about microcontroller peripherals and how they arecongured and used.

Become familiar with Atmel Studio as an environmentfor the development of embedded-C applications.

Use the bootloader to program the compiled softwareonto your microcontroller.

Produce a microcontroller application which measuresthe voltage across, current through, and period of a load,outputting the data through a serial port.

3.2 Microcontroller Peripherals

In order to take the frequency/voltage/current measurementsand output them on the serial port, you will need to make useof the ATmega88PA's internal ADC, timer, comparator andUART peripherals. The UART conguration and operationhas been provided for you.

You will need to refer to the relevant sections of the micro-controller datasheet, for background information, as well asspecics, while working through the implementation. Notethat the very long datasheet PDF has a useful table of con-tents, and that bookmarks to sections and subsections areavailable in the online PDF.

Section 3.3 provides an overview of how to use the internalperipherals, section 3.4 provides a detailed walk-through ofthe sample design with notes on what you need to congureto make this operational. Section 3.4 should be read in con-junction with the sample code which shows where you needto make changes.

3.3 Background theory

The next few sections describe in general how embeddedprograms use on-chip resources, you can using it as a ref-

8 MIC Engineering Practice

erence when implementing the software required in Sec-tion 3.4.

3.3.1 Libraries

The embedded programming for this activity will rely heavilyupon AVR Libc. This provides a subset of the standard Clibrary and the startup code needed for Atmel AVR 8-bit mi-crocontrollers. A helpful FAQ (Facts And Questions) page isavailable under the documentation at the AVR Libc website athttp://www.nongnu.org/avr-libc/. This library includesseveral standard routines for dealing with interrupts and typeconversion amongst many other useful utilities.

To perform UART communications, this activity will also beusing the Procyon AVRlib, which provides formatted printfunctions and interrupt driven serial communications amongvarious other functions.

3.3.2 Interrupts and ISRs

An interrupt is an asynchronous signal sent to the microcon-troller that changes the program counter to execute the asso-ciated Interrupt Service Routine (ISR) on the next clock-cycle.Once the interrupt has been serviced, the microcontroller re-sumes execution of the code that was interrupted.

It is possible to prevent interrupts occurring by using a specialCPU instruction. Due to the ATmega88PA being an 8-bitmicrocontroller, operating with variables larger than 8-bits re-quires more than one instruction, and so an interruption whilein the middle of processing a 16 bit quantity which is usedby the code running in the associated ISR may corrupt data.Temporarily disabling interrupts around the code which wouldbe problematic can prevent this.

The AVR Libc provides a convenient method of using inter-rupts, as shown in listing 2.

#i n c l u d e <av r / i n t e r r u p t . h> // d e f i n i t i o n s

ISR (ADC_vect ) // f u n c t i o n w i l l r un on i n t e r r u p t

// u s e r i n t e r r u p t s e r v i c e r o u t i n e

main ( ) // u s e r code run from main

// o t h e r code

c l i ( ) ; // d i s a b l e i n t e r r u p t s

// code wh ich must not be i n t e r r u p t e d

s e i ( ) ; // e n a b l e i n t e r r u p t s

// o t h e r code

Listing 2: An example of an Interrupt Service Routine (ISR)for the ADC in C.

3.3.3 Measuring AC Voltage & Current

The external hardware for the measurement of these valueshas already been designed and implemented by yourself in thesecond session. This may require some further tuning to im-prove performance later in the activity. We assume single-ended measurement with the AC waveform symmetrical aboutzero. Therefore it is necessary only to detect the maximumwaveform value.

The voltages (across the bulb supply and the current sens-ing resistor) are sinusoidal. The ADC is congured to takethousands of readings every second. In order to calculate thepower we would like to measure the peak value of these. Thecode you are given nds the overall maximum over many cy-cles, which is simple and works.

A more sophisticated way to compute peak value is to ndthe maximum of these separately for each cycle of the sinewave. The Python pseudocode in listing 3 shows how.Process_new_value() here is assumed to be run wheneveran ADC measurement is made.

min imum_thresho ld = 2adc_max = min imum_thresho ld

de f process_new_va lue ( ) :i f ( new_value > adc_max ) :

adc_max = new_valuei f ( new_value <= min imum_thresho ld ) :

ou tpu t adc_max ; // w i l l happen once pe rc y c l e

adc_max = min imum_thresho ld

Listing 3: Example pseudocode for peak detection in asequence of ADC measurements, assigning the peak value tothe adc_max variable.

The algorithm in listing 3 outputs the stored maximum valuewhen the current value (i.e. the voltage across the CSR) fallsbelow a threshold, this is used to nd a point denitely afterthe sine peak. The minimum threshold value may require sometweaking to take into account noise in the circuit: it must belarger than the lowest sample during a cycle, but smaller thanthe lowest peak sample over a cycle..

Q* Assume that electrical noise in the range 1-50mV, depending on circuit construction, is presentat the ADC inputs. How does the electrical noise er-ror compare with the absolute accuracy of the ADC(refer to the datasheet)? How does this aect yourreadings? Would calculating a moving average (ofthe last N samples) increase the accuracy? What de-termines the maximum value of N? How could youimplement this?

EEE & EIE Second Year Electronics Laboratory 9

Count: 8 9 10 11 12 13 14 15 16 17 18 19

Capture: old value 13 13 13 13 13

main code

AIN0

AIN1

Output

Comparator:

Timer:

Microcontroller:

ISR

main code continues

Time

Figure 10: Sequence of events to capture comparator transi-tions

3.3.4 Measuring Period

The period is measured using a combination of the AnalogueComparator and the 16-bit Timer/Counter1. The comparatoris congured with the signal input connected to AIN1, withAIN0 connected to appropriate xed voltage level. When thevoltage on the AIN1 pin goes above that of the AIN0 theanalog comparator output is set. This signal is routed toTimer1 capture, which stores the exact value of the timercount register when the event occurred as the capture value.this sequence of events is illustrated in Figure 10

The Timer1 capture value can then be used to calculate theperiod. The rate at which the timer count increments is de-termined by the `prescaler', which divides the microproces-sor's clock frequency by a preset value. The time betweensuccessive increments is called the tick time. The micropro-cessor clock is derived directly from a calibrated internal RCoscillator on the microprocessor is set to 8 MHz, assumingthe CKDIV8 fuse is not programmed, therefore providing an 8MHz clock to the time prescaler. The period in numbers ticksis calculated using the algorithm in listing 4.

timer_max = 2**16new_timer_count = t imer_countp e r i o d = new_timer_count o ld_t imer_countp r i n t p e r i o d

Listing 4: Example Python pseudocode to measure the period,when it overows the 16-bit new_value variable.

The Timer1 capture value is only 16 bits, and it will increaseby 1 each clock tick returning to zero only when the valueoverows. The algorithm in listing 4 relies on the timer over-owing no more then once for each period measurement. TheTimer1 prescaler must be congured so that this condition ismet for the operating frequency measurement range.

Q. Choose a possible value for the timer prescalerfrom the device datasheet and work out the tick fre-quency. What measurement periods (in numbers ofticks) would you expect for an input signal of 50 Hz?Note that the timer count is a 16 bit quantity: whatis therefore the maximum period that can be mea-sured with your chosen prescaler value? If necessarychoose a dierent value to ensure that the requiredfrequency range can be detected.

Q*. The timer count will wrap round to 0 after216 1. What error could this cause in the value

of period? Does this matter? Note that the C intdatatype on the AVR a 16 bit quantity.

3.3.5 Microcontroller Peripheral Conguration

Microcontroller peripherals are connected to the processor us-ing special memory locations called registers. These can bedivided into two main types:-

Data Registers contain data, usually from the periph-eral.

Status and Control Registers used to congure the pe-ripheral and control them from the application.

These locations have names dened in C header les and canbe read or written just like normal variables. The peripheralsare congured by setting or clearing bits within these registers.The gure below shows ADMUX, the `ADC Multiplexer Se-lection Register'. This register is used to specify which ADCinput is used, which voltage reference, and if the data outputinto the data registers is left or right adjusted.

Note that the initial (reset) value for all of the register bits is 0,so if you do not want to set a bit, nothing needs to be done (solong as it has not been set elsewhere). ADMUX is an exampleof a peripheral control register. It may be read or writtenlike a memory location except that it has the side eect ofcontrolling some aspect of the ADC operation.

AVR Libc links all of the names used in the datasheet, to thephysical locations of memory within the device, so that ratherthen specifying the ADMUX register as 0x7C we can simplyrefer to it as `ADMUX'.

10 MIC Engineering Practice

2628161D–AVR–10/09

ATmega48PA/88PA/168PA/328P

23.9 Register Description

23.9.1 ADMUX – ADC Multiplexer Selection Register

• Bit 7:6 – REFS1:0: Reference Selection BitsThese bits select the voltage reference for the ADC, as shown in Table 23-3. If these bits arechanged during a conversion, the change will not go in effect until this conversion is complete(ADIF in ADCSRA is set). The internal voltage reference options may not be used if an externalreference voltage is being applied to the AREF pin.

• Bit 5 – ADLAR: ADC Left Adjust ResultThe ADLAR bit affects the presentation of the ADC conversion result in the ADC Data Register.Write one to ADLAR to left adjust the result. Otherwise, the result is right adjusted. Changing theADLAR bit will affect the ADC Data Register immediately, regardless of any ongoing conver-sions. For a complete description of this bit, see ”ADCL and ADCH – The ADC Data Register” onpage 265.

• Bit 4 – Res: Reserved BitThis bit is an unused bit in the ATmega48PA/88PA/168PA/328P, and will always read as zero.

• Bits 3:0 – MUX3:0: Analog Channel Selection BitsThe value of these bits selects which analog inputs are connected to the ADC. See Table 23-4for details. If these bits are changed during a conversion, the change will not go in effect until thisconversion is complete (ADIF in ADCSRA is set).

Bit 7 6 5 4 3 2 1 0(0x7C) REFS1 REFS0 ADLAR – MUX3 MUX2 MUX1 MUX0 ADMUXRead/Write R/W R/W R/W R R/W R/W R/W R/WInitial Value 0 0 0 0 0 0 0 0

Table 23-3. Voltage Reference Selections for ADCREFS1 REFS0 Voltage Reference Selection

0 0 AREF, Internal Vref turned off

0 1 AVCC with external capacitor at AREF pin

1 0 Reserved

1 1 Internal 1.1V Voltage Reference with external capacitor at AREF pin

Figure 11: ADMUX The ADC Multiplexer Selection Register, taken from page 262 of the ATmega88PA datasheet.

3.3.6 ADC example conguration using macros

Firstly we will write code to set which ADC input pin is mea-sured by conguring the ADC multiplexor (MUX). This is theleast signicant 4 bits of the ADMUX register. Following thedatasheet, if you want to measure input ADC4, ADMUX(3:0)should be set to 0b0100 or 4 in decimal, an example of whichis shown in listing 5. Note that 0b prex designates a binaryconstant.

ADMUX |= (0 b0100 ) ;

Listing 5: Example of setting the ADMUX register to 0x7Cin C with the AVR Libc library.

To set (for example) the ADC voltage reference to use AVcc,we follow the datasheet to set REFS(1:0) to 0b01. The 2REFS bits are most signicant within ADMUX, thus AD-MUX(7:6). Four dierent ways of doing this are shown inlisting 6, note that in C:

« denotes a shift operation used to align the eld value0b01 with the (7:6) bits within the register

|= denotes a binary OR operation which will preserve thevalues of all other bits in the register while setting thosewhich are non-zero on the RHS.

ADMUX |= 0b01000000 ;ADMUX |= (0 b01 << 6) ;ADMUX |= (1<<6) ;ADMUX |= (1<<REFS0) ;

Listing 6: Four methods of setting the same ADC referencevoltage in C with the AVR Libc library.

To make this setting of bit elds easier, a number of macroshave been dened in the source code, as shown in listing7.

// Va lue w i t h 1 i n b i t l o c a t i o n n

#d e f i n e _BV( n ) (1<<(n ) )

// Set b i t s 1 i n x wh ich a r e 1 i n y

#d e f i n e SETBIT( x , y ) ( x |= ( y ) )

// Set b i t s to 0 i n x wh ich a r e 1 i n y

#d e f i n e CLEARBIT( x , y ) ( x &= ~( y ) )

// Re tu rn s 1 i f any o f b i t s s e t to 1 i n y a r e 1

i n x

#d e f i n e CHECKBIT( x , y ) ( x & ( y ) )

Listing 7: Four included C macros to make setting individualbits easier.

Using these macros, the three bit elds of ADMUX, REFS,ADLAR, and MUX, as shown in gure 11 from the datasheet,can be separately congured for example as in listing 8.

SETBIT(ADMUX, 0b0100 ) ; // s e t MUX f i e l d to 0

b0100

SETBIT(ADMUX, _BV(ADLAR) ) ; // s e t ADLAR one b i t

f i e l d to 1

SETBIT(ADMUX, (0 b01<<REFS0) ) ; // s e t REFS f i e l d

to 1

Listing 8: An example of conguring the ADC in C.

3.4 Implementation

3.4.1 Programming

The rmware, once complete, will output a comma-delimitedstring containing the value of the rst ADC followed by thesecond, then the period. These values will be the raw val-ues in the registers converted to decimal (hence the %d inthe rprintf call) for sending across the serial link. In thenext session we will convert these values into something read-able.

To edit, compile and download the rmware, follow the in-structions in Programming for MIC on the handout web page,to nd bugs, check Appendix B.

The provided project contains a le main.c which containsa sample program which will make repeated ADC samples,process the results, and send them via Zigbee wireless to thecommon network controller. From there you can access themthrough the laboratory LAN and your PC.

The sample program contains detailed instructions on whichparts need to be congured by you, and how to congurethem, for a minimal working deliverable. Read this care-fully. Code you need to change is agged with a /*** com-ment. The minimum conguration required, in source leorder, is:

Congure ADC input pins, prescaler, reference. Cong-ure timer prescaler and clock.

EEE & EIE Second Year Electronics Laboratory 11

Setup Analog Comparator (for period measurement).

Setup Timer1 to capture based on comparator outputtransition (see datasheet).

Compute waveform period from old and new capture val-ues in the TIMER1_CAPT_VECT ISR.

Write to ADCSRA to enable ADC and start ADC con-version (see datasheet).

Write to ADCSRA to clear ADIF bit (see datasheet).

Note that the main code, in initial form, is complete andworking. It needs no change other than as above.

See main.c for details. Rebuild the project to create thermware image as le defaultMIC.hex. In the next section, you will use the bootloader towrite your compiled code to the microcontroller's built-in ashmemory.

Q*What happens if you do not reset the ADIF bit inget_adc()? How does the ADCSRA register behavedierently on read and write from a normal memorylocation?

Q* Why are the cli() and sei() functions used inthe code? What would possibly happen if they wereremoved?

If you require any further help, ask one of your demonstra-tors.

3.4.2 Testing your code

See section 2.5 for how to load a hex le, generated fromyour C project, onto the microcontroller. After the le hasbeen successfully loaded the int main(void) function willrun and, if all is well, produce output. You can debug yourcode by running Termite and connecting it to the FTDI USBport as you've done previously (see `PC communications setupwith Termite' guide) - note that you cannot connect Termiteand AVRdude at the same time. The rprintf statementsin the source code will print via the serial port and thereforeappear in the Termite window. If the code does not work asintended then extra rprintf statements can be added tohelp with debugging (these should be removed or commentedout once the correct output is achieved). Please ensure thatTermite is displaying the expected outputs from the micro-controller before proceeding to the next section.

Appendix B should be read carefully if you have problems get-ting your own code to load to the microcontroller or run cor-rectly.

3.4.3 Unexpected Errors

Circuits combining digital and analog processing often result innoisy analog signals that lead to signicant errors. How theseerrors are handled by software can then make very complexbehaviour.

This especially so for the period measurement since this relieson waveform edge detection by a comparator.

Q* Do errors in period measurement appear moreoften at high or low AC source frequencies? Canyou explain this behaviour? Can you explain the errorvalues?

One tip is to add decoupling capacitors across the micropro-cessor supply, analog supply, and reference inputs to reducenoise, and then to lter the pins used as ADC inputs withappropriate sized capacitors. Complex investigation of errorsshould be delayed until you have completed the entire experi-ment.

3.5 Session 3 deliverables

At the end of this session you should have been able to com-pile, download and test the skeleton C le for MIC. You shouldhave modied this (slightly) to make it work with the interfacecircuits you built in the last session. You should be able totest the ADC measurements by observing characters transmit-ted via serial port to Termite, and the transmitted numbersshould be roughly what you expect when measuring a 50HzAC waveform. You should have written and tested code tomeasure the waveform period.

4 Networking

4.1 Introduction

By the end of this section you should end up with a functionalwireless frequency/voltage/current measuring device for thelight-bulb. When the values you are receiving across the seriallink between the microcontroller and FTDI module are correctredirect the serial communications from the FTDI module tothe XBee module. Therefore instead of sending the voltageand frequency readings to Termite over the serial line, you willbe sending them via a wireless link to the server. From thereyour PC-based client software will receive the data, where youcan convert the values back into human-readable units.

12 MIC Engineering Practice

4.2 Final Wiring

Connect the RX, TX lines so that the AtMega88 connectsto the XBee module (see Appendix ??). Preserve all supplyconnections, and keep the FTDI module: its function now isto supply 5V from USB to the rest of the circuit. In a realwireless sensor it would be replaced by a battery.

4.3 Client Software Connection

The micclient.py script you ran in section 1 will be modi-ed to convert the incoming text into something more read-able. The script is in the Python programming language, ageneral-purpose high-level programming language. This is aninterpreted language, hence you do not need to compile yourcode.

To check that everything is working, connect your power mon-itor up to the signal generator and light-bulb box as before.Check the number that the number of your XBee module isas before, in which case you may use our previous record ofthe MAC address. Otherwise you must measure this again asin the session 1.

Open the client software, micclient.py, using Pyscripter. Usethe handout page quick start guide if necessary. Note thatto run micclient.py with the MAC address as command lineparameter you must enter this in Pyscripter under:

run->command line parameters

Run micclient.py under Pyscripter (see the guide on the hand-out page for help) and connect to the server as in session 1.You should now be receiving the serial data from the micro-controller.

If not, then check your RX and TX wires, or disconnect the USBpower and wire the microcontroller back to the FTDI moduleagain to check with a serial terminal that your microcontrolleris functioning correctly.

4.4 Client Software Walkthrough

Walking through the source code, a couple of libraries areimported followed by the parseValues function. The appli-cation when run rst checks for a command-line argument.If one exists, it assigns its value to the xbee_mac variable.It then attempts to create a network socket connection tothe server, where it sends the word CONNECT concatenatedwith the provided hexadecimal MAC address. At this point,the server disconnects the client if the serial number is in-valid.

The socket is then used to create a le object, to make readingdata from it easier. Then the script enters the main, never-

ending loop of operation. This loop checks to see if any datais available for writing to the screen. Once data arrives it isbuered until a newline character is seen. Then the buer isconverted into a human-readable string by the parseValuesfunction and printed to the screen. A few exception handlingroutines at the end of this loop quit the script in the event ofany network errors.

You have been given two versions, micclient, and micclientgui.The latter includes a GUI but performs the same function.You are free to use either for testing, and to modify eitheras required below to output your measurements, however thenon-GUI client is simpler and the description here assumes youuse this.

If you are doing this experiment rst (before MAT) expect toget signicant help from GTAs with python programming ifneeded.

4.5 Parsing Values

To process the raw integer values into values a user can moreeasily interpret, a function at beginning of the script has beenincluded for you to edit. The code for this function can beseen in listing 9.

de f p a r s eV a l u e s ( l i n e ) :v a l u e s = l i n e . s p l i t ( ' , ' )

# Attempt to r ead the s p l i t v a l u e s

t r y :adc0 = v a l u e s [ 0 ]adc1 = v a l u e s [ 1 ]p e r i o d = v a l u e s [ 2 ]

e x c ep t I n d e x E r r o r :# Er r o r r e a d i n g v a l u e s , r e t u r n the l i n e

r e t u r n l i n e

r e t u r n adc0 , adc1 , p e r i o d

Listing 9: The included Python function to take a line andsplit it into 3 values before returning the values as a string.

The code in listing 9 takes the line read from the le objectdata, and then splits it using a comma character (,) as a de-limiter. Then we enter a `try except' block (otherwise knownas an exception handler), which tells the interpreter to tryand read the split values. If this fails with the IndexErrorexception, the line is returned unedited. This suggests thatthere were no values present at the indices requested. It wasthe functionality used in session one when you tested Zigbeecommunication.

Modify this function to scale the input values you have, know-ing the resistances you used in your passive network design toconvert the raw integer values back into volts (V), milliamps(mA) and hertz (Hz).

EEE & EIE Second Year Electronics Laboratory 13

To experiment with the interactive Python interpreter, usePyscripter as described in the Python programming documenton the handout page.

Add another function to calculate the power used by the bulbin milliwatts (mW), and present this on the screen.

Q* Given the tolerances of the components youused, and the accuracy of the ADC converter withinthe microcontroller, what is the overall tolerance ofyour power measuring device for a 10Vpkpk input?

Q** The Zigbee network is arranged as a mesh, inwhich end-point devices may communicate with thenetwork controller either directly or through routers,according to what is in range. Each end-point devicecan serve as a router for this mesh communication.Because of meshing, and also packetisation over-head, and also lost packet overhead (necessitatingretransmission) Zigbee networks have a much lowerpractical data rate between endpoints and controllerthan the physical rate of 500kbits/second. Explorethese overheads for the laboratory network. Esti-mate, stating any assumptions, the practical datarate you would expect if all nodes are transmittingsimultaneously? How does this radio link constraintcompare with the maximum server data bandwidthgiven that data packets are received by the controllerover a 115kBaud serial link (Baud = bit/second)?

4.6 Session 4 deliverables

At the end of this session you should have interfaced yourworking measurement circuit and microcontroller to the XBeemodule for wireless operation. You should have been able toreceive the transmitted characters via the client software, andmodied the client to correctly display your measurements ina nicely readable form.

You will notice that getting an initial working embedded sys-tem design is surprisingly complex, and a rewarding mixtureof hardware and software. The real fun then starts when youmeasure and analyse the performance of your design. Doesit work well? If not, what is the cause of the errors? Howcan circuit changes, or clever software, reduce errors? Thesequestions are dicult to answer but can usually be solvedwith a mixture of clever analysis and investigation throughmeasurement.

Congratulations on completing this complex practice designexperiment.

A Debugging the PC to XBee connec-

tion

A list of things that may go wrong is shown in Figure 12.With so many possibilities to check, and no certainty each isxed until they are all xed and it works, debugging can bedicult. Strategies to help:

Check easiest and most likely errors rst. In this case,Termite setup problems and wiring problems are themost likely errors.

The least likely errors are broken modules. Check ev-erything else rst, before replacing modules. If you haveto replace modules lever them out gently with a screw-driver keeping the module parallel to the breadboard atall times. Otherwise you will bend or break pins.

Check wiring. With power o use a multimeter to checkthat connected pins are actually connected. In this casethere are 4 necessary connections: Tx, Rx, +5v, Ground.

Check power. With power on check voltage betweenXBee +5v and 0V pins.

Isolate errors. For example, a loopback test connectingFTDI Tx pin to Rx pin can check everything before theXBee module and its wiring

B Debugging the Programming

Toolchain and Firmware

When rst writing embedded code using a new software envi-ronment the problem is often to set up the tool chain correctly.In MIC this is mostly done for you, but in case of dicultieshere is the list of problems:

Boot loader . In MIC this is Avrdude. This takes a hex leof compiled code and loads it into the ash ROM of themicrocontroller, usually via a serial port interfaced withthe microcontroller serial connection. It can be testedindependently of the compiler by using a pre-built hex lefor your microcontroller, which is often available. In thisexperiment it is mic2.hex.

Is the boot loader connected to the correct COMport?

Is the COM port locked by another application (e.g.connected to Termite)?

Are the COM port settings correct? The FTDI chipwill auto-detect speed, and Avrdude will set up theother parameters correctly, so this should not be aproblem for you.

14 MIC Engineering Practice

Component Problem Check Fix

Termite wrong port Check available ports (settings) withFTDI module connected and discon-nected to nd FTDI port

Alter settings

Termite Disconnected Top left button indicates discon-nected

Click disconnectedbutton

USB Bad USB conn Does FTDI module form COM portwhen connected?

Check cable is con-nected, change cable

FTDI module Broken Perform loopback test Replace (use screw-driver as in Appendix )

Supply wiring Incorrect Check Zigbee supply voltage Rewire

Data wiring Incorrect Check pin to pin continuity Rewire

Xbee module Broken Replace (use screw-driver as in Appendix )

Xbee mode Wrong mode XBee will drop out of command modeinto data mode quickly, and then notrespond to AT commnds

Send +++

Figure 12: Possible faults in PC to XBee connection

FTDI Module AtMega88 (mounting position when

used in later sections)

Xbee Module

1 7 pin 1 pin 12

pin 24 pin 13

Pin FTDI AtMega88 Xbee

TXD 1 3 2

RXD 5 2 4

+5v 15, 21 7, 20 3

0v (GND) 7, 24 8, 22 1

USB

1

28

14

15

FTDI DTR 2

XBee RESET 5

AVR RESET 1

Figure 13: Pin Summary

EEE & EIE Second Year Electronics Laboratory 15

Is the microcontroller connected to the FTDI chipcorrectly? You need to check +5v and GND, TXand RX, and also critically the reset circuit. Thereset circuit and supplies can be checked indepen-dently if your microcontroller has a program loadedthat does something visible, like output data on auart line. Note that if reset is not properly acti-vated at the start of the boot loader process themicrocontroller will not be recognised.

Is the hex le too large for the available memory?The compiler will normally give a warning but notprevent over-large programs. They cannot t in theavailable memory do the boot loader will fail.

Compiler In your case this is Atmel Studio 6 which uses theavr-gcc compiler. You have correctly downloaded a pro-gram via the boot loader. This certainly means the mi-crocontroller is working. If the program was correctlycompiled it will run. The problems now are both soft-ware and hardware:

Did the most recent version of your code correctlycompile and build a hex le? If not you will be load-ing the old version.

Is the boot loader picking up the correct le? Makesure the compiler output is in the same directoryas the boot loader input, otherwise you could beloading the wrong le.

Check the new software is running by outputtinga debug message via the serial port to Termite(rprintf here). A debug message received whenthe program is run will tell you that you have in-deed correctly down loaded the right le, and thatthe microcontroller is working. That is an importantsanity check before doing real software debugging.

If you can't understand what the microcontroller isdoing, but it is doing something, check the TXDoutput with a scope. You can manually decode thecharacters sent in serial format, and check that theyare sent at the expected times, etc.

Debug the software. Because it is embedded youwill nd the easiest way to debug code is via theaddition of rprintf statements (to a PC serial ter-minal via the UART).

Beware broken hardware pins. One cause of diculterrors is a partially broken microcontroller. Exces-sive voltages and currents will break the ADC inputcircuitry of a particular pin, while leaving the rest ofthe device working. Check and cure this by swappingto a dierent input pin - since the ADC is switch-able between pins. If you have a microcontrollerwith a broken pin please get a sticker from the lab

technicians to make it broken, so no-one else usesit.

C Data Wiring

RXD (Din) is always wired to TXD (Dout) and vice versa.Figure 13 summarises the necessary connections. Note thatthe Atmega88 and Xbee Module power supplies (5v and 0v)always come from the FTDI module - not an external powersource. The FTDI module must therefore always be con-nected to a PC even when it is not being used.

In all congurations two of the three modules will be con-nected, and the third not used.

D Removing modules and ICs from

plugboard

If you remove multiple-pin modules from plugboard manuallyone end will come lose before the other, bending half the pins.Pins will then need to be bent back to the correct position,and may break.

The correct removal method is to place a small screwdriverunderneath the module of IC so that the tip protrudes at theother end. Then gently lever the module upwards by pullingon the screwdriver handle. Should the screwdriver angle be-come too large you can insert the screwdriver further, or levelfrom the other side, to ensure that the module is extractedwhilst remaining parallel to the plugboard, with no appreciablebending of pins.

16 MIC Engineering Practice