microprocessor_interfacing C31

Page 1

Microprocessor Interfacing - v1.05 - J R Smith

MICROPROCESSOR INTERFACING 1

INTRODUCTION

2

BINARY LOGIC AND ELECTRONICS 2.1 From voltages to logic 2.2 TRI-STATE logic 2.3 Binary inputs and outputs

3

BINARY INPUT TRANSDUCERS 3.1 3.2 3.3 3.4 3.5 3.6

Mechanical switches. Multiplexed inputs Switch debouncing. Some other switches Non-mechanical switches. Pseudo-binary inputs

4 BINARY OUTPUT TRANSDUCERS 4.1 Solenoids 4.2 Pseudo-binary outputs 5 ENCODING INFORMATION BY VARIATIONS WITH TIME 5.1 5.2 5.3 5.4 5.5 5.6 5.7

Introduction Elapsed Time Frequency Modulation (FM) Pulse Width Modulation (PWM) Bitstream Modulation (BSM) Coding Information coding in Biology (not required for exam)

6 BASIC ANALOGUE COMPONENTS 6.1 Amplifiers 6.2 Comparators 6.3 Using analogue transducers as binary transducers (not required for exam) 7 DIGITAL TO ANALOGUE CONVERSION 7.1 7.2 7.3 7.4

How many bits? Bitstream Binary-weighted resistors R-2R Ladder

8 ANALOGUE TO DIGITAL CONVERSION 8.1 8.2 8.3 8.4

Parallel or Flash Successive Aproximation Integrating Delta - Sigma

1


Microprocessor Interfacing - v1.05 - J R Smith

9 TRANSDUCERS 9.1 TRANSDUCERS FOR TEMPERATURE 9.1.1 Thermocouple 9.1.2 Thermistor 9.1.3 Semiconductor junction 9.1.4 Temperature dependent oscillator 9.1.5 Resistor 9.1.6 Peltier (thermoelectric) module. 9.2 TRANSDUCERS FOR LIGHT 9.2.1 Light Dependent Resistor (LDR) 9.2.2 Photodiode 9.2.3 Phototransistor 9.2.4 Solar cell 9.2.5 Incandescent lamp (Light Emitting Resistor) 9.2.6 Light Emitting Diode 9.3 TRANSDUCERS FOR SOUND 9.3.1. Dynamic microphones 9.3.2. Elecret, capacitor and condensor microphones 9.3.3 Dynamic Speaker 9.3.5 Electrostatic Loudspeaker 9.3.6 Magnetostrictive transducer 9.4 TRANSDUCERS FOR CHEMICAL CONCENTRATIONS 10 INTERACTION SCHEMES 10.1 Programmed interaction or polling 10.2 Interrupts 10.3 Direct Memory Access (DMA) 11 SOME ASPECTS OF COMPUTER ARCHITECTURE 11.1 Types of memory

These notes are written with specific reference to the 'ATOM' microcontroller. However much of the information is also applicable to the 'BASIC STAMP' microcontroller or other microcomputers. Copyright J R Smith 2003 2


Microprocessor Interfacing - v1.05 - J R Smith

1

INTRODUCTION

You should now be familiar with the BASIC MICRO 'ATOM' microcontroller. It is based on the 16F876 PICMicro MCU. It has 8K of FLASH memory used for storing programs, 384 bytes of RAM for storing the variables used in programs and 256 bytes of EEPROM that can store data when the power is removed. What can a device like this do? It turns out that it can do almost anything. However it does have two fundamental limitations - speed and complexity. The internal cycle time (200 ns) and the time taken to execute instructions (of the order of 30 µs) both limit how rapidly the ATOM can respond to external events. This limitation can be overcome for short periods by using external circuitry with a faster response. However for continuous operation the speed is ultimately limited by the instruction execution time. Consequently the ATOM is simply too slow for some tasks (e.g. real time, high fidelity, audio processing). The limited space available for program and variables also imposes an eventual upper limit on the complexity of tasks that the ATOM can reasonably handle. However you are unlikely to approach this limit. I have written large programs (>20 pages of code) that still fit into the 8K memory. Physicists are interested in the behaviour of the real world, however the parameters of interest don't occur in the form of binary signals with voltage levels compatible with the binary logic of microcomputers. Consequently transducers are used to convert various physical parameters to and from suitable electrical signals. These notes aim to provide an introduction to the • interfacing computers to the real world • some common transducers • various techniques used to convert between analogue and digital variables • techniques for synchronising a microcomputer with real world events Suitable circuits and programming examples will be presented wherever possible. They will often be specifically for the ATOM28, but the basic principles are applicable to most microcomputers or microcontrollers.

3


Microprocessor Interfacing - v1.05 - J R Smith

2

BINARY LOGIC AND ELECTRONICS

2.1 From voltages to logic Although you have now been using an electronic implementation of digital logic for several weeks, until now you have not needed to concern yourself with what voltages were used to represent binary logic. However before you can interact with signals from the real world you need to which voltage levels correspond to a logical 0 (often called LOW) and which belong to a logical 1 (often called HIGH). Currently there are 2 main families of electronic logic that you are likely to meet. The first is 'TTL' - short for Transistor Transistor Logic. They are almost always powered from a 5 V supply. Although there are many subspecies with slightly different characteristics, their logic levels are approximately logical 0 corresponds to a voltage between 0 and 1.5 volts logical 1 corresponds to a voltage between 1.5 and 5 volts The second main family is CMOS. - Complementary Metal Oxide Silicon. These are usually powered with a voltage (VDD) in the range 3 to 18V - the particular maximum value of VDD depends upon the particular species. Their logic levels are approximately logical 0 corresponds to a voltage between 0 and VDD/2 logical 1 corresponds to a voltage between VDD/2 and VDD There also exist species of CMOS that have inputs that are compatible with TTL voltage levels when VDD = 5V. 2.2 TRI-STATE logic If you examine the data sheet for many microprocessors, you will find that a given pin can sometimes be an input, and sometimes be an output! To understand how this is possible we need to examine a slightly different form of electronic logic - TRI-STATE logic. This has the normal digital logic levels of LOW and HIGH plus an extra output state where the output is essentially disconnected from the internal logic circuitry. An additional 'enable' input determines whether the output behaves normally or is disconnected.

A B E

Q

A

B

E

Q

0 0 1 1 x

0 1 0 1 x

0 0 0 0 1

0 0 0 1 z

x = doesn't matter z = high impedance or 'disconnected'

Fig. 2.2.1 A 2-input AND gate with tri-state output. The ’enable’ input is denoted by E. Bus structures TRI-STATE logic is very useful in bus structures where it enables multiple outputs to be connected together. This will not give rise to logical contradictions providing only one output is enabled at any given time.

4


Microprocessor Interfacing - v1.05 - J R Smith

Multiplexed inputs Many devices designed for interfacing with microcomputers come with TRI-STATE outputs. The outputs of multiple devices can thus be connected to a common set of inputs, and the desired device selected via its enable input. DEVICE A D3 D2 D1 D0

E P3 P2 P1 P0

D3 D2 D1 D0 DEVICE B

P6

ATOM

P7

E

Fig. 2.2.2 Schematic diagram showing how two devices with tri-state outputs can be multiplexed. The state of the outputs P6 and P7 will determine whether the data (D3-D0) from either device A or B will be present at the inputs P3-P0.

Bidirectional ports These allow the transfer of data in either direction - consequently it is possible for a given pin to be either an input or an output at different times.

A

Q

E

A

E

Q

x = doesn't matter

0 1 x

0 0 1

0 1 z

z = high impedance or 'disconnected'

Fig. 2.2.3 A buffer with tri-state output. input/ output

input

(direction = 1)

output (direction = 0) direction

Fig. 2.2.4 Schematic diagram of a circuit that allows a single connection to be used as either an input or an output according to the state of an input that specifies the direction of data transfer. 5


Microprocessor Interfacing - v1.05 - J R Smith 2.3 Binary inputs and outputs The circuit shown below can be used to determine the range of input voltages that correspond to a logical ‘0’ and a logical ‘1’. +5V ATOM 20k

P0 V

Fig. 2.3.1 Circuit for measuring input characteristics of digital inputs. The ATOM has 2 types of input. Inputs 0 to 7 have conventional TTL levels. Schmitt trigger inputs. Sometimes the input characteristics are deliberately given a degree of hysteresis - the logic levels are different for increasing and decreasing voltages. This feature gives the logic a degree of immunity against 'noise' on the input signal - often very useful when interfacing to the real world. Inputs 8-15 are Schmitt trigger inputs. The 0->1 transition occurs around 3V, whereas the 1->0 transition occurs around 1.5V

binary output

1

binary output

0 0

1 2 3 4 input voltage

5

1 0 0

1 2 3 4 input voltage

5

Fig. 2.3.2 The input characteristics for conventional TTL (left) and TTL with Schmitt trigger inputs (right).

6


Microprocessor Interfacing - v1.05 - J R Smith

3

BINARY INPUT TRANSDUCERS

Some input transducers or devices inherently have only two possible states. 3.1 Mechanical switches. These usually involve contact between two or more pieces of conductive material - usually metal. There are many possibilities and we will limit discussion to some simple basic types. The diagrams below indicate how they could be connected directly to a digital input. The 10k resistor connected between an input and +5V is often known as a 'pull-up resistor' - it 'pulls' the input up to +5V when nothing is connected to that input. On the ATOM the command SETPULLUPS can be used to connect a set of 10k internal pullup resistors on inputs 1 to 7 if required. +5V

+5V +5V

10k P0

P0

P0 10k

SPST Single Pole, Single Throw switch open: P0 = 1 switch closed: P0 = 0

SPST Single Pole, Single Throw switch open: P0 = 0 switch closed: P0 = 1

SPDT Single Pole, Double Throw switch up: P0 = 1 switch down: P0 = 0

Fig. 3.1.1 Circuits indicating how switches can be connected to a digital input, in this case P0 of the ATOM. SPDT switches are sometimes called 'changeover'. All of the pins on the ATOM are inputs by default when a program starts. A pin can be made an input via the INPUT command, its value can be determined by examining the variable In0. Some switches only change their state momentarily, e.g. push buttons. They are often available as 'normally closed' (nc) or 'normally open' (no). They can be wired using the same circuitry as conventional switches. Often the transition between states is important. The following code repeatedly tests if the input = 1, and proceeds to the next instruction once the input = 0, i.e. the button has been pushed. It thus effectively detects the 1-> 0 transition. Loop1: IF In0 = 1 THEN Loop1 'program reaches this point when In0 = 0 7


Microprocessor Interfacing - v1.05 - J R Smith +5V

10k P0

Fig 3.1.2 Circuit indicating how a push button can be connected to a digital input. 3.2 Multiplexed inputs The 16 switches on your BS2 development board are connected to the ATOM via a 16 input multiplexer. A 4 bit address determines which of the 16 inputs is connected to the multiplexer output which can then be connected to an ATOM input. Determining the state of a switch is slower with this technique because the address of the desired switch must be supplied to the multiplexer before reading. Multiplexing also means that you can only determine the state of a single switch at a time - without multiplexing the ATOM could simultaneously determine the state of 16 switches. However it has the great advantage of needing only 5 input/output pins rather than the 16 required if the switches were connected directly. Question: What is the maximum number of switches that your ATOM could monitor with suitable external multiplexing hardware?

3.3 Switch debouncing. Mechanical switch contacts usually 'bounce' for a few milliseconds after they make initial contact. Consequently in the circuits given above for SPST switches you will get a series of multiple rapid transitions between 1 and 0 as the contacts close. In most applications you will need to ignore these initial bounces. 1 0 Idealised

Real world

Fig. 3.3 Diagram illustrating the multiple transition between states that occur when a switch changes states.

The ATOM has a BUTTON instruction is designed to take care of switch debouncing. I can't get it to work!

8


Microprocessor Interfacing - v1.05 - J R Smith 3.4 Some other switches Thermostats These are switches that change state at a given temperature, usually based on a bi-metallic strip. Transition is either predefined or adjustable. Quite cheap (e.g. JAYCAR ST-3821/3/5/6 = $4.45). The bi-metallic strip is composed of two metals with different coefficients of thermal expansion. When heated the lower layer of metal expands more than the upper layer, the strip bends, and the circuit is is broken.

high temperature

normal temperature

Thermal cutouts and thermal fuses These are switches that go open circuit (usually permanently) above a predefined temperature. Cheap (e.g. JAYCAR ST-3800/4/8 = $2.80). Two springy wires are held together by a waxlike material. At a sufficiently high temperature the wax melts and the wires spring apart.

high temperature

normal temperature

Mercury switches A small drop of mercury maintains electrical contact between two wires when the switch is in the upright position. If the switch is rotated, the mercury drop moves and an open circuit results. Useful for detecting when an object is moved from the vertical position. Compact and relatively cheap ( e.g. JAYCAR SM-1035 = $2.80) bead of mercury

glass container

2 wires Magnetic Reed Switch Constructed from magnetic wire sealed inside an evacuated glass enclosure. Contacts are normally open, but close when a magnet is near. Can also get n.c. or changeover contacts. Compact and cheap (e.g. JAYCAR SM-1002 = $2.80). Widely used for burglar alarms. Have several advantages including: (i) no mechanical contact required (ii) metal contacts are in an isolated environment – no corrosion Trembler switch The end of a thin springy wire is surrounded by a ring of wire. Vibration or motion will make the springy wire vibrate and thus make momentary contact with the wire ring. Useful for detecting motion, or <TILT> on a pinball machine.

9


Microprocessor Interfacing - v1.05 - J R Smith 3.5 Non-mechanical switches Switches can operate without moving mechanical parts. Some examples use the strength of a magnetic field (Hall Effect switches) or the presence or absence of light (various optical switches). 3.6 Pseudo-binary inputs Many analogue transducers are often used in a pseudo-binary fashion. This is because it is often sufficient to know if an analogue parameter is greater or less than a certain value. The inputs 0 to 7 of the ATOM assume that Vin<1.5 V is a logical 0 and Vin > 1.5 V is a logical 1. The following code sets an output high or low depending upon the input voltage. LOOP: IF In6 = 0 THEN LOW P8 ELSE HIGH P8 ENDIF GOTO LOOP A potential divider can be used to increase Vin above 1.5V. Similarly an amplifier (see later) can be used for Vin <1.5.

10


Microprocessor Interfacing - v1.05 - J R Smith 4. BINARY OUTPUT TRANSDUCERS 4.1 Solenoids The most common bistable output transducers are variants of the solenoid. These operate by passing a current through a coil of wire. The resultant magnetic field then attracts a magnetizable material into the solenoid. The mechanics of the device are usually designed to ensure that the operation is bistable. Solenoids are used to move mechanical components between two positions. They are often connected to a hydraulic valve to control water flow in domestic appliances such as dishwashers and washing machines. They can also be used to operate levers. Relays are a solenoid in which the mechanical action is connected to a switch. It is then possible for the small current from a microprocessor to switch much larger currents. They also provide electrical isolation between the microprocessor and the controlled circuit. Solenoids often require relatively large currents for operation. The ATOM can only supply a small current from its outputs, and so a single transistor, or even a Darlington pair, will often be used to amplify the current available from the outputs of the ATOM. The value chosen for R will depend upon the particular relay and transistor used. The transistor effectively amplifies the current by a factor known as b; typically b = 100. The function of the diode in the following circuit is to 'short out' any transient high voltages that can occur when the current through the inductance of the solenoid is removed.

+V

solenoid or relay

R P0

4.2 Pseudo-binary outputs Many analogue transducers are often used as pseudo-binary fashion. Examples include LEDS, heating elements, etc. The intensity of light emitted by a LED depends upon the current flowing through it, and this depends upon the voltage across it. R P0 LED

The value of the resistor R can be changed to suit the particular LED. The voltage across a typical LED is about 2 V. Consequently the current I flowing through the LED will be given by I = (5 - 2) / R. If R = 220 ohms, then I = 14 mA. 11


Microprocessor Interfacing - v1.05 - J R Smith

5. ENCODING INFORMATION BY VARIATIONS WITH TIME Up until now we have discussed simple binary operations - inputs and outputs have only two possible states. Surely a microprocessor can do more than this. The answer is to consider the past history of binary operations -information can be encoded into the time variation of a binary signal. The encoding process is often called 'modulation'. We will look at a couple of possibilities.

5.1 Introduction Elapsed Time The information is encoded in the elapsed time between some events. Frequency Modulation. The frequency of the binary signal carries the information Pulse Width Modulation (PWM) The frequency is kept constant, but the width of the pulse carries the information. Bitstream The running average value of a stream of pulses carries the information. The frequency and pulse widths will usually change to allow the desired waveform to be as precisely as possible. Digital Coding Can use the presence or absence of pulses in a specific sequence to carry the information. Some electronic examples are RS232, USB, Firewire (IEEE1394), I2C, etc. Some nonelectronic examples include Morse code, semaphore, etc.

12


Microprocessor Interfacing - v1.05 - J R Smith 5. 2 Elapsed Time One common technique involves measuring the time taken to charge or discharge a capacitor through a series resistor. The ATOM has a useful instruction that allows it to measure the resistance and/or capacitance of an external element - the instruction RCTIME RCTIME Pin, State, Variable Pin - specifies the pin to be used State - specifies the desired state for measurement. A counter is started once RCTIME starts to execute. Once Pin is not in State, the instruction terminates and the value of the counter is stored in Variable. Variable - used to store the measurement of ELAPSED time. For your ATOM each unit stored in Variable corresponds to 1 Âľs. If Variable is a WORD, the maximum time that can be measured is 216 Âľs = 65.535 ms. This instruction can be used to measure the time take to charge or discharge an external resistor / capacitor (RC) circuit. This can be very useful - the ATOM can measure the setting of potentiometer. It can also measure the output of many transducers that change their resistance or capacitance in response to changes in the parameter of interest. It can be used to measure the duration of short pulses. It can even be used to measure voltages. When RCTIME commences execution it starts an internal counter. This counter is stopped once the specified Pin is no longer has the value = State. The time constant t = RC can be calculated from the time taken for the capacitor to charge or discharge. Then R can be calculated from C, or C can be calculated from R. Before RCTIME is used, it is essential to use an OUT command to charge or discharge the capacitor to either 0 or 5 V. This level must be maintained until the capacitor is effectively charged or discharged - typically 4t will be sufficient - see manual. Charging circuit V(t) = V [1 - exp(-t/t)]

charging

t = - t / ln[(V-VFinal )/V] = - t / ln[(5-1.5)/5] = 2.8 t For the circuit shown below, VFinal = 1.5V (the transition from 0->1 occurs around 1.5 V on inputs 0-7 of the ATOM).

R P0 C

voltage

+5V 1.5

0 RCTIME

Demonstration code for RC charging. 13

time


Microprocessor Interfacing - v1.05 - J R Smith

Temp var TIME LOW 0 PAUSE 10

; start to discharge capacitor ; the length of the pause should be ≈ 4RC ; you should calculate it for your circuit RCTIME 0,0,TIME ; now measure time to recharge Discharging circuit A more accurate approach is to measure the time it takes to discharge a capacitor. This because then VInitial = 5 V and VFinal = 1.5V, a difference of 3.5 V. V(t) = V exp(-t/t)

discharging

t = - t / ln[VFinal /V] = - t / ln[1.5/5] = 0.83 t +5V

P0

C

voltage

5

1.5

R

0 RCTIME

time

Demonstration code for RC discharging. Temp var TIME HIGH 1

; ; PAUSE 10 ; ; RCTIME 0,1,TIME ;

start to discharge capacitor i.e. both plates at +5V the length of the pause should be ≈ 4RC you should calculate it for your circuit now measure time to recharge

Measuring voltage It's also possible to use the RCTIME command to measure an unknown voltage by connecting components with known values of R and C to the unknown voltage. The process of charging the capacitor from the voltage source can drain a significant current, and so this approach is only suitable for voltages with a low source impedance.

14


Microprocessor Interfacing - v1.05 - J R Smith

5.3 Frequency Modulation (FM) The frequency of the binary signal carries the information. The example below shows how three different frequencies might be encoded.

low freq

high freq

medium freq

Its often convenient to keep the duty cycle constant and equal to 0.5. Because random noise and interference will generally affect only the amplitude of a signal, FM is very tolerant of noise and interference. For example, compare FM radio with AM (amplitude modulated) radio. The ATOM has an instruction for measuring the frequency of an input signal. COUNT pin, period, variable This instruction makes the selected pin an input, then counts the number of complete cycles (i.e a 0->1->0 or 1->0->1 sequence) during the defined period (in ms). The count is stored in ‘variable’. It can measure square wave inputs with frequency < 125 kHz (the pulse width must be ≥ 4 µs). Sometimes the frequency itself of an input signal is important. One example would be a guitar tuning meter. An analogue voltage can be measured by connecting it to a voltage-controlled oscillator (VCO). A VCO produces an output signal with a frequency that depends upon the input voltage. The ATOM can measure the VCO frequency, and thus determine the analogue voltage. unknown voltage

Voltage controlled oscillator

ATOM (COUNT instruction)

There is no single instruction for producing a square wave output at a defined frequency. You will have to write your own if needed using PULSOUT or OUT. (The instructions DTMFOUT and FREQOUT generate pseudo-sine waves using a bit-stream technique). FM is sometimes used to send purely binary information in noisy environments – for example modems.

15


Microprocessor Interfacing - v1.05 - J R Smith

5.4 Pulse Width Modulation (PWM) The frequency is kept constant, but width of the pulse (tH) carries the information. The time tH + tL is kept constant. The duty cycle is defined as tH / (tH + tL). tH

tL

tH

duty cycle = 0.5 tH

tL

duty cycle = 0.75

tL

duty cycle = 0.25 The ATOM has no simple instruction for producing a ‘correct’ PWM signal with constant frequency. (The PWM instruction uses what we will call bitstream modulation). The interpreter is slow, each instruction takes a few ms for execution. The following example can produce pulses of different width depending upon the value of 'Num'. The frequency remains constant, but is hard to predict accurately because extra time is taken by the For loops and the BRANCH instruction. Demonstration code ‘ Program to demonstrate PWM Var VAR WORD Num VAR WORD Denom VAR WORD Num = 2 Denom = 5 Loop: For Var = 1 to Num HIGH 0 NEXT For Var = Num+1 to Denom LOW 0 NEXT BRANCH Loop You will later use a sort of PWM signal to control the angle of servomotors. The average value of a PWM signal can also be used to carry information. However it is not particularly suitable for rapidly varying signals because it takes many complete cycles for the average value to change. A better approach involves allowing the frequency to vary as well as the pulse width - see bitstream modulation.

16


Microprocessor Interfacing - v1.05 - J R Smith 5.5 Bitstream Modulation (BSM) The 'running average' value of a stream of pulses carries the information. The frequency and pulse widths will usually change to allow the desired waveform to be as precisely as possible. The example below shows roughly how a triangle wave could be encoded.

The PWM instruction effectively performs BSM. The output string of pulses can be filtered to produce different analogue voltages. It thus can act as a Digital to Analogue converter (DAC). The component pulses are quite short (often approx. 4Âľs and so are easier to filter out than true PWM). Demonstration code. ' Program to demonstrate BSM of LEDs ‘ Throbbing LEDs Loop VAR WORD LED VAR BYTE FOR Loop = 0 TO 255 FOR LED = 0 TO 255 PWM 0, LED, 5 // gradually increase brightness NEXT FOR LED = 0 TO 255 PWM 0, 255-LED, 5 // gradually decrease brightness NEXT NEXT END The FREQOUT instruction uses BSM to produce an output containing one or two pseudosinusoidal signals. FREQOUT Pin, Period, Freq1, Freq2

17


Microprocessor Interfacing - v1.05 - J R Smith

Sound generation The stream of pulses produced by PWM or FREQOUT needs to be filtered to remove the high frequency components associated with the rapid 0->1 and 1-> 0 transitions. A simple RC filter is usually OK (see manual). This instruction is very useful for generating audio output that is useful for: • Warning ‘beeps’ or ‘pings’ • Provideing feedback on program status, - e.g. an indicator that program has finished some part of program • Providing feedback (usually via frequency) about some measurement that does not require visual interaction. • Fun !! (Why not program your ATOM to play ‘Stairway to Heaven’ ? ) 390R P0 SPEAKER

5.6 Coding Can use the prescence or absence of pulses in a specific sequence to carry the information. Some examples are RS232, USB, Firewire (or IEE...). The ATOM has some instructions designed to extract information from pulse sequences. SERIN – used to read in asynchronous serial data SEROUT – used to send asynchronous serial data SHIFTIN – used to read in synchronous serial data (i.e. when a clock is involved) SHIFTOUT – used to send synchronous serial data (i.e. when a clock is involved)

5.7 Information coding in Biology (not required for exam) Frequency modulation is used in the human nervous system. Nerve impulses are binary pulses that switch from approx - 60 mV to approx + 50 mV and back to - 60 mV in a few ms. Information about external stimuli is generally carried by the rate at which these nerve impulses occur (usually the rate is approximately proportional to the logarithm of the strength of the stimulus - physiologists call this Fechner's law). The biological equivalents of logic gates in the nervous system are implemented by a cunning temporary transition to analogue chemical transmission. Nerves connect to each other at specialised junctions called synapses. When the nerve impulse reaches the end of an ‘input’ nerve, it releases small amounts of a chemical messenger into a small region between the nerves – the synaptic cleft. The rate at which nerve impulses occur at the ‘output’ nerve is determined by the concentration of chemical messengers in the synaptic cleft. There are two types of chemical messenger – agonists (these tend to increase the firing rate) and antagonists (these tend to decrease the firing rate). The binary signal produced by the output nerve thus depends upon the nett effect of the various agonists and antagonists that are released by the ‘input’ nerves. Try PHYS2410 if you would like to know more about this 'Biologic'.

18


Microprocessor Interfacing - v1.05 - J R Smith 6

BASIC ANALOGUE COMPONENTS

6.1 Amplifiers

VA VB

+ Vout

_

Vout = Gain (VA - VB) This is a differential amplifier, i.e. it amplifies the difference between the two inputs. 6.2 Comparators Basically a high gain amplifier with analogue inputs and a digital output, i.e. the output voltage levels are compatible with standard logic. Used to determine whether VA is greater or less than VB

VA VB

+ Vout

_

If VA < VB Vout = 0

If VA > VB Vout = 1

6.3 Using analogue transducers as binary transducers Often we just want to know if an analogue signal is greater or less than a certain value. The inputs 0-7 of the ATOM assume that Vin<1.5 V is a logical 0 and Vin > 1.5 V is a logical 1. So by amplifying the input voltage Vin with a gain of G, and subtracting a reference voltage VREF it is possible for the 0"–>"1 transition at an ATOM input to correspond to any desired input voltage.

Amplifier gain = G VIN

+ _

Comparator GVIN

GVIN _ VREF P0

+ _

+5V VREF

19


Microprocessor Interfacing - v1.05 - J R Smith 7 DIGITAL TO ANALOGUE CONVERSION We have already seen how an ATOM can output an analogue voltage using PWM or FREQOUT. However in many situations we require higher precision, faster response and multiple outputs. These will require extra components external to the ATOM.

7.1 How many bits? How many bits are required to produce a voltage with sufficient precision? n bits can encode 2^n possible states n=

8

10

16

# of states

256

1024

65,536 ~10^6

precision

~0.5%

0.1%

16 ppm

20

24 ~16x10^6

1 ppm

0.06 ppm

ppm = parts per million 24 bit precision is incredibly precise. A plane journey from Sydney to Rome is about 16,000 km and takes perhaps 20 hours flying time. 24 bit precision would require knowing your absolute position with respect to Sydney with an error of only 1 m, only 20% more than the distance between seats in economy class.

7.2 Bitstream Could use the PWM instruction to produce a desired DC voltage. PWM Pin, Duty, Cycle If output is smoothed with a suitable filter, Vout = (Duty / 255) x 5 V For time varying output voltages, very sophisticated algorithms can be used to produce the closest match to the desired waveform, whilst minimising noise in the output signal. Bitstream can be very precise because there are essentially no components that need to be calibrated (see later). However very precise values require averaging a large number of pulses, so they are relatively slow. Some examples can reach 23 bit precision with sample rates below 100Hz.

20


Microprocessor Interfacing - v1.05 - J R Smith 7.3 Binary-weighted resistors R1 = 1.25k

8 mA S3 4 mA

R2 = 2.5k S2

2 mA

R1 = 5k

Load

S1 R0 = 10k

1 mA S0

Fig. 7.3 An idealized circuit in which the load resistance is assumed to be small in comparison with the resistors R0 to R3. A functional DAC would generally use some additional transistors or op-amps.

By closing the appropriate switches we can get any current from 0 to 15 mA. If each switch were controlled by an appropriate bit, the current I could be described by I = value of 4-bit word in mA. The current can easily be converted into a voltage if required. The problem: for an n-bit DAC we need n resistors that cover a range from R to 2nR, where R is the value of the resistor with the lowest value, each resistor must have a tolerance of at least Âą R. For n > 10 this is very difficult to achieve. Even if discrete resistors are initially sufficiently precise, they will slowly experience different shifts in value with temperature variations and aging. Laser trimming of resistors on the same substrate can achieve suitable precision for n <= 16. Another approach generates binary weighted currents by using digital logic to produce pulse sequences with different average values. In this situation there is nothing to go out of calibration.

21


Microprocessor Interfacing - v1.05 - J R Smith 7.4 R-2R Ladder A cunning method of obtaining binary weighted currents that only needs one or two values of resistor. 16i

8i 8i

R

4i

R

4i

4i

2i

R

2i

i

2i

i

2R

2R

2R

2R

8i

4i

2i

i

2R

The resistors can be manufactured on the same substrate, and consequently should have similar variations with temperature and time.

22


Microprocessor Interfacing - v1.05 - J R Smith 8 ANALOGUE TO DIGITAL CONVERSION Our ATOM now needs a method of measuring an analogue voltage using of external circuitry. We now discuss Analogue to Digital converters (ADC). 8.1 Parallel or Flash This involves simultaneous comparison with multiple voltage standards. Vin 3V

+ _

D3 Priority encoder

2V

+ _

D2

A1 A0

1V

+ _

D1

+5V

D0

The above circuit is a 2-bit flash converter. The output of the priority encoder (A0,A1) is the binary address of the highest asserted input (D0-D3). Advantages: very fast, only requires the time for a comparison plus some digital logic. Disadvantages: expensive - an n-bit converter requires 2n-1 comparators. Becomes prohibitive for n>10. They are usually used for low resolution, very high speed situations (e.g. digitising video or digital oscilloscopes). The oscilloscopes in the lab have 8 bit, 1 GHz converters.

23


Microprocessor Interfacing - v1.05 - J R Smith 8.2 Successive Approximation This involves a single comparator in sequential comparisons with a voltage standard that is adjusted according to prior comparisons.

Vin VDAC

end of conversion

+ _ Successive approximation register DAC

EOC

Start n

The 'start' command initiates a binary search sequence controlled by the Successive Approximation Register (SAR) (1) The most significant bit (msb) of the DAC = 1, all other bits = 0. (2) the comparator output now indicates whether VDAC<Vin or VDAC>Vin. (3) if VDAC<Vin then msb = 0 or if V DAC>Vin msb = 1 for the rest of the conversion (4) now set the next significant bit = 1. Again the comparator output will indicate if this bit should remain set at 0 or 1. (5) repeat for all the bits of the DAC. (6) assert the EOC output (End Of Conversion) (6) the digital approximation to Vin is then the final code sent to the DAC. Advantages; relatively cheap, only requires one comparator + DAC Disadvantages: slower than flash because an n-bit conversion requires n comparison steps. Can operate at speeds approaching 10 MHz at 12 bits. Slower versions (200 kHz) can have 16-bit precision.

24


Microprocessor Interfacing - v1.05 - J R Smith 8.3 Integrating This measures the time taken for a known capacitor to charge using a known current until its voltage is equal to the unknown voltage. Vin VC

+ _

I

stop Binary counter

C

start

Start (1) Initially the counter is set to zero and the switch is closed, so VC = 0. (2) The first step is to open the switch and start the counter. (3) The capacitor then starts to charge up. The current I is constant, so VC increases linearly with time. (4) Eventually VC = Vin. The comparator output then changes state and stops the counter. (5) The count will then be proportional to Vin. Advantages: very cheap, capable of very high precision - 20 bits or more, the integration process can remove noise and interference. Disadvantages: very slow, conversion rates are typically a few Hz.

25


Microprocessor Interfacing - v1.05 - J R Smith 8.4 Delta - Sigma Differential amplifier

Vin VDAC

+ _

Comparator

Integrator

V1

V2

+ _

V3

bitstream output

1-bit DAC The output of the differential amplifier ,

V1 = Vin - VDAC

The integrator output V2 = sum of V1 over many cycles. V3 is the output of a comparator: if V2>=0

V3 = 1 else V3 = 0

VDAC = +1.00 if V3 = 1 or VDAC = -1.00 if V3 = 0 The circuit operates at a very fast clock rate. If the value in the integrator is positive the DAC output will be positive and this will be subtracted from Vin, reducing the output of the integrator. Similarly if V2 is negative, then VDAC will be negative and the output of the integrator will be increased. Consequently a stream of pulses is produced whose average value reflects the value of Vin. This then undergoes sophisticated filtering via a decimation filter to become the final serial output. Advantages: cheap, very precise (a one bit DAC has nothing to go out of calibration), can perform very sophisticated filtering to remove noise and interference. Disadvantages: The clock rate must be very much higher than any changes in Vin. These ADC are increasingly used for digital audio (20 bit resolution at 96 kHz) and very low frequency measurements (23 bits at 20 Hz).

26


Microprocessor Interfacing - v1.05 - J R Smith

9 TRANSDUCERS Transducers are devices that convert one form of energy into another. Usually we use them to covert various physical parameters to and from electrical signals. This is because a microprocessor or microcontroller can conveniently measure electrical signals via an ADC and output electrical signals via a DAC. 9.1 TRANSDUCERS FOR TEMPERATURE 9.1.1 Thermocouple A thermocouple is made when two dissimilar metals are placed in contact. A voltage is generated between them that varies with the temperature of the junction. The voltage is quite small <100 ÂľV/oC, so amplification will often be required. To reduce the number of temperature dependent junctions between different metals, the unknown temperature is often measured with respect to another thermocouple that is kept at a constant reference temperature (usually at 0oC). A special integrated circuit can also be used to provide the correct reference voltage. Unknown

+ _

ADC

ATOM (ADCIN instruction)

Reference 9.1.2 Thermistor These use semiconductor materials or oxides with a resistance that varies with temperature. It is possible to get NTC (negative temperature coefficient) or PTC (positive temperature coefficient) devices. Their resistance is usually a non-linear function of temperature. A typical value might be 10 kW with a variation of - 1kW/oC. +5V C

!!!!!!ATOM (RCTIME instruction)

Thermistor

+5V

R

!!!!!!ATOM (SHIFTIN instruction)

ADC

Thermistor

27


Microprocessor Interfacing - v1.05 - J R Smith 9.1.3 Semiconductor junction The voltage across a semiconductor junction varies with temperature. (For a silicon pn junction it is approx. 2.2 mV/oC). In theory one can use any diode, but calibration is difficult. Consequently it is easier to use specialised integrated circuits that provide either a voltage or a current that is linearly proportional to the temperature. +5V

R

!!!!!!ATOM (SHIFTIN instruction)

ADC

9.1.4 Temperature dependent oscillator This transducer uses an oscillator that is sensitive to temperature changes. Temperature is measured by counting its output frequency. Temperature controlled oscillator

!!!!!!ATOM (COUNT instruction)

9.1.5 Resistor When a current I passes through a resistor R, the Joule heating produced is given by I2R. When a voltage V is maintained across a resistor R, the Joule heating produced is given by V2/R. (Because the value of a resistor changes slightly with temperature, they are also sometimes used to measure very low temperatures). 9.1.6 Peltier (thermoelectric) module. In these modules a flow of electric current provides the necessary energy for a flow of heat against its thermal gradient (i.e. heat is extracted from a cold surface and passed to a hot surface). These allow a computer to control the amount of cooling. If the polarity of the current is reversed, the direction of current flow is also reversed. !!!!!!ATOM (PWM instruction)

R

load C amplifier

The load in the above circuit could be a resistive heating element or a thermoelectric module.

28


Microprocessor Interfacing - v1.05 - J R Smith

9.2 TRANSDUCERS FOR LIGHT 9.2.1 Light Dependent Resistor (LDR) When a photon of light of a suitable wavelength falls on a semiconductor, an electron can be excited from the valence band into the conduction band. The resistance of the material then decreases. This leaves the absence of an electron in the valence band - usually referred to a positively charged 'hole'. Eventually an electron and a hole will meet and recombine, and the original resistance will be restored. There are some materials, particularly CdS or CdSe, where the decrease in resistance can be greatly amplified. An LDR usually consists of a thin, folded, strip of such material. Their response time is quite slow (typically hundreds of milliseconds). Typical values might be 1-10k in dim light and 100 ohms in bright light. They can be connected in the same fashion as a thermistor (see section 9.1.2) 9.2.2 Photodiode These are made by placing p- and n- type semiconductor materials in contact and so forming a pn diode. The n-type has an excess of mobile negative carriers (electrons) and the p-type an excess of mobile positive carriers (holes - really the absence of electrons). Electrons at the edge of the n-region will be attracted to the holes at the edge of the p-region, and vice versa. They combine, and a high resistance 'depletion layer', with a very low concentration of mobile charge carriers is formed across the region of contact. A strong electric field is produced across this depletion layer because of the charge movement associated with its formation. When photons strike a depletion layer they can generate electron-hole pairs. These would normally quickly recombine, but the strong electric field across the depletion layer rapidly separates the electron-hole pairs so that they can't recombine. This produces a shift in the voltage-current characteristics of the diode, and can be used to produce a current or a voltage depending upon the external circuitry. The current increases linearly with illumination, but generally requires some amplification.

_

R !!!!!!ATOM (SHIFTIN instruction)

ADC

+

9.2.3 Phototransistor The current generated by the electron-hole pairs is now amplified via normal bipolar transistor action. Used mainly to detect the presence/absence of light. 9.2.4 Solar cell These are p-n junctions that are designed to optimise power production.

ADC

!!!!!!ATOM (SHIFTIN instruction)

Solar cell

29


Microprocessor Interfacing - v1.05 - J R Smith 9.2.5 Incandescent lamp (Light Emitting Resistor) If a material is made sufficiently hot it will start to emit visible light. Usually made from a coiled piece of resistance wire in an evacuated bulb. (Air would allow the hot wire to oxidise). Can be used in a similar fashion to resistive heating elements and thermoelectric modules. (see section 9.1.6). Because of thermal inertia they have a relatively poor frequency response. 9.2.6 Light Emitting Diode These are semiconductor diodes that emit approx. monochromatic light when current flows through them. The corresponding voltage across the diode is usually in the range 1.5 to 2.5 volts. (Shorter wavelengths require higher voltages). 9.3 TRANSDUCERS FOR SOUND 9.3.1. Dynamic microphones The sound pressure wave acts on a diaphragm that moves a coil of wire in a magnetic field, thus producing a voltage. The voltage is small (mV or less) and will require amplification before the ADC. Magnet Coil of wire Voltage

Diaphragm 9.3.2. Elecret, capacitor and condensor microphones

Sound pressure moves one plate of a very delicate charged capacitor. Because the charge remains constant, while the plate separation varies, the voltage across the plates will change. Elecret microphones use permanently charged plastic electrodes (electrets). Capacitor and condensor microphones usually require an external source of charge (48V on standard audio systems).

+ -

Voltage

9.3.3 Dynamic Speaker Current is sent through a coil of wire (the voice coil) that is placed in a magnetic field. A diaphragm is connected to the voice coil so that a varying current causes motion of the diaphragm that moves the surrounding air. Magnet Speaker coil Speaker cone

Voltage

30


Microprocessor Interfacing - v1.05 - J R Smith 9.3.4 Piezoelectric speaker A voltage across a piece of piezoelectric material causes it to flex, and thus set air in motion. piezo-electric material Speaker cone voltage 9.3.5 Electrostatic Loudspeaker A high voltage is place between two conducting plates. Causes relative motion of plates that in turn set air in motion. basically a capacitor microphone in reverse. 9.3.6 Magnetostrictive transducer Magnetostrictive materials contract in a magnetic field. One example is the 'Soundbug'. A rod of magnetostrictive material (Terfenol - made from terbium, iron and dysprosium) is surrounded by a wire coil. When a current flows through the coil, the resulting magnetic field causes the Terfenol to change shape. This in turn vibrates the object to which it is attached and that produces the sound. suction cap

magnetostrictive material Voltage

9.4 TRANSDUCERS FOR CHEMICAL CONCENTRATION 9.4.1 pH electrode The electrode tip is made from special glass that is permeable to protons. A voltage is then generated between the inside and outside that depends upon the internal and external proton concentrations. Their output impedance is very high, usually > 109 ohms.

+ _

known [H]

high input impedance amplifier unknown [H] proton permeable glass 31


Microprocessor Interfacing - v1.05 - J R Smith 10 INTERACTION SCHEMES 10.1 Programmed interaction or polling In this approach the computer program continually monitors various status flags that indicate the state of real world variables. Advantages: Simple to program, requires minimal hardware Gives the fastest response to an external event, i.e. minimum latency. Disadvantages: Fastest response requires that the microprocessor continually monitor the status flags leaving no time for other tasks. If a very fast response is not required, for example checking if a key has been pressed on a computer keyboard, then the microprocessor can do other tasks whilst only checking the status flags occasionally. 10.2 Interrupts This involves the external hardware having access to the internal workings of the microprocessor via specific ‘interrupt’ logic lines. When a specific condition occurs on one of these lines, the microprocessor acts as if the next instruction in your program was Gosub address This can be thought of as a ‘pseudo-instruction’. The subroutine that you wish to be executed (the interrupt handler) should be located at this address. When this subroutine has finished processing, the program continues operating from the line in your code after the one it was execution when the interrupt occurred. Instruction are available that tell the microprocessor to either ignore or to pay attention to interrupts. Serious microprocessors also have methods of specifying different priorities for different interrupts. Advantages: Microprocessor can perform useful tasks whilst waiting for interrupt. Disadvantages: Requires special hardware Increased latency Harder to program RESETS All microprocessors have another type of interrupt - the RESET. The microprocessor can then always start execution from a well-defined state.

32


Microprocessor Interfacing - v1.05 - J R Smith

The ATOM has three types of RESET Power on reset = ONPWR: This occurs when power is first applied to the ATOM, or when power is removed and restored Brown out reset – ONBOR: This occurs when the power supply voltage falls below 4.1V. This can be useful for situations that derive their power from batteries. A ‘LOW BATTERY’ warning can be initiated, and any important parameters saved in EEPROM. Also useful for detecting situations when the mains power fails. Reset pin reset – ONMOR: This occurs when a 0->1 transition occurs at the ATN/RES pin. Often triggered by a ‘RESET’ button. 10.3 Direct Memory Access (DMA) The device that wishes to perform DMA must first undergo an arbitration process with the microprocessor to become the ‘bus master’. When ready the microprocessor can relinquish control of the busses. The device can then take control of the busses and rapidly transfer data. Advantages: The microprocessor is free to perform other tasks Very fast data transfers, particularly when large blocks of data are moved. Disadvantages: High latency can make it inefficient for transferring small amounts of data. Requires more complex hardware – the device must be smart enough to become ‘bus master’ Requires more complex programming. The ATOM28 has no DMA capability (there are no external busses that it can release to another device).

33


Microprocessor Interfacing - v1.05 - J R Smith 11 SOME ASPECTS OF COMPUTER ARCHITECTURE 11.1 Types of memory ROM = Read Only Memory: The desired truth table is permanently programmed by the manufacturer of the integrated circuit. PROM = Programmable ROM: The desired truth table is programmed by the user. This involves using an externally applied current to melt small internal wire links. Cannot be reprogrammed. EPROM = Erasable PROM: The desired truth table is programmed electrically by the user as the presence of charge on internal ‘capacitors’. The data can be erased by exposure to photons of sufficiently high energy, i.e. ultraviolet light. A quartz window is provided for this purpose. EEPROM = Electrically EEPROM: The charge on the internal ‘capacitors’, and hence the stored truth table can be altered by an applied voltage. FLASH = a type of EEPROM that can be easily reprogrammed. RAM = Random Access Memory: nowadays this refers to read/write memory that ‘forgets’ when the power is removed. There are two main species: Dynamic and Static. SRAM = Static RAM: This memory is implemented using flip-flops. DRAM = Dynamic RAM: This memory is implemented via charge on tiny ‘capacitors’. The charge on these capacitors leaks away quite rapidly – in a couple of ms. Consequently the memory is ‘refreshed’ by internal logic every ms or so. Static vs Dynamic Static memory requires more transistors per bit than dynamic, and so is more expensive and occupies more space. However it is significantly faster. An ideal computer would use only SRAM, however this would be too expensive for most situations. The common approach is to use SRAM within the microprocessor and DRAM for the main memory. A copy of sections of the main memory is then kept in caches built using SRAM that can be accessed rapidly by the microprocessor.

34


Turn static files into dynamic content formats.

Create a flipbook
Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.