physics 358 - tools for science · physics 358 advanced electronics lab manual fall 2014 operation...

19
PHYSICS 358 Advanced Electronics Laboratory Manual Fall 2014 Dr. Adam T. Whitten

Upload: hahanh

Post on 04-Jul-2018

221 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: PHYSICS 358 - Tools for Science · Physics 358 Advanced Electronics Lab Manual Fall 2014 Operation ... In part 2 you will measure an externally applied frequency from a function generator

PHYSICS 358

Advanced ElectronicsLaboratory Manual

Fall 2014

Dr. Adam T. Whitten

Page 2: PHYSICS 358 - Tools for Science · Physics 358 Advanced Electronics Lab Manual Fall 2014 Operation ... In part 2 you will measure an externally applied frequency from a function generator

Notes

Page 3: PHYSICS 358 - Tools for Science · Physics 358 Advanced Electronics Lab Manual Fall 2014 Operation ... In part 2 you will measure an externally applied frequency from a function generator

Physics 358 Advanced Electronics Lab Manual Fall 2014

Preliminaries

The Coridium ARMmite microcontroller (CAM) receives its power from the USB connection to yourcomputer. The CAM has a 3.3V regulator to reduce the voltage to the LPC2103 microcontrolleron the board. While inputs to the microcontroller are 5V tolerant, you can burn out the protectiondiodes for the LPC2103 inputs if 5V is applied while the CAM is powered down, rendering it useless.Because of this:

1. Never power up the protoboard unless the CAM is powered up first.2. Protect inputs to the CAM IOs with 1kΩ resistors.3. Never exceed 3.3V on an AD input.4. Outputs from the CAM should be buffered with TTL chips.

Connect your CAM board to the lab protoboard using the provided ribbon cable.

One side of the ribbon cable plugs into the header on the CAM board while the other end has 2DIP connectors allowing it to plug into the protoboard. The pinouts are as follows:

Note the orientation of the ribbon cable connected to the microcontroller board and the protoboard.

1

Page 4: PHYSICS 358 - Tools for Science · Physics 358 Advanced Electronics Lab Manual Fall 2014 Operation ... In part 2 you will measure an externally applied frequency from a function generator

Physics 358 Advanced Electronics Lab Manual Fall 2014

Operation

Connect the USB cable to your CAM and logon to the PC with your username and passwordbefore powering on the Global Specialties protoboard. Connect the ribbon cable to the CAMand protoboard. Connect the protoboard’s ground to the two ground wires on the ribbon cable.You need only power on the protoboard when you test your programs. Launch the BASICtoolsprogram on the desktop. When you are done with a lab session, always power off the protoboardand disconnect the ribbon cable from the CAM (a power outage may result in the protoboardhaving power on while the computer and CAM have power off).

Dual Usage Pins

Eight IO pins can be used by the hardware pulse width modulation (HWPWM) function and twopins can be used for external interrupts. Plan accordingly if you use either of these features.

Hardware Pulse Width Modulation External Interrupts

IO Pin 0 1 2 3 4 9 10 11 IO Pin 14 15

Channel 1 2 3 4 5 6 7 8 EINT 0 2

Only HWPWM channels 1-4 use the LPC2103’s Timer2 and Timer3 modules, while channels 5-8use the Timer2 and Timer1 modules. The Timer0 module is used in conjunction with the BASICkeyword TIMER. Therefore, if you want to use timed interrupts and HWPWM in the same program,you should use Timer1 for the timed interrupts which will limit you to HWPWM channels 1-4.

IO15 is also connected through a 330Ω resistor to a LED which is tied to 3.3V. Anything connectedto IO15 will be in parallel with this circuit, so design accordingly.

The 10-bit analog to digital inputs (AD0-AD7) can also be configured as digital input/outputs(IO16-IO23). On reset or power up the AD pins are configured as AD inputs. To change thoseto digital IOs you must individually specify a control direction using INPUT(x), OUTPUT(x),DIR(x), or IO(x) commands. After that they will remain digital IOs until the next resetor power up.

Lab Reports

Record your lab report in an Ampad #26-251 (or equivalent). You should turn in your lab notebookat the beginning of class on Tuesday so that I may grade them. I will put your graded notebooksin your mailbox by Wednesday afternoon so you can prepare for the next lab. The labs build uponeach other and are structured to prepare you to be able to complete a project during at the end ofthe course. Therefore timely completion and submission of your lab notebook is important.

Include an introduction and conclusion for each lab. Sketch all oscilloscope waveforms and recordall numerical data in your lab book. Output to the computer can be cut and pasted into a textdocument for printing and then taped in your lab book if necessary. Include flowcharts used forprogram design and diagrams for electronic circuits. Programs should be written using Notepad(using a .bas extension), fully documented, and printed out for inclusion in your lab book.

2

Page 5: PHYSICS 358 - Tools for Science · Physics 358 Advanced Electronics Lab Manual Fall 2014 Operation ... In part 2 you will measure an externally applied frequency from a function generator

Lab 1 – Basic Input and Output

Introduction

In this lab you will take keyboard and digital inputs and display them on 7-segment common anodeLEDs. In part 1 you will read a hexadecimal digit from the keyboard and display it. In part 2 youwill display a counting loop of hexadecimal numbers 0-F. In part 3 you will decode a 4-bit binarynumber and display it as a hexadecimal digit. In part 4 you will decode an 8-bit binary numberand display it as two hexadecimal digits.

While there are several ways to drive 7-segment displays, in this lab you will use 8 digital outputsfrom the CAM to turn on and off the seven segments plus decimal point. Make sure to buffer youroutputs to the 7-segment display with a TTL device (e.g., 7404 Hex Inverter). Also limit the currentinto the display with a 330Ω resistor between the common anode and the 5V supply. By the endof the lab you will end up using 8 digital inputs and 10 digital outputs, so plan accordingly. Sinceyou will use this LED display in subsequent labs, avoid using pins 0-3 (HWPWM), 14 (EINT0),and 15 (EINT2).

Additional Components Needed (quantity):

• 7-segment common anode LED displays (2)• 330Ω resistors (2)• appropriate TTL devices for output buffers (enough for 10 outputs)• limiting resistors for CAM inputs (number depends on design)• 2N3904 NPN switching transistors (2)• side-board SPDT switches (1 bank of 8 switches)

Common Anode 7-Segment Display 2N3904 Transistor

Pin Assignment Pin Assignment

1 Cathode a 14 Common Anode

2 Cathode f 13 Cathode b

3 Common Anode 12 N. C.

4 N. C. 11 Cathode g

5 N. C. 10 Cathode c

6 N. C. 9 Cathode dp

7 Cathode e 8 Cathode d

Pin Description

1 collector

2 base

3 emitter

The convention for displaying hexadecimal digits beyond 9 is: A, b, C, d, E, F. To distinguish “6”from “b”, segment a is lit for “6” and dark for “b”.

Part 1 – Terminal input and 7-segment displays

Using the DEBUGIN command, read a hexadecimal digit (0-F) and display it on a 7-segmentdisplay. Perform a check on the input to make sure it is in the proper range. You should firstdecide which eight pins you will use to control the display. Using consecutively numbered pins willmake your code easier to write and faster to execute. DIM and initialize a 16 element integer arraywith 8-bit values corresponding to the 8 outputs that turn on and off the segments necessary todisplay a digit. These values will depend on which pin is controlling each segment, so documentyour connections at the beginning of your program. Remember to buffer your outputs with TTLgates. Use a FUNCTION or SUB to set the levels of the outputs to the display so that it can bereused later. After your program works make sure to save it and print it out for inclusion in your

3

Page 6: PHYSICS 358 - Tools for Science · Physics 358 Advanced Electronics Lab Manual Fall 2014 Operation ... In part 2 you will measure an externally applied frequency from a function generator

Lab 1 – Basic Input and Output

lab report. Show your working system to the instructor.

Part 2 – Simple counting

Instead of displaying a hexadecimal digit typed in on the keyboard, create a counter that countsfrom 0 to F and displays each digit for 1 second. After the count reaches F it should roll over backto 0 and repeat. Use the same displaying function as in Part 1. After your program works makesure to save it and print it out for inclusion in your lab report. Show your working system to theinstructor.

Part 3 – Digital inputs

Now for your input use 4 SPDT switches to input a high or low signal to the CAM and display thecorresponding 4-bit number in hexadecimal. Use the same displaying function as in Part 1. Theoutput should remain on the display until a switch is changed. Since the protoboard operates at5V and the CAM operates at 3.3V, you must protect the CAM inputs with at least 1kΩ limitingresistors. This can be done by using two 1.0 kΩ resistors to make a voltage divider to supply thehigh side of the SPDT switches with 2.5 V. Explain why this works in your lab notebook! Decidewhich inputs you will use and document them within your program. Keep in mind that in part 4you will expand the number of inputs to 8 and that if the inputs are numbered consecutively it willmake you code more compact and efficient. After your program works make sure to save it andprint it out for inclusion in your lab report. Show your working system to the instructor.

Part 4 – Strobing two 7-segment displays

An 8-bit binary number requires two hexadecimal digits to display. Instead ofusing 16 outputs to control 2 displays, you can use 8 outputs to tell a display whichsegments to turn on and 2 additional outputs to control power to the displays.This way you can load the data for the low nibble, turn on its display for 1 ms,then load the data for the high nibble, turn on its display for 1 ms, and repeat thisprocess indefinitely. A human eye will not notice the continual switching becauseof the persistence of vision effect. Use the two additional control lines to turn onand off 2N3904 transistors which control power to the Common Anode (CA) ofthe displays. After your program works make sure to save it and print it out forinclusion in your lab report. Show your working system to the instructor.

Do not dismantle your 7-segment LED display circuit when you are finished – you will use it againin Labs 2 & 4.

4

Page 7: PHYSICS 358 - Tools for Science · Physics 358 Advanced Electronics Lab Manual Fall 2014 Operation ... In part 2 you will measure an externally applied frequency from a function generator

Lab 2 – Timing External Events and PWM

Introduction

In this lab you will investigate the various ways the CAM can generate frequencies and measurefrequencies and pulse widths. In part 1 you will generate frequencies and examine them on anoscilloscope. In part 2 you will measure an externally applied frequency from a function generatorand display the frequency to 2 significant digits. In part 3 you will generate a pulse width modulated(PWM) signal that could be used to control a stepper motor and view it on an oscilloscope. Inpart 4 you will use external interrupts to measure your reaction time.

There are various methods for generating frequencies on the CAM. Usually an interrupt drivenroutine is used that runs continously in the background. Non-interrupt driven routines will monop-olize the microprocessor until they are finished. The typical method for measuring a frequency is tocount the number of pulses at an input for a set time period. You can then calculate the frequencyof the signal. Another common task is to create and measure pulse widths. You generate a pulseas part of a method to measure a person’s reaction time.

Additional Components Needed:

• the 2 digit 7-segment LED display circuit from Lab 1 Part 4• capacitors and resistors for push button switch debouncing and voltage dividing• appropriate TTL devices for output buffers• limiting resistors for CAM inputs• LED• oscilloscope• function generator• digital multimeter

Part 1 – Frequency generation

Write a short program that will use HWPWM to create a 1kHz signal on pin 0. Examine the signalon an oscilloscope, sketch it in your lab notebook, and measure its frequency.

Now add code to generate a second 1kHz signal on pin 1 using PWM (you may have to continuouslyloop to generate the signal repeatedly). Examine both the HWPWM and PWM signals on anoscilloscope. Sketch the PWM signal in you lab book and measure its frequency. Are there anyother differences between the two signals?

Now add code (after the PWM code) to create a signal on pin 2 that is similar to the HWPWMsignal on pin 0 using the PULSOUT routine (this may require some thought). Examine both theHWPWM and PULSOUT signals on an oscilloscope and describe/sketch them in you lab book.What are the differences between the two signals? What is the effect you observe on the oscilloscopethat is a consequence of some signals being interrupt driven and others being non-interrupt driven?

Save your program and print it out for inclusion in your lab report.

Part 2 – Frequency measurement

Use the COUNT subroutine to measure a frequency from the function generator. Use the TTL(pulse out) on the function generator and make sure to limit the input to the CAM with a resis-tor. Display the frequency in kHz on your 2 digit 7-segment LED display. Your program shouldaccomodate signals from 0.1 to 99. kHz and display the decimal point in the appropriate location,

5

Page 8: PHYSICS 358 - Tools for Science · Physics 358 Advanced Electronics Lab Manual Fall 2014 Operation ... In part 2 you will measure an externally applied frequency from a function generator

Lab 2 – Timing External Events and PWM

updating the display every 0.5 seconds. For frequencies less than 0.1 kHz display “0.0.” and forfrequencies greater than 99. kHz display “-.-.”. Note that there is a tradeoff between the accuracy ofthe measurement and the quality of the display. More time spent COUNTing gives more accuracy,but increases flicker on the display; less time spent COUNTing decreases both flicker and accuracy.Justify your choice of count time. After your program works make sure to save it and print it outfor inclusion in your lab report. Show your working system to the instructor.

Part 3 – Pulse width modulation with external interrupts

Write a program that will create a 2kHz pulse width modulated signal. The duty cycle shouldbe displayed on your 2 digit 7-segment LED display and use external interrupt routines withappropriately debounced push buttons (see figure below). Use one push button to increase theduty cycle by 10% (to a maximum of 100%) each time it is pressed and a second push button todecrease the duty cycle from it’s current value to 0% over 2 seconds. View the waveform on anoscilloscope and measure the output voltage on a voltmeter. What happens to the output voltageas the duty cycle increases, remains constant, and decreases? Collect data for output voltage versusduty cycle and plot it using WAPP+. Is the graph linear? Explain. After your program worksmake sure to save it and print it out for inclusion in your lab report. Show your working systemto the instructor.

Part 4 – Measure reaction time

Create a system to measure a person’s reaction time using external interrupt routines with anappropriately debounced push button. When a push button is first pressed, turn on an LED for arandom length of time between 3 and 6 seconds. When the LED goes off, time how long it takesfor the person to press the button again. Display this time in seconds on your 2 digit 7-segmentdisplay putting the decimal point in the appropriate location, with times less than a second havingno decimal point. After your program works make sure to save it and print it out for inclusion inyour lab report. Show your working system to the instructor.

6

Page 9: PHYSICS 358 - Tools for Science · Physics 358 Advanced Electronics Lab Manual Fall 2014 Operation ... In part 2 you will measure an externally applied frequency from a function generator

Lab 3 – Analog to Digital Conversion

Introduction

In this lab you will check on the accuracy and precision of the CAM analog to digital converter.You will also use measurements of the decaying voltage on a capacitor to determine the capacitanceof a RC circuit. The CAM can perform a 10-bit analog to digital conversion in approximately 6µs and the result is stored as a 16-bit left justified number. To convert the 16-bit number to theappropriate 10-bit number shift it to the right 6 bits. To convert the count to a voltage you multiplyby Vmax (in this case 3.3 V) and divide by the maximum count (210).

Notes: You can copy output from the BASICtools terminal window and paste it into a spreadsheetor document. WAPP+ is limited to 99 data points.

Additional Components Needed:

• the 2 digit 7-segment LED display circuit from Lab 1 Part 4• capacitors and resistors for push button switch debouncing and voltage dividing• appropriate TTL devices for output buffers• limiting resistors for CAM inputs• digital multimeter• 1.0 µF capacitor and 330 kΩ resistor for RC circuit

Part 1 – Analog to digital conversion

Using the 10 kΩ potentiometer on the protoboard and suitable resistors create a circuit to providea variable 0.0-3.3 V input to the CAM. Use EINT0 to initiate a series of 10 analog to digitalconversions and print out the resulting counts to the terminal. Also measure the voltage with adigital multimeter (VDMM) during the conversion process and record the uncertainty δVDMM in thismeasurement. Collect data over the full range of voltage inputs (do not worry if your input does notgo all the way up to 3.3 V or down to 0.0 V). Use a spreadsheet to find the average and standarddeviation of the mean of the ten conversions of each voltage. Use WAPP+ to fit Counts vs. VDMM

to a straight line and graph it. Put the fit report and graph in your lab notebook. Comment onthe fit parameters. To how many bits is the conversion process accurate? What is the conversionfactor for counts to voltage and how does it compare to the theoretical value? After your programworks make sure to save it and print it out for inclusion in your lab report. Show your workingsystem to the instructor.

Part 2 – Measure RC time constant

Wire up the simple RC circuit pictured at the right. Measure and recordthe resistance in your lab notebook. Use the CAM to digitize the voltageon the capacitor and measure elapsed time during a discharge and sendthese values to the computer. Use EINT0 to trigger a discharge and startthe measurement cycle. Note: the capacitor will charge when IO(0)=1 anddischarge when IO(0)=0. You may use the CAM to convert the digitizedcounts to voltages and print the voltage and elapsed time to the terminal.

Copy your data to a spreadsheet and use WAPP+ to fit Voltage vs. Time and graph it. Describein your lab notebook how you found the uncertainties in the voltages. Put the fit report and graphin your lab notebook. Comment on the fit parameters. What is the RC time constant? Calculatethe value of your capacitor. After your program works make sure to save it and print it out forinclusion in your lab report. Show your working system to the instructor.

7

Page 10: PHYSICS 358 - Tools for Science · Physics 358 Advanced Electronics Lab Manual Fall 2014 Operation ... In part 2 you will measure an externally applied frequency from a function generator

Lab 3 – Analog to Digital Conversion

This page intentionally left blank.

8

Page 11: PHYSICS 358 - Tools for Science · Physics 358 Advanced Electronics Lab Manual Fall 2014 Operation ... In part 2 you will measure an externally applied frequency from a function generator

Lab 4 – I2C Interfacing

Introduction

In this lab you will interface an I/O expander and EEPROM memory with the CAM using the I2Cprotocol. Communication with I2C devices is via I2CIN and I2COUT:

I2CIN(DATApin, CLKpin, addr, OUTcnt, OUTlist, INcnt, INlist)I2COUT(DATApin, CLKpin, addr, OUTcnt, OUTlist)

The PCF8574A I/O expander is a simple slave device that runs at 100 kHz,can drive LEDs directly, and has a device address 0111zyxR, where zyx arethe logic levels on pins A2, A1, and A0 respectively. R is either 1 for a readoperation or 0 for a write operation. It can also generate an interrupt signalwith any rising or falling edge of the port inputs when in input mode. Datais sent to the I/O expander one byte at a time so OUTcnt is always 1 in theI2COUT command. Since it has only one internal “memory” location, datais received by setting OUTcnt to −1, OUTlist to null (i.e., “ ”), and INcntto 1.

The 24LC512 is a 512 Kbit serial EEPROM, meaning that it has 64K bytes of storage. To randomlyaccess this much storage a 16 bit (or 2 byte) address is needed. When using I2CIN with the24LC512 you pass the desired read memory address in OUTlist. The 24LC512 has a device addressof 1010zyxR, where zyx are the logic levels on pins A2, A1, and A0 respectively. R is either 1 for aread operation or 0 for a write operation.

Operations on 24LC512 memory chips with the CAM that can be performed are:

Operation OUTcnt value OUTlist

Byte Write 3 hiaddr,loaddr,dataPage Write 4 up to 130 hiaddr,loaddr,data0,...,data127Current Address Read −1 (blank) – use “ ”

Random Read 2 hiaddr,loaddr

For read operations, setting INcnt to 1 will perform a byte read and any number greater than 1will perform a sequential read. Refer to 24LC512 datasheet for restrictions on page writes andsequential reads.

Additional Components Needed:

• the 2 digit 7-segment LED display circuit from Lab 1 Part 4• capacitors and resistors for push button switch debouncing and voltage dividing• 2 PCF8574A remote 8-bit I/O expanders for I2C bus• 24LC512 I2C bus serial EEPROM• pullup resistors for clock, data, and interrupt lines

Part 1 – Using two 8574As for input and output

Revisit Lab 1 Part 4 – Strobing two 7-segment displays, but instead of using CAM I/O lines forinput and output use 2 8574A I/O expanders. Instead of using 8 I/O lines from the CAM to drivethe segments of the displays, use a 8574A I/O expander with A2, A1, and A0 hardwired to groundso that its address is 0111000R (note: R will always be 0 for writes). Since the 8574A runs at100 kHz, you should include #define I2Cspeed100. You will still need 2 CAM I/O lines to controlpower to each 7-segment display.

9

Page 12: PHYSICS 358 - Tools for Science · Physics 358 Advanced Electronics Lab Manual Fall 2014 Operation ... In part 2 you will measure an externally applied frequency from a function generator

Lab 4 – I2C Interfacing

Give the second 8574A and address of 0111001R (note: R will always be 1 for reads) and connect itto the side-board data switch. When the input changes, the 8574A should send an interrupt to theCAM so that it can read the new data and update the display. Use a delay at the beginning of theinterrupt service routine and before reading the data in order to accommodate for switch bounce.The INT requires a pullup resistor (1.0 kΩ is fine) and goes low when any input pin changes. Afteryour program works make sure to save it and print it out for inclusion in your lab report. Showyour working system to the instructor.

Part 2 – I2C memory interfacing

Revisit Lab 3 Part 2 – Measure RC time constant, but instead of sending data to the computerwrite it to a 24LC512 I2C bus serial EEPROM. Leave the 8574A used for the 7-segment display.Since the analog to digital converter is good to ten bits, it will take two bytes in the 24LC512 tostore the digitized number. If the digitized number is converted to a single precision floating pointvalue, that value will required 32 bits or 4 bytes of storage. Similarly, since TIMER is a 32-bitvalue it will take four bytes in the 24LC512 to store a single value. Reserve the first two memorylocations to store the address high byte and address low byte of the last memory location used.Flash this memory location on the 7-segment display: high byte for 1 second, low byte for 1 second,then blank for 1 second. If you use page writes, be careful to not write across page boundaries (i.e.,don’t use page writes). For byte writes you may need to insert a delay after each write to allow theEEPROM to complete the writing process. Use EINT2 to tell the CAM to read the 24LC512 andsend the data to you computer. Copy your data to a spreadsheet and use WAPP+ to fit Voltagevs. Time and graph it. Put the fit report in your lab notebook. Is the value for your RC timeconstant the same as what you found in Lab 3 Part 2? After your program works make sure to saveit and print it out for inclusion in your lab report. Show your working system to the instructor.

10

Page 13: PHYSICS 358 - Tools for Science · Physics 358 Advanced Electronics Lab Manual Fall 2014 Operation ... In part 2 you will measure an externally applied frequency from a function generator

Lab 5 – Matrix Keypads and Multidigit Displays

Introduction

In this lab you will interface more complex input output devices. A matrix keypad allows forgreater flexibility in user input compared to simple pushbuttons or switches. Multidigit displayseliminate the need for software multiplexing, but require more I/O lines for interfacing.

The matrix keypad requires 8 connections. All buttons in a common row are connected by acommon wire available at pins 1-4 for rows 0-3. All buttons in a common column are connectedby a common wire available at pins 5-8 for columns 0-3. In your textbook, the columns have anexternal 1 kΩ pull-up resistor, although the keypad will also work if the pull-up resistors are puton the rows instead. The keypad is read by sequentially setting the row lines to LOW and thenreading the column lines. When a button in ⟨row, col⟩ = ⟨i, j⟩ is pressed, col j only reads LOWwhen row i is low, otherwise col j is high. The period for changing rows should be in the ms range.

ABC

2DEF

3

GHI

4JKL

5MNO

6

PRS

7TUV

8WXY

9

OPER

0* #

A

B

C

D

1

1 2 3 4 5 6 7 8

16 Button Keypad Top View Pinout

Button Location

Terminal LocationFacep

late Character

01

2

345

67

8910111213

14

15

1 2 3 4 5 6 7 8

12

3

A45

6B

789C

*0

#

D

16 Button Code and Truth Table

Pull-up Resistors

(could connect to I/O expander)

(could connect to

I/O expander)

Pin 5 Pin 6 Pin 7 Pin 8

Pin 1

Pin 2

Pin 3

Pin 4

(could be onrows instead)

Both polling and interrupt techniques can be used to interface the matrix keypad. Polling techniquesrequire the microcontroller to spend time checking if a key is pressed (executing a loop every hundredmilliseconds or so) and then decoding the matrix. Interrupt techniques wait until a key has beenpressed before decoding the matrix, thereby freeing up the microcontroller to handle other tasks.Neither approach is superior to the other – the best approach depends on the particular application(see pages 57-58 of your text).

If polling is used, 4 digital outputs from the microcontroller are connected to the row pins andare periodically driven low sequentially in order to test whether a button has been pressed. Thecolumn lines are connected to 4 digital inputs to the microcontroller and read to see if one of theinputs is LOW. Alternatively, the column lines could be connected to an I/O expander which canthen be read after each row line goes low to check if a key has been pressed. These are pure pollingtechniques.

There are several ways to make an interrupt driven keypad system, but I/O expanders with interruptcapabilities facilitate their design. Half the lines of an I/O port are connected to the rows and halfare connected to the columns. In some application notes (e.g., AN1081 “Interfacing a 4x4 MatrixKeypad with an 8-Bit GPIO Expander,” by Mike Curran of Microchip Technology Inc., 2007) thefunctions of the rows and columns are reversed: columns are output pins and rows are input pinswith external pull-up resistors to VDD. When a button is pressed a row input is changed fromhigh to low generating an interrupt. The expander is read to determine the row number, the I/Odirections are flipped, and the expander is re-read to determine the column number.

11

Page 14: PHYSICS 358 - Tools for Science · Physics 358 Advanced Electronics Lab Manual Fall 2014 Operation ... In part 2 you will measure an externally applied frequency from a function generator

Lab 5 – Matrix Keypads and Multidigit Displays

Multidigit displays are nice because they can convey more information than one or two 7-segmentdisplays. However, they have significantly more inputs, so I/O expanders may be necessary. The 4-1/2 digit LCD displays that are available are 40-pin devices with 38 segments that can be activated.Typically not every segment is required for every application (e.g., multimeters would not need thecolons and clocks would not need all the decimal points or the ±). In this lab we will use 4 digits,so you will need 2 16-bit I/O expanders.

a

b

cd

e

f g

dp4dp3dp2dp1

col2

col3

la

x

xy

DIG. 5DIG. 4DIG. 3DIG. 2DIG. 1

1

40

20

21

Pin 1 2 3 4 5 6 7 8 9 10

Seg. COM y 1bc dp1 2e 2d 2c dp2 3e 3d

Pin 11 12 13 14 15 16 17 18 19 20

Seg. 3c dp3 4e 4d 4c dp4 5e 5d 5c 5b

Pin 21 22 23 24 25 26 27 28 29 30

Seg. 5a 5f 5g 4b 4a 4f 4g col3 3b 3a

Pin 31 32 33 34 35 36 37 38 39 40

Seg. 3f 3g col2 2b 2a 2f 2g la x COM

The MCP23017 is a 16-bit I/O expander with 22 individual registers.Its device address (i.e., control byte) is of the form 0100zyxR, where zyxare the logic levels on pins A2, A1, and A0 respectively. R is either1 for a read operation or 0 for a write operation. Ten registers areassociated with port A and ten are associated with port B. There isone shared register (IOCON). The port A registers are identical to theport B registers. They can be separated by bank (all port A registersat addresses 0x00-0x0A, all port B registers at addresses 0x10-0x1A) orcan be paired (addressed sequentially by function first for port A andthen for port B). To use these expanders you should first configure themwith I2COUT commands before entering your MAIN: loop.

MCP23017

1

2

3

4

5

6

7

8

9

10

11

12

13

14

16

15 A0

A1

A2

GPA0

GPA1

GPA2

GPA3

GPA4

GPA5

GPA6

GPA7

VSS

VDD

SCL

SDA

RESET

17

18

19

20

21

22

23

24

25

26

27

28

NC

NC

GPB7

GPB6

GPB5

GPB4

GPB3

GPB2

GPB1

GPB0

INTA

INTB

I2CIN(DATApin, CLKpin, addr, OUTcnt, OUTlist, INcnt, INlist)I2COUT(DATApin, CLKpin, addr, OUTcnt, OUTlist)

For example, to separate the registers into two banks and disable sequential operation the addressof the IOCON register (0x05) is sent followed by the desired data value (0xA0): OUTcnt= 2 andOUTlist=(0x05, 0xA0). Then to read the data present on port A, use I2CIN with OUTcnt=1,OUTlist=(0x09), and INcnt=1. At power on or after a reset the ports are configured as inputs bydefault.

Additional Components Needed:• 1 4x4 keypad• 1 4-1/2 digit LCD display• 1 PCF8574A remote 8-bit I/O expanders for I2C bus• 2 MCP23017 remote 16-bit I/O expanders for I2C bus• pullup resistors for keypad, clock, data, and interrupt lines• capacitors and resistors for push button switch debouncing and voltage dividing

Part 1 – Polled matrix keypad

Connect your matrix keypad directly to the microcontroller. Use the configuration outlined in your

12

Page 15: PHYSICS 358 - Tools for Science · Physics 358 Advanced Electronics Lab Manual Fall 2014 Operation ... In part 2 you will measure an externally applied frequency from a function generator

Lab 5 – Matrix Keypads and Multidigit Displays

textbook – put 10 kΩ pull-up resistors on columns and periodically drive the rows sequentially lowto test for a button being pressed. If you use consecutively numbered I/O lines, your programmingcode will be more compact. Print out to the terminal the location (0-15) of the button when itis pressed. You’ll need to decide on an appropriate polling time so that you capture the buttonpressing event once and only once. Remember that the interval for changing the row should be inthe millisecond range. Show your working system to the instructor. Clearly explain in your labnotebook why you chose the polling time and row interval you ended up using (i.e., what did yousee happening that caused you to increase or decrease these times).

Part 2 – Interrupt-driven matrix keypad

Use the INT feature of the 8574A I/O expander to make an inter-rupt driven keypad interface. Connect the keypad as shown in thediagram. Note that the pull-up resistors are now connected to thekeypad rows. Not shown in the diagram are the pull-up resistors forSDA and SCL (2.2 kΩ) and INT (1.0 kΩ). The quasi-bidirectionalport lines of the 8574A allow the pins to function as either inputsor outputs. An interrupt is generated (INT pulled low) if the dataon the port changes. The 8574 is initialized by writing 0xF0 (binary11110000) to the port so that the rows are high and the columns arelow.

Mat

rix K

eypad

1

2

3

4

5

6

7

8

row 0

row 1

row 2

row 3

col 0

col 1

col 2

col 3

P0

P1

P2

P3

P4

P5

P6

P7

SDA

SCL

INT

8574A

VDD

10kΩ

When a key is pressed it’s corresponding row will go low, changing the data on the port andgenerating an interrupt. For example, if the “6” key is pressed the data on the port becomes0xD0 (binary 11010000). If you read the port (which clears the interrupt) and divide the value by16, the resulting number has a 0 in the bit position corresponding to the row of the key that waspressed. Note that mechanical buttons suffer from switch bounce and that keypads are no exception.Pressing a button may cause multiple interrupts, so your interrupt service routine should wait fora millisecond before doing anything else.

Next the direction of the I/O lines of the 8574A is flipped by writing 0x0F to the port making allrows low and all columns high. However, because a key is still pressed one of the columns will staylow (in this example with “6” pressed column 2 will be low). Reading the port gives a numberthat has a 0 in the bit position corresponding to the column of the key that was pressed. In thisexample, you would read 0x0B (binary 00001011) from the port.

The last step is to flip the I/O directions back to their original stateby writing 0xF0 to the port. If this is done immediately then anotherinterrupt will be generated when the button is released. You can testfor button release by reading the port until its value goes back to0x0F. After the port returns to this state, then flip the I/O directionsback by writing 0xF0 to the port. To convert the bit positions toa number, you can use the compact code shown to the right. Oncethis is done for the row and column values, then the button locationis obtained from key=4*row+col. Print this button location out tothe terminal only if a button is pressed.

j=16

FOR i=3 DOWNTO 0

j >>= 1

IF (row AND j)=0 THEN

row=i

EXIT

ENDIF

NEXT i

Show your working system to the instructor. Do you ever see a button location outside the range0-15? If so, when does it occur? Give an explanation of why it occurs. Do not dismantle thiscircuit – you will use it in part 3.

13

Page 16: PHYSICS 358 - Tools for Science · Physics 358 Advanced Electronics Lab Manual Fall 2014 Operation ... In part 2 you will measure an externally applied frequency from a function generator

Lab 5 – Matrix Keypads and Multidigit Displays

Part 3 – Multidigit displays

The multidigit displays have 4-1/2 LCD digits. To activate the segment of a digit its correspondingpin must be made high. Each digit has 7 segments and a leading decimal point, so it is convenientto use a single 8-bit port to drive them (e.g., one port can drive segments 5a-5g and dp4). Use2 MCP23017s to drive digits 2-5 and dp1-dp4 in this manner. A single PCF8574A could then beused to drive digit 1, col2, col3, x, y, and la (only 6 bits are required), but we will not use them inthis lab. Your goal is to start with a blank display and then scroll characters across the display askeypad buttons are pressed. You will need to map the button location to a byte that will be sentto the correct MCP23017 port to display a proper hexadecimal digit corresponding to the value onthe keypad button (0-9, A-D). When the asterisk key (*) is pressed “E” should be displayed andwhen the pound key (#) is pressed “F” should be displayed. Make sure to check for button locationvalues that are out of bounds and do not update the display if this event occurs. Only update thedisplay when a valid key is pressed. For example, after starting the program if you press buttons2-C-#-9-4-B-* the display should show:

⟨blank⟩ ⇒ 2 ⇒ 2C ⇒ 2CF ⇒ 2CF9 ⇒ CF94 ⇒ F94B ⇒ 94BE

Make sure the MCP23017s have different hardware addresses and that you connect their resetlines to VDD. Note that the default power-on state of the MCP23017s is to be in paired mode(IOCON.BANK=0) with port pins set as inputs (IODIRA=IODIRB=0xFF). Therefore, the onlyconfiguration you have to do is to set the port pins as outputs. Thereafter you send data toregisters GPIOA (hex address 12) and GPIOB (hex address 13). Since the keypad is interruptdriven, have your main program continuously send data to the I/O expanders. View SCL and SDAon an oscilloscope. Sketch their waveforms in your lab notebook and identify each bit in the datasequence as well as the start and stop conditions. Show your working system to the instructor.

14

Page 17: PHYSICS 358 - Tools for Science · Physics 358 Advanced Electronics Lab Manual Fall 2014 Operation ... In part 2 you will measure an externally applied frequency from a function generator

Lab 6 – Device Interfacing

Introduction

In this lab you will interface various devices that are typically used in standalone microcontrollerapplications. In part 1 you will control a DC motor using interrupts to spin up and spin down themotor. These interrupts could be generated by other devices such light detectors and range finders,but we will use pushbuttons in this lab. In part 2 you will measure the output of a phototransistorcircuit which is properly interfaced to the analog to digital converter. In part 3 you will modifyyour phototransistor circuit to provide a digital input to the microcontroller.

Additional Components Needed:

• the 2 digit 7-segment LED display circuit from Lab 1 Part 4• +3.3 and −3.3 voltage regulators• Lambda power supply, function generator, and oscilloscope• various discrete components (see descriptions for each part below)

Part 1 – DC motor control

You will use hardware pulse width modulation to bring a motor up to its maximum speed andthen back down by activating push buttons as in Lab 2 Part 3 – Pulse width modulation withexternal interrupts. You may use the same control program that you used in Lab 2 Part 3 withthe exception that you will have to determine the best driving frequency. DC motors have intrinsicresistance, capacitance, and inductance that may change with the frequency of the applied drivingcurrent which is being switched on and off. You can quantitatively determine the best frequencyby first driving the motor with a TTL pulse train (equivalent to a 50% duty cycle) and measuringthe speed of the motor. In this lab you will not do a quatitative assessment, only a qualitativeassessment of a good frequency by observing the speed of the motor. You should end up with afrequency between 100 Hz and 1 kHz depending on which motor you use.

The motors run at either 5 V, 12 V, or 27 V (check the label on the motor) so set up a Lambdapower supply to provide this Vs. You will also need to determine appropriate values for R1 and R2

based on maximum ratings for input and output current listed in the MCT272 datasheet. The diodeis used to block current produced by back emf when the power switches off. Be sure to describehow you chose your driving frequency, R1, and R2 in you lab notebook. After your program worksmake sure to save it and print it out for inclusion in your lab report. Show your working systemto the instructor.

15

Page 18: PHYSICS 358 - Tools for Science · Physics 358 Advanced Electronics Lab Manual Fall 2014 Operation ... In part 2 you will measure an externally applied frequency from a function generator

Lab 6 – Device Interfacing

Part 2 – Phototransistor analog interfacing

Use a FPT5902 phototransistor and a LF356 opamp to generate an analog signal to be measuredby the microprocessor. Choose feedback resistors that do not saturate the output when the photo-transistor is illuminated with a flashlight. Use +3.3 and −3.3 voltage regulators to provide VCC andVEE to the opamp and bias to the phototransistor. You could end up with lots of data, so start andend the measurements with push buttons. Start a measurement, quickly pass the flashlight over thephototransistor, and end the measurement. Collect time and voltage data during the measurementcycle and print it to the screen so you can graph it and include it in your lab notebook. After yourprogram works make sure to save it and print it out for inclusion in your lab report. Show yourworking system to the instructor.

Part 3 – Phototransistor digital interfacing

Use the FPT5902 in a common-collector amplifier configuration to provide a digital input to themicrocontroller. Be sure to use a high enough resistance so that the photodiode operates in switchmode. The microprocessor should continually read the output and display its status on a singleLED (on if illuminated, off if not). Your circuit should also have an enable feature provided by themicroprocessor so that when the circuit is disabled by the microprocessor the output is always low.Use a single push button to activate and deactivate the enable feature. After your program worksmake sure to save it and print it out for inclusion in your lab report. Show your working systemto the instructor.

16

Page 19: PHYSICS 358 - Tools for Science · Physics 358 Advanced Electronics Lab Manual Fall 2014 Operation ... In part 2 you will measure an externally applied frequency from a function generator

Lab 7 – Project

Using what you have learned in class design your own microcontroller circuit that meets the fol-lowing requirements:

1. uses at least one interrupt2. uses at least one analog or digital input3. uses at least one output (digital, PWM, pulse) for control4. incorporates at least one I2C device in some useful way5. provides feedback to the user in the form of LEDs or 7-segment displays

If a particular input or output device is not on hand you may simulate its presence with otherelectronics after first researching the device’s specifications. For example, frequency inputs can besimulated with a function generator, digital inputs with switches, and analog inputs with poten-tiometers; outputs can be displayed on an oscilloscope or voltmeter.

Your project must be pre-approved by the instructor before lecture on Tuesday, November 11.At the beginning of lab on November 13 you will turn in a copy of your Product RequirementsSpecification and top level design. Your second level and detailed designs are due at the beginningof class on Tuesday, November 18. All that will be left to do in lab is code the microcontroller andbuild the interface. Document your work in your lab notebook. Put a copy of your program inyour lab notebook. Show your working system to the instructor.

Write up your project in a short (3-10 pages) report that includes a copy of your control programat the end.

17