Sie sind auf Seite 1von 21

Embedded Controllers for Audio Devices

, Greg Bartlett , PAVO,Philadelphia, PA, USA


,%

Embedded control fundamentals are presented, along with an'overview of a genetic MIDI-based controller that can be easily adapted for use in audio products and systems. The intent of the paper is to introduce simple development procedures and tools for adding computer-controlled features to audio devices.

INTRODUCTION Embedded control can open up a whole new world of automated applications for analog audio circuits. It is simple to add this capability by adapting an existing generic embedded control circuit to your needs.

Memory This is where data is stored to and taken from. Arithmetic Logic Unit (ALU) This performs math and logic computations on the data. Control their

EMBEDDED CONTROL

FUNDAMENTALS

Embedded control requires an embedded computer, Computers process numbers. Therefore, if your device settings can be expressed as numbers, they can be received, generated, and modified by your computer. Embedded Control Computer Hardware

This directs the computer's activities by pulling instructions out of memory to accomplish specific tasks. Central Processing th,ts (CPUs9 and microprocessors are combination ALU/Control Units. Mput.'OUttnt!1'0) ( Input devices (e.g., pushbutton switches) allow humans to talk to computers. Output devices (e.g., liquid crystal displays) allow computers to talk to humans. Memory,

A computer has four sections, shown in Figure 1.

ALU [ ]

locations in memory, and the data stored at each address. Memory consists of addresses that identify particular Figure 2 shows a typical section of memory.

Memory L_

I'"

Control Unit 1 ADDRESS 07 DATA $A2 06 $DC 04 05 I/O 1 b._ 02 03 01 00 $23 $74 $84 $B2 $A3 $01

__ m,__[ Fromthe wor_dl

ITo the.worl%

Figure 1: Computer Hardware Block Diagram

Figure 2: Computer Memory Representation

AES 13thINTERNATIONAL CONFERENCE

99

BARTLETT

There are many types of memory devices, differing in functionality and fabrication technology, I64NI)OM A('C'ESS M!':MORY(RAM) This read/writeable memory, is typically volatile -- i.e., if the power is removed from the circuit, data is lost. RAM is availablein several forms: 19ynamic RAM (DRAM) Each cell consists of a capacitor. A charged capacitor might indicate 1, and a discharged capacitor 0. Since capacitor charges dissipate, special circuitry is required to refresh the charge. This refresh process happens hundreds or thousands of times each second. ,Static I_M (SRAM) Each cell is a flip-flop circuit that does not require refreshing. Since flip-flop circuitry is more complex than DRAM cells, SRAM chips are physically larger than an equivalent DRAM. However, they do not require DRAM's refresh circuitry. Some SRAM can be backed up with battery power to preserve data if the main power source goesaway. READ ONLYMEMORY (ROM) This memory is nonvolatile -- i.e., if the power is removed from the circuit, data is preserved. ROM is availablein several forms: Programmable ROM (PROM) These devices can be programmed by the equipment manufacturer. Unlike RAM, which can be rewritten with data over and over, PROM data can be written once. Erasable PROMs (EPROMs) By shining ultraviolet light through a window on top of its package, EPROMs can be erased. They can be programmed, erased, and reprogrammed thousands of times, making them convenient for prototyping firmware. In production, it costs !ess to use PROMs. Electrically erasable PROMs (EEPROMs) EEPROMs can be erased by applying a voltage to one of the chip's pins. Since the embedded computer can apply this voltage, you can write to and read from EEPROMs. EEPROM is similar to battery-backed SRAM. Arithmetic Logic Unit (ALU)

execution. A necessary part of the control unit is its collection of registers, or special purpose memory addresses. The Program Counter (PC) holds the address of the next instruction to be executed. After the Control Unit fetches an instruction, the PC is updated to point to the next instruction. The PC is the computer's book marker. The Accumulator (AC('I.D holds the inputs and outputs of ALU arithmetic and logical operations. Most Control Units contain one or two Accumulators. Riding the Bus A bus is a group of related connections that tie together elements inside a computer. For example, the transfer of one data byte from one memory location to another occurs over aparallel data bus. An 8-bit byte requires an 8-wire parallel bus (one wire per bit). MIDI is an example of a serial bus, since data is sent one bitafteranother. Parallel busses are faster than serial busses. Operating at the same clock speed, an 8-bit parallel bus transmits a complete byte in the time it takes one bit to travel over a serialbus. However, if the parallelbus connection is made with a physical cable, one wire is required for each bit, increasing cost and complexity. Input/Output (1/O)

Because so much happens in the outside world that might interest your computer, there are many types of input and output devices. Each I/O device connects to your computer at a port. The simplest I/O ports are can be quickly configured as either an input or output, often changing designation from one instruction to the next. Input ports typically connects to something outside the computer (e.g., a keyboard switch). The computer monitors data appearing at this port. Output ports are used to send data from the computer to an external device (e.g., a light-emitting diode). Ports are usually implemented in flip-flops, remembering their state until told to change. Memory-mappedl/O treats input and output ports as specific locations in memory. Reading data from an input .(or writing data to an output) works just like reading from or writing to an address in memory.

The ALU performs arithmetic and logical operations (addition, subtraction, logical AND, logical OR, etc.) on its inputs. Results appear at the ALU's output. The Control Unit

The Control Unit sequentially fetches instructions (stored in memory), decodes them, and directs their

100

AES13th INTERNATIONAL CONFERENCE

EMBEDDED CONTROLLERS AUDIO FOR DEVICES

Interrupts External events happen unpredictably, often demanding the immediate attention of the computer. Such events must interrupt whatever the computer is doing and force it to service them. For example, your computer does not know when the musician is going to play a note on a keyboard, sending a MIDi message. When the note is played, your computer must stop what it is doing and deal with the message. Computers support a special class ofl/O called interrupts. When an interrupt occurs, the computer program's normal execution is suspended. The computer executes a special block of software (an btterrupt Service Routine, or ISR) written to handle the interrupt. Interrupts can be generated internally as well as from asynchronous data appearing at the I/O ports. For example, the computer's internal timer can generate a timer interrupt at specific intervals. The timer ISR could then execute a periodic software routine, such as blinking a light or sending a MIDI clock message, Peripherals A microprocessor is a very generic building block. Since they find their way into every conceivable application, no single device could ever have all the I/0 and memory needed for all applications. Consequently, most special I/0 functions are implemented in off-chip peripherals, Analog to digital converters (ADC.s;)measure analog signals from the real world (audio, temperature, fader position, etc.) and translate the values into digital data. A typical ADC converts an analog voltage to a one-byte binary number, giving a resolution of 256 different values. Figure 3 shows how an ADC digitizes a potentiometer'sposition. +5v

With the control turned fully clockwise (a), the potentiometer (pot) output shows the maximum voltage (5V). At the full counterclockwise position (b), the pot shows the minimum voltage (0V). In between these two extremes, the pot output differs between the analog extremes. The ADC converts the pot voltage into a binary, number that is fed to the microprocessor, in this way, the microprocessor "knows" the pot's position. Digital to attalog converters (DA('._) provide the complementary, function to ADCs by converting a digital number into an analog voltage. A typical DAC converts a one-byte number to a voltage, providing a resolution of 256 different analog voltages. Latches are banks of flip-flops. Most latches are 8 bits wide, storing one byte external to the microprocessor. Once a byte is written to an external latch, the external circuitry is free to do what it wants with the information (e.g., control an LED with each latched bit). Latches can be parallel or serial, although serial latches are commonly known as sh/fi registers. Most shift registers have either a serial input and parallel output, or a parallel input and serial output. These parts are useful in connecting a bus from one circuit board to another. Rather than running eight separateconnections to connect a byte-wide bus between each board, a parallelto-serial shift register can convert the eight lines to a single serial line. A serial-to-parallel shift register then converts back to parallel data at the other end. Universal A.synchronous Receiver Transmitters (UARI;s;)are specialized shift registers used to send digital data generated by one microprocessor to another device over a communications link. While normal shift registers require synchronization, a UARTdoes not need a clock line.To provide synchronization, the receiver and transmitter agree ahead of time on the rate at which bits will be exchanged. To

(a) ov__
m

converter digital

to microprocessor digitized output maximum value

analog to I

data stream. The receiver decodes these bits them in the transmitter generates special bits and inserts to determine beginning byte starts and ends. byte, the data mark the where a and ending of a data Most serial communications protocols, such as MIDI and RS-232 require UARTs. Both ends of the interface

+5v

(b) 0V__ -

converter digital I analog to I

to microprocessor digitized output


minimum value

encoded stream, it knows when to look for all future the receiver deciphers one valid block of bits from the ones, resulting in synchronization. UARTs can talk and know ahead of time howt fast to transferof speeds listento otherUARTs a widerange the bits, When a and dataformats,without needfor special ynchronization. s LiquM crystal display.(LCDs) provide a human interface from your computer by carrying ASCii' text

Figure 3: Digitized Potentiometer

AES13th INTERNATIONAL CONFERENCE

101

BARTLETT

messages, displayingdata, drawingpictures, and so on. l?mer peripherals allow the microprocessor to mark time. They are comprised of a free-running counter running at a known fi-equency.The microprocessor reads the counter (converting the count to real seconds if required) whenever it wants to. Some timers provide sophisticated functions that allow the microprocessor to sound alarms, automatically set or reset I/O ports at predetermined times, etc. Timers can also interrupt the microprocessor so it can perform a function periodically (just likean alarm clock), Memory Peripherals are used when the microprocessor's internal memory is too limiting. One example of a memory peripheral is an EEPROM. The interface betweenthe EEPROMand themicroprocessor is generally a serial bus. Memory peripherals look just like a large bank of shift registers to the microprocessor. Microcontrollers Despite the diversity of applications for embedded control computers, the hardware needed tO implement many of them is very similar. For example, the microprocessor+UART+LCD+memory combination can be found in many musical instruments and automobile dashboards. Therefore, chip designers offer microcontrollers that integrate a microprocessor with peripherals. They are single-chip computers with a microprocessor, memory, FO, and peripheral devices. The generic embedded control computer introduced in the next section uses a popular microcontroller called the MC68HC705C8 (68HC705). This microcontroller has several general purpose I/O ports, a timer, a UART, a serial I/O port, memory, and other built-in functions. Embedded Control Firmware

do = 23 fine = 57 how = 16 just = 01 thank = 142 you = 09 We can now carry on a conversation with someone using this new language: 16 23 09 23? 01 57 142 09! If you can decode the above exchange, then you can understand machinelanguage. Machinelanguage simply assigns a unique number to each of the computer's instructions. For example, the 68HC705 assigns the following (arbitrary) code numbers: add = 171 subtract = 160 AND = 164 OR = 170 Since we also need the data that will be added, subtracted, ANDed and ORed, a complete machine language instruction requires not just the operation codes shown above, but also the data. Therefore, an example of a complete 68HC705 instruction that adds 23 to a number in memory is: 171 23 Each program is simply a sequence of such instructions. Performing (1+2) and storing the result in memory address $1000 looks like: Address 0 1 2 3 4 5 6 Data 10100001 00000001 1010101 l 00000010 1100011 ! 00010000 00000000

Your computer's powerlies in its abilityto understand and perform a list of instructions,knownas a computer program or.firmware. Different computers have different repertoires of instructions, with some having a more powerful instruction set than others. Machine Language All languages use a specific set of symbols to represent something. Since computers understand binary numbers only, their languages use binary numbers. A computer's native (numerical) language is called machine language. Expressing concepts as numbers should not intimidate. Suppose we create our own language and represent the following words with the numbers as shown:

The program's instructions are organized in contiguous memory (i.e., at consecutive address locations). Each instruction in the above list consists of two pans: the operation code (or op code)and data (the operand). We can rewrite the above program, showing the op codes and operands:

102

AES13th INTERNATIONAL CONFERENCE

EMBEDDED CONTROLLERS AUDIO FOR DEVICES

Op code

Operand

Literal Meaning

advancing the Program Counter as it does so. After the execution cycle, the Program Counter now points one byte past the last byte of the operand, which is the first byte (op code) of the next instruction. The computer loops back to perform the next fetch cycle, and this two-step sequence repeats over and over until the system power is turned off. The speed of performing the fetch and execution cycles determines the computer's perceived speed. Most digital signal processor (DSP) chips, being in a special class of microprocessors, have special mechanisms that perform the fetch and execution cycles simultaneously. Subroutines Specific blocks of instructions often occur more than once in a program. Rather than rewrite this block several times (wasting time, memory, and making future maintenance of all the redundant versions a chore), we can create a subroutine that can be called and executed from any point in the program. When the subroutine ends, the program resumes where it left off. The process of executing a subroutine is called a jump to subroutine. Most microprocessors have an instruction for this. When a subroutine is called, the content of the Program Counter is stored so that the computer knows where to return when the subroutine ends.

0) 10100001 1) 00000001 FETCH #1 2) 10101011 3) 00000010 ADD I to 2 4) 11000111 5) 00010000 STORE result in 6) 00000000 address 00010000 0000000 (hex $1000) The first two instructions in the above example, at addresses 0) and 2), have one-byte operands. The third instruction, at address 4), has a two-byte operand, How do we decode this program? Application books for your microprocessor will give a detailed list ofop codes. In our example, op code 10100001 means "fetch the number" given in the operand [2], which is binary 00000001 (decimal 1). The second instruction, op code 10101011, says "add the number fetched above to the operand," which is binary 00000010 (decimal 2). The final instruction, op code 11000111, says "store the result in the address specified by the operand bytes," which is binary 00010000 00000000 (hex $1000). Thus, this machine language program performs the operation (1+2) and stores the result in the 16-bit address $1000. The operand does not necessarily always hold the data for an op code (as in the above example), but can sometimes merely point at the data. Different addressing modes dictate where the op code finds its data. Each microcontroller can use any or all of various addressing modes, including inherent, immediate, direct, extended, indexed, or relative. The op code specifies the addressing mode, so your computer always knows which addressing mode to use for a given instruction, Because the computer knows the required addressing mode for each op code, it also knows how many more data bytes are in the operand and what to do with them. Instruction Cycles

Assembly

Language

While it's possible to write a program directly in your computer's machine language, programming in numbers has obvious limitations. For programs that work with tight timing or memory constraints, assembly language is o_en the best choice. Assembly language associates a short name (called a mnemonic) with each machine instruction. Instead of telling the computer to "$AB" ,(add two numbers), you say "add" in assembly language. Assembly language not only assignsnamesto machine code instructions, it allows the programmer to give meaningful names to constants and variables. A variable is a specific address where known data is stored. For example, when doing addition we can use the assemblylanguage instruction "sta RESULT" to tell the computer to store the contents of the accumulator register (the "sta' op code) in address$1000, provided that the variable, RESULT, was defined as number $1000 earlier in the program. The variable names are meaningful to the programmer; the corresponding numbers are meaningful to the computer.

The embeddedcontrol computer repeatstwo basic steps: (1) Fetch the next instruction from memory (2) Perform the prescribed action The fetch cycle always reads the instruction (the op code) pointed to by the Program Counter. The Control Unit then looks at this new op code to find out what it's supposed to do. During the execution cycle, the computer reads any operand bytes and performs the instruction. After locating the operand data (based on the op codespecified addressing mode), the instruction is performed,

AES13th INTERNATIONAL CONFERENCE

103

BARTLE'I-r::'_

.....

High Level anguages L Solving real world problems in assemblylanguagecan also be awkward, since we ilormally do not consider 'problems from the perspective of binary data manipulation. Moreover, since different computers generally speak different sets of machine code instructions, a program written in assembly language for one computer will seldom execute on other computers, High level languages such as C and BASIC (an acronym for Beginner's All-purpose Symbolic Instruction Code) provide the programmer a set of instructions that more closely resemble a human language. For example, some typical instructions in BASIC include "PRINT," "C = A+B,' and "IF this is true THEN do that." Eventually, high level programs need to be translated to computer's machine code numbers. Special computer programs called compilers translate (compile) the high level instructions into the low level (machine code) instructions understood by the computer. As a result, a highlevellanguagewillworkwithanycomputerthat has a compiler (translator) available for that language. Back to the Basics: Creating Firmware Figure 4: The Termination Box Symbol The oval symbol in Figure 4 represents the beginning or end of a sequence of instructions. It is a termination box.

Do This
Figure 5: The Operation Box Symbol The operation box symbol in Figure 5 represents a processing or command operation. It contains a few words explaining what operation is performed. __

Efficient, elegant firmware can be difficult to write. The programmer must follow three basic steps: Figure 6: The Decision Box Symbol (1) Define and understand the problem and solution (2) Design a step-by-step approach to to the solution (3) Translate the solution into a sequence of instructions Example: A MIDI Sequencer Remote Control The decision box symbol in Figure 6 represents a decision point and usually asks a question. The answer to this question routes the program to one of two or more possible paths.

Step 1: Define attd Understand the Problem Our sequencer remote control should operate like a VCR remote control. Press Play and the sequencer starts to play; press Stop, and it stops. If you press Pause while the sequencer is playing, the sequencer pauses; if you press Play or Pausewhile the sequenceris paused,it will continue playing from the point where it was paused. Step 2: Design a Solution to the Problem Breakthe solution into small steps. These steps must be specified carefully since any ambiguities or discrepancies in the solution could lead to unspecified results. Programmers use an assortment of tools, such as the /Tow chart, to break the solution of big problems into small steps. Flow charts are very personal -- no two programmers will draw the same diagram to solve the same problem. However, there is a basic set of symbols.

ii=,"-

Figure 7: The Instruction Flow Symbol Instruction Flow Symbol arrows (Figure 7) show the flow of instructions. All other symbols in the flow chart have one arrow entering them and one or more exiting. Figure 8 shows a completed flow chart for the operation of our MIDI sequencer remote control.

104

AES3th 1 INTERNATIONAL CONFERENCE

EMBEDDED CONTROLLERS AUDIO FOR DEVICES

CALL _.,_ somewhere else in the computer's memory. In this Thiscallsa subroutine- another blockof instructions example, the READ_KEYS subroutine is a preexisting block of instructions that reads the remote's keypad. IF...THEN 1F the following condition is true, THEN do the action specified after the "THEN" part of the instruction. GOTO This forces the program to start executing instructions from the specified line number. You'll notice that each line in the BASIC program starts with a unique number. These line numbers define the order in which instructions are executed, from the lowest number to the highest. GOTO instructions specify line numbers so the program knows where to go. Following each block of lines is an explanation of what ,_-_ _[]'-_ the lines mean. Here we go... 10 REM MIDI SEQUENCER REMOTE CONTROL 20 REM 4DEC94 GBARTLETT 30 REM 40 REM SUBROUTINES CALLED ARE: 50 REM 60 REM 70 REM 80 REM 90 REM 100 REM 110 REM 120 REM 130 REM 140 REM 150REM 160 REM READ_KEYS reads keys, loads NEWKEY (where NEWKEY--vafiable with a code corresponding to the key status.) NEWKEY codes: =0 No key is pressed = 1 Play key is pressed =2 Pause key is pressed =3 Stop key is pressed MIDI START sends a MIDI START

t_l.%-.nu_ Rm_

Figure 8: MIDI Remote Control Flow Chart Step 3: l?anslate the solution into instructions Translating the flow chart defined above into a list of instructions the computer can understand is often called coding, and represents the most varied element of programming. There are many different computer languages and tools used to create code. The programmer's choice of a language is left up to personal preference and economics. Your options range from the computer's native iow level machine language to many generic highlevellanguages. First we will write the MIDI sequencer remote control program in BASIC, and then in 68HC705 assembly language. Try to follow each program's flow of instructions against the flow chart. BASIC Program Solution Only four different BASIC instructions are needed to completely code the MIDI sequencer remote control example: REM Text following this instruction is a remark intended for humans (programmers and curious bystanders) who want to understand what's going on. The computer ignoresREM instructions,

170 REM 180 REM MIDISTOP sends a MIDI STOP 190 REM 200 REM MIDl_CONT-sends a MIDI CONTINUE 210 REM Lines 10-210 give useful information for someone looking at the program. 220REM ---keypressed? 230 CALL READ KEYS 240IFNEWKEY 0 THEN = GOTO 220 This block calls the READ_KEYS subroutine to check to see if a key has been pressed. If the result of reading the keysis 0, no key has been pressed (see REMark line 110); the program goes back to line 220, waiting for the next key to be pressed.

AES 13thINTERNATIONAL CONFERENCE

105

BARTLETT

250 REM---whichkey? 260 IF NEWKEY = 2 THEN GOTO 220 270 IF NEWKEY = 3 THEN GOTO 220 280 REM --- send MID1 Start 290 CALL MIDI START If the result of READ_KEYS was not 0, the program does not go back to line 220 but instead keeps moving to line 250. If READ_KEYS returns 2 or 3, the program now goes back to line 220. However, if READ_KEYS returns 1 (the Play key is pressed), the program goes to line 290, and sends a MIDI start command. 300 REM --- key pressed? 310 CALL READ_KEYS 320 IF NEWKEY = 0 THEN GOTO 300 We've now started the sequencer playing. It's time to check whether another button has been pressed. If READ_KEYS now returns 0 (no key pressed), the program loops back to line 300 until READ_KEYS returns something non zero. 330 REM --- which key? 340 IF NEWKEY = 1 THEN GOTO 300 350 IF NEWKEY = 2 THEN GOTO 390 If the NEWKEY variable is 1, the Play key has been pressed. Since the sequencer is already playing, the program loops back to line 300 to read the keys and see ifa value other than 0 or 1 shows up. lfthe NEWKEY variable read by READ_KEYS is 2 (Pause has been pressed), the program jumps to line 390. If the variable is 3 (the stop key has been pressed), the program moves on to the next blockof code. 360 REM --- send MIDI Stop 370 CALL MIDI_STOP 380GOTO220 If the variable was 3, the program sends a MIDI Stop command. After doing that, the program jumps back to line 220 and waits for the next button press. 390 REM --- send MIDI Stop 400 CALLMIDI_STOP If the variable was 2, then line 350 instructed the program to jump to line 390. The program sends a Stop command to pause the sequencer. 410 REM--- keypressed? 420CALL READ_KEYS 430 IF NEWKEY = 0 THEN GOTO 410 This block of code is very similar to lines 300-320. If no

key is pressed (NEWKEY=0), looping backto line410.

the program keeps

440 REM --- which key? 450 IF NEWKEY = 3 THEN GOTO 220 If the Stop key is now pressed, the program sends a MIDI Stop command. After, the program jumps back to line 220 and gets ready for the next button press. 460 REM --- send MIDI Continue 470 CALL MIDI_CONT 480 GOTO 300 What happens if READ_KEYSreturned a 1or 2 back in line 420? The program skips lines 420-460, and sends a MIDI Continue command. Assembly Language Program Solution

This example is meant to give you an idea of what an assembly language program looks like. Consider this an introductiononly; for further details,look at the 68HC705 programmer's manual.[2] Since assembly language is a lower level language than BASIC, we'll need to use more types of instructions; they will have less intuitive meanings compared to BASIC. However, there are some similarities between the two languages. Both languages support comments for human eyes only (assembly language comments are typically prefaced with a semicolon rather than BASIC's REMs), both use subroutines to do the generic stuff, and both follow the same flow chart. Assemblylanguagedoes not use line numbers. Instructions are executed in the order they appear. In a sense,the address of each instruction in memoryis its line number. Labels refer to specific instructions that markareasof the program.Programmers referto keep p labels short (to keep the code readable), so labels often resemble words on personalized license plates. Here we go... Sequencer Remote Control example ; using 68HC705assemblylanguage ; 4DEC94 GBartlett ; Subroutines called by this program: ; ' ' ; ; READ_KEYS reads keys; loads the NEWKEY variable (declared somewhere else) with a code correspondingo the keystatus. t NEWKEY codes: =0 No key ispressed =l Play key is pressed

106

AES13th INTERNATIONAL CONFERENCE

EMBEDDED CONTROLLERS AUDIO FOR DEVICES

' '

=2 Pause key is pressed =3 Stopkeyis pressed MIDI START sends a MIDI START MIDI STOP sends a MIDI STOP MIDI CONTsendsa MIDICONTINUE

'--- keypressed? RDKY3' jsr Ida cmp beq '--which key? crop beq /tI RDKY 1 ;Stop? ;yes! READ_KEYS NEWKEY /tO RDKY3 ;read the key status ;No key pressed? ;yes

;---Program Entry BEGIN: ;--key pressed? RDKYI' jsr Ida cmp beq ;--~ which key? cmp beq cmp beq /t2 RDKY1 tt3 RDKYI ;Pause? ;yes! ;Stop? ;yest READ_KEYS NEWKEY /t0 RDKY 1 ;read the key status ;No key pressed? ;yes!

;if we get here it must pause or play ;--- send MIDI Continue jsr jmp '---program exit ;actually, this program never ends ;butwewillcallthisthe endanyway! rts ;traditionally, this program would ' have been called as a subroutine so execute "return a from subroutine" ' when itends.. Maybethisis notthe mostbrilliant roseyou'veever p seen. The important point is that we have defined our problem,comeup with a solution,and codedthat solution in a form the computer can understand. Introducing State Machines MIDI_CONT RDKY2 ;go to subroutine :wait for stop/pause

;ifwegethereit mustbeplay '--- send MIDI Start jsr MIDISTART ;goto subroutine

;--key pressed? RDKY2: jsr Ida cmp beq '--- which key? cmp beq cmp beq

READ_KEYS NEWKEY #0 RDKY2

;read the key status ' ;No key pressed? ;yesT

#1 RDKY2 /t2 RDKY2A

;Play? ;yes! ;Pause? ;yest

;if we get here it must be stop ;--- send MIDIStop jsr jmp RDKY2A: ;--- sendMIDI Stop jsr MIDI_STOP MIDI_STOP RDKY 1 ;go to subroutine ;go wait for Play

The flowchart isjust one way to documenta solutionto a particularproblemIt works wellfor problemsof simpleor intermediatecomplexity.However,with more sophisticated problems, the flow chart can grow unwieldy and sprout hundreds of boxes and arrows. In particular, flow charts are not very usefulfor eventdriven control applications that have many inputs (e.g., pushbuttons)and functions.For these applications, he t state machine provides an improved model. Whereas the flow chart gives the designer complete freedom to create any possible web of instructions, the statemachine prescribes onerigidmodel that canbe used to implement a huge number of different systems. In other words, the state machine a predetermined is program structure that adapts to the application

;go to subroutine

AES13thINTERNATIONAL CONFERENCE

107

BARTLETT

And four output actions: The fundamental tenet of a state machine is that its output is a function of its current state and inputs. State The state machine is always sitting in a known state. A state is a condition. The MIDI sequencer remote control has three states: stopped, playing and paused. Each state defines what is happening fight now. lnput Events The state machine responds to a set of input events. Our sequencer remote control recognizes three input events: Play button has been pushed Stop button has been pushed Pause button has been pushed When any of these input events occur, the remote control changes state. If necessary, it can "change" to sequencer is playing and you press Stop, the remote enters the stopped state; when you press Play, it enters the playing state, and so to. the same state if it wants on. For example: when the Output Actions Output actions are the tasks performed by the device. The sequencer remote control's actions are: send a MIDI Continue message. a MIDI state machine send a MIDI Start message; sendSince the Stop message; is always of twiddling our thumbs while waiting for the equivalent doing something, we also need to include something to do. We call this the idle action. Output actions occur only in response to input events, This type of state machine is called a "Mealy Machine."[ 1] Input events cause two things to happen: (1) The state machine changes state (2) It performs an output action State Machine Implementation: The MIDI Sequencer Remote Control The best way to understand a state machine is to actually build one. Our remote control has three states: State 1: Stopped State 2:Playing State 3: Paused Three inputevents: Action Action Action Action 1' 2: 3: 4: Send MIDI Start message Send MIDI Stop message Send MIDI Continue message Idle (sit around and twiddle thumbs)

After defining these states, events, and actions, we can draw a state transition (bubble) diagram of the state machine. The bubble diagram consists of two symbols: (1) A bubble represents a state (2) An arrow represents a response to an input event Written adjacent to each arrow is the input event corresponding to this arrow, and (separated by a slash symbol) the output action executed as the state machine transitions to the next state pointed to by the arrow. The bubble diagram for our remote is given in Figure 9.

rmt _. P /Idb ___ v IStart , S_a/n_ St.o

Smj_/.=e / _'Le i P (;';"_})_J' _ xx-,,__/k_l


_K

-,
.-'_'_a_

_ --_,_ \

_tiox_tn/MDl\

I Pd"'Y_i O ) ) P_m-_/l_rcii_&_ _/_... ..... / S_

Figure 9: State Transition (Bubble) Diagram. The bubble diagram fully describes the operation of the state machine. If we know the current state (what we're doing now) and detect an input event, the bubble diagram tells us what to do (the output action) and what state to transition to (what to wait for next). Seeif you can read the operation of the sequencerremote control directly from the bubble diagram. When the sequenceris stopped (state), and you hit the play key (event), you send a MIDI Start (output action) and start playing (next state); etc. State Matrix Bubblediagramsare fun to draw,but computerscan not read them; they must be translated to machine code. One way is to translatethe operationof the state machine to a table of numbers called a state matrix. lnput events correspondto rows of the state matrix;

Event 1:Play keypressed Event 2: Pause key pressed Event 3: Stop key pressed

108

AES INTERNATIONAL 13th CONFERENCE

EMBEDDED CONTROLLERS AUDIO FOR DEVICES

states are represented by columns. Each column/row intersection in the state matrix dictates the next state and output action performed when that event occurs during that state. The state matrix:for the sequencer remote control would look as follows:. Events' I...................... Stopped Play Playing/ pressed Send Start Pause Stopped/ pressed Idle Stop Stopped/ pressed Idle States ....................... Playing Paused Playing/ Idle Paused/ Send Stop Stopped/ Send Stop Playing/ Send Cont Playing/ Send Cont Stopped/ Idle [

computer how to use the data found in a state matrix. A state machine operates in a simple loop, forever: (1) (2) (3) (4) (5) (6) Did we get an input event? No? goto 1: Yes? goto 2 Look up output action from state matrix Perform output action Look up next state from state matrix Transition to new state Go back to number l

The entire program only requires these 6 lines of code, the state matrix, and the simple output actions. The state machine is an efficient model for event-driven programs. The generic embedded control design discussed in the next section is based on a state machine. Typical input events are pushbutton presses, data fader moves, and MIDI data reception. Typical states are "Select MIDI channel", "Select This", and "Transmit That". Typical output actions are "Send a message," "Write something into the LCD display,""Set the MIDI Channelto the value specified by the data fader," and so on. Firmware Development

Each row/column intersection shows the resulting "next state/output action" when the row's input event occurs while in that column'sstate, The above state matrix completely describes the operation of the sequencer remote control, just as the bubble diagram did. You should be able to read the entire operation of the remote directly from it. Notice that the matrix is defined with labels (groups of common words) corresponding to each event, state, and action. These labels canbe assignedunique numbers that get programmed into the computer. If we usethe numbers originally assignedto the states,events, and actions of the sequencerremote (just before Figure 9), we get the following matrix: 2,1 1,4 1,4 2,4 3,2 1,2 2,3 2,3 1,4

Producing a tangible program involves several steps. The program must be written, converted to a list of machine instructions the computer can understand, and debugged. These stepsare almost always performed on a personal computer, requiring an assortment of software tools that help you write and debug your firmware. Source Code Regardlessof the language usedto write firmware, it is initially written on a personal computer with a word processing program. The resulting file is the sottrce code file. This is the program's master record; future modifications are made by modifying the source code. Assembler Source files written in assembly language require an assembler program to translate the source file (which is, of course, a list of assembly instructions) into machine language instructions (which is the only thing the computer can understand). The resulting file is called object code. Object code is what ultimately gets loaded into your embedded control computer's memory. Compiler Depending on the high level language, compilation can involve a number of steps. Often, the high level language is first translated to assembly language. An assembler then translates this to machine language.

This matrix can be written directly into the computer's memory as 2,1,2,4,2,3,1,4,3,2,2,3,1,4,1,2,1,4. Only 18 numbers describe the MID1 sequencer remote control's operation! This is the beauty of the state machine. Poorly written programs often malfunction because the programmer overlooked a peculiar input event at an unanticipated time. One of the charms of the state machine is it defines a reaction for every possible input event during every possible state. The state machine forces the programmer to take complete responsibility for all possible circumstances. State machines are very robust; it is difficult to crash them. Coding A State Machine The actual code for a state machine must tell the

AES 13thINTERNATIONAL CONFERENCE

109

BARTLETT

Linker An individual source code file frequently does not contain a complete program. Programs are typically split into several source code files that isolate certain parts of the program. Each file covers only one particular resource or peripheral device contained in the computer, For example, one source file might contain all LCD source code, another the Switch code. By partitioning a large program, several programmers can work on one product, and you can modify certain pieces without disturbing the rest of the program. If we want to change the program to support a different LCD, we simply replace the LCD file, leaving the rest of the files alone, Since a program can consist of many source code files, something needs to tie them all together before they can feed the computer. This is the linker's job. Linkers link object code, so each source file must first be individually assembled (assuming they are assembly language source files), and the resulting object files linked into one big object file. High level language compilers generally take care of linking for you. Debugging Programmers like to say they are debugging, rather than admit they are fixing their mistakes. There are a variety of debugging tools available that generally aid the programmer in finding flaws in the object code, which must be fixed in the source code. Loading and Running a Program

INTRODUCING A GENERIC EMBEDDED CONTROL COMPUTER A generic embedded control computer was developed as a simple platform for MIDI application development. Known as the MIDItools Computer, it is a simple, inexpensive and accessible platform for developing embedded control applications. It was designed for: Generic operation -- Since this one computer was intended to support many different applications, it had to be flexible enough to accommodate them. Modularity -- The computer is configured using a number of modular circuit boards. These provide a ?building block" approach so that auxiliary circuit boards can be designed, built, tested and changed independently. Simplicity -- The original design goal was to use this platform to create a set of useful MiDI devices. Inexpensive and easy-to-findparts -- The parts required to build the MIDItools Computer are common. Block Diagram

The modules are the CPU board, the Standard Human Interface board (H/I board), and the Expansion board(s). The circuit boards interconnect with standard 16-wire ribbon cables, eliminating point-to-point wiring. Schematics for the MIDIt0ois Computer CPU and Standard H/I boards are given in Figures 14 and 15 at the end of this text. Specifications can be obtained from PAVO 10 S. Front St., Phila. PA 19106; 215-413-2355. Figure 10 shows the block diagram.

Once you have your object code file, it must be loaded into your computer. If the program is destined for a source code program is first written, assembled,and
control board, then transfer the the resulting object code to a device called an EPROM programmer, which writes the object code into an EPROM or OTPROM (One Time Programmable ROM). The PROM is then plugged into your circuit board. small microprocessor-based embedded linked on a personal computer. You

_ MIDInterface I O_T T_RU I I _


SPI Bus

OPfinal Expansin Bird

I Expansion Connector

Resetting the microprocessor, by connecting the "reset" pin on the microcontroller chip to logic 0 sets its PC to the first op code in the program and starts cranking out the fetch/execute cycles. It's that simple! If you use an EPROM, it can be erased by exposing the chip to intense ultraviolet light. If your program doesn't work, just erase the EPROM, change the program's source code, assemble, link and reprogram!

68HC705

Contro_ us B
ParallelData Bus

Switch Bus Standard HIIBoard switches, LEDs, pot) Figure 10: MIDItools Computer Block Diagram [1

110

AES 13th INTERNATIONAL CONFERENCE

EMBEDDED CONTROLLERS AUDIO FOR DEVICES

The CPU Board The heart of the CPU board is Motorola's 68HC705 microcontroller. The 68HC705 contains plenty of RAM and ROM, lots of I/O ports, a Serial Communications Interface (UART), and enough power for sophisticated MIDI processingfunctions. However, the 68HC705 does not contain everything we want -- and we wouldn't want it to. Implementing some resources outside the microcontroller allows for greater flexibility. Note that the components most likely to change from one application to another (switches, LEDs, LCD, and ADC) are external to the microcontroller, Buses Peripherals connect to the 68HC705 via four buses. Serial Peripheral blterface (SPI) Bus The SPI bus connects the 68HC705 to-devices with serial data interfaces. The SPI bus is especially useful for interfacing between circuit boards since it requires only three wires for two-way data communication. The downside is that each bit is sent serially, so data transfer is slower than the Parallel Data bus. Parallel Data Bus' The Parallel Data bus is a general purpose bidirectional (transmit and receive) bus that connects the 68HC705 to devices with parallel data interfaces. It contains 8 lines. Switch Bus The Switch bus connects switches to the 68HC705. One pushbutton switch connects to each of the 8 bus lines. Control Bus The Control bus contains the control signals required to enable the peripheraldevices. CPU Board Peripherals

Electrically Erasable PROM (EEPROM) Turning offpower to the 68HC705 causes any data in RAM to disappear. The EEPROM stores up to 256 bytes of data external to the 68HC705 and is nonvolatile. It connects to the 68HC705 via the SPI bus. Analog to Digital Converter (AD() The potentiometer's position needs to be converted into digital information before the computer can use it. This is the job of the ADC: a four channel, 8-bit device. The ADC converts analog signals ranging from 0 to +5V at each of its four analog inputs to an 8-bit number. It connects to the 68HC705 via the SPI bus. Each change of 19.5 mV (5V divided by 256) on an analog input corresponds to a change of I in the digital domain. Liquid Crystal Display (LCD) The MIDItools Computer uses a 2 row by 16 character LCD for the human interface. It connects to the 68HC705 via the parallel data bus. Fortunately, most LCD manufacturers have standardized on one LCD control interface that accommodates all different display sizes, from 1 row by 8 character to the big 4 row by 80 character types. You can easily upgrade to one of these alternative sizes. Light Emitting Diodes (LEDs) The computer controls up to 16 LEDs, which connect to a latch that the 68HC705 controls via the SPI bus. Switches The MIDItools Computer reads up to eight switches, each connected to the 68HC705 via the switch bus. Expansion Port The Expansion Port connects the CPU board with optional expansion boards via a 16-wire ribbon cable. The port interface carries the important signals in the computer: the SPI bus, the Data bus, one input to the ADC, two general purpose control signals,and power. These signals allow for all kinds of expansion. Although not shown in the block diagram, the following peripherals also exist in the MIDItools Computer: Os'cillator The oscillator provides the computer's basic heartbeat and determines its timing. The oscillator forces the 68HC705 to perform fetch/execute cycles. Although much of the oscillator is internal to the 68HC705, it requires an external crystal for operation. Human Interface Connector The Standard Human Interface board connects to the CPU board via a 16-wire ribbon cable connector. This connection carries the signals required by the H/I board: SPI bus, switch bus, control lines, and power.

Here are the peripheral devices on the main CPU board, MIDI b_terface The MIDI interface conforms to the MIDI specification, providing MIDI In, Out, and Thru ports via 5-pin female DIN connectors. The MIDI In signal passes through an optoisolator, which converts the current flowing through the MIDI line into a voltage compatible with the 68HC705's Serial Communications Interface (SC1/UAR1). The MIDI Out and Thru connections are buffered from the outside world; if there's any'abuse to the system (like plugging the MIDI Out into the AC line), the buffer chips fry instead of the 68HC705.

AES 13thINTERNATIONAL CONFERENCE

111

BARTLETT

Firmware I'ower Supply The power supply consists of two parts: an external line transformer and an internal rectifier/regulator circuit, The Standard Human Interface Board Writing firmware involves judgment calls, just as a painter judges how to mix paint and brush it onto a canvas. What follows is not necessarily the "right" way to write software; it is just "a" way. The generic embeddedcontrol computer's firmware follows three ground rules: (1) Simplicity -- so people at all levels of computer literacy have a chance of understanding it (2) Flexibility -- so it can be adapted to many different . applications (3) Efficiency and reliability -- so the program does not crash on you during use One of the stumbling blocks to writing a program is the sheer complexity of taking care of all the little details. To deal with this, the MIDItools Computer contains a collection of basic input/output routines (the BIOS) that contain the code needed to handle low-level actions -e.g., put characters on the LCD. Relieved of dealing with the messy parts, you are free to concentrate on writing the application itself. The State Matrix is crucial to writing your own application using the modular circuit boards, as it represents a very simple and rapid way to define and solve a problem (your application). You'll recall that the basic procedure is to set up a matrix of input events (button presses, MIDI data received at the MIDI input, ADC readings) and output actions (characters to write to the LCD, LEDs to light). At the intersectionof each input event (row) and current state (column), you tell the computer what action to perform and where to go next. The MIDItool Computer's state machine recognizes three types of input events from its peripherals: button pushes, ADC (fader) changes, and MIDI data reception. Once you've configured your state matrix, all that remains is to put it into the correct format to burn, or program, into the EPROM. Firmware MIDI Patch Bay Board (provides MIDI connections for a patch bay) Relay Board (contains relays that can be triggered by MIDI data) Custom Instrument Board (a real-world-to-MIDI-converter) Structure

The Standard Human Interface board provides the "control panel" for the computer user. It provides 8 pushbutton switches, 16 LEDs, and 1 potentiometer. ,$h'i/ches The switches connect to the 68HC705 via the switch bus. The standard switch is a normally open momentary pushbutton switch. Other types of switches can be used as long as you pay attention to the voltages feeding the 68HC705. The 68HC705 considers a logical I (+5V) on a Switch bus line to represent the switch in its "ON" position; a logical 0 (0V) represents "OFF". LEDs The 16 LEDs are powered from two serial to parallel shift registers. These accept a serial input from the SPI bus, and convert the data to 8 parallel outputs. The LEDs, connected to the register outputs, turn on or off as each bit is set to logical 1 or 0, respectively. The shift registers have 8 outputs each. Since the H/I board has 16 LEDs, it takes two of the chips to handle the LED data. Pote,/iometer The Human Interface board's potentiometer feeds one ADC input. Rotating the pot from one extreme to the other changes the voltage going to the ADC from 0V to 5V. The ADC digitizes this voltage, taking a relative reading of the pot's position. The pot controls device parameters in the computer, Three of the four ADC inputs connect to the Human Interface board; two are currently unused. They can be connected to other analog voltages between 0V to 5V. Expansion Boards

The remaining circuit boards are optional expansion, or auxiliary, circuit boards that contain the unique circuitry required by a particular custom application. Three expansion boards are currently available. [ 1]

The firmware is partitioned into two general modules: Basic Input and Output Services (B105) The BIOS contains basic routines that control the M1DItool Computer's hardware, providing a foundation on which applications are built. It contains all generic stuffthat is used in all applications. Since the state machine is common to all applications, most of its

112

AES 13th INTERNATIONAL CONFERENCE

EMBEDDED CONTROLLERS AUDIO FOR DEVICES

software is located in the BIOS. Applicatio, The Application contains the routines unique to a particular application. Since the BIOS is generic, creating a new device (program) requires creating a new Application file that contains the unique source code. Output actions are defined in the Application file since they define unique reactions to input events, BIOS Module Basics

Interrupt Service Routines Some peripheral devices issue interrupts. BIOS files that support such peripherals contain an additional type of routine, the Interrupt Service Routine (1SR). An ISR is executed whenever its associated interrupt occurs. For example, the Serial Communications Interface (SCI) will issue an interrupt (if it's enabled) whenever the MIDI In port receives a byte. When this interrupt occurs, the program turns control over to the SCI ISR, located in the MID1.ASM BIOS file. ISR Call Backs

The BIOS module consists of 11 source code files. Ten of the files govern resources in the computer. The eleventh, MAIN.ASM, is the mother of all source code files; it specifies which BIOS files and Application to include (via linking) for the particular application. The BIOSfiles providedare: MAIN.ASM SYS05C8.ASM SPI.ASM T1MER.ASM MID1.ASM LCD.ASM LED.ASM SW.ASM ADC.ASM The main source code file 68HC705 system routines SP1routines Timer routines SCI (UART) and MIDI routines LCD routines LED routines Switchroutines ADC routines

You can override each BIOS ISR by using an ISR call back, which calls a custom routine at a known location in the Application file. The first thing a BIOS ISR does is jump to this address. When the Application file receives control, it has the option of immediately returning control to the BIOS ISP_ or exeCUtingts own i code. If you don't want to service a particular interrupt in the Application file you just jump back to the BIOS. Even though the MIDltoolsComputer handlesa lot of resources of varying complexity, accessing and operating these resources is straightforward. Remember, you really don't want to mess withthe private routines. Use the publicroutines;they give you fullaccess to each resource,with no headaches. To add a new peripheral to the library, you simply define a new BIOS file with private and public routines consistent with the rest of the resources. This keeps your code clean, consistent, and maintainable. Your new file would then need to be included in the MAIN.ASM file to assure that it is linked to the other BIOS files and the Application. The Application Files

EEPROM.ASM EEPROM routines STMACH.ASM State machine routines Each BIOS file contains two classes of routines: private routines and public routines. To understand the difference, consider your telephone dial. It provides a simple interface to the telephone company's complex labyrinth of cables, switches and routing technology. The dial is your simple, public interface to the underlying network. You don't care about what fills telephone company buildings; all the complicated stuffis private. Private Routines Private routines hide the BIOS' most intimate operations. They generally transfer raw data between the 68HC705 and peripherals, hiding the application from the complexity of the interfaces. Application files are discouraged from accessing these routines. Public Routines Public routines provide the public interface to the computer's resources. These routines simplify the interface between an application and the resources by shielding the application from all the details handled by the private routines. For example: public LCD routines write information into the LCD by passing simple commands to the BIOS; the details of what codes to send over what ports are handled by private routines.

Although each Application file is unique, they follow the same format. Each file contains six ingredients: (1) A comment header at the top of the file that describes what you need to know about the application (2) Declaration of constants and variables (3) Specification of the State Matrix (4) Initialization code that resets variables to default values and writes defaults to the displays (5) Output action subroutines that perform the unique functions of the application. They are referenced in the state machine and called automatically whenever their corresponding input events occur (6) ISR call back routines that allow the Application to

AES INTERNATIONAL 13th CONFERENCE

113

BARTLE'fT

service interrupts as needed, or return to the BIOS ISR The actual code found in each of the above six categories in each Applicatlon file is unique. To design a new device, just fillin the six sections. In most cases, it takes only a couple of hours to create a new device! The following example Application file -- "Adjust a number and displayit in the LCD" -- outlines the process. The end of the listing has an explanation. 1, I EXAMPLE.ASM Rev1.0 I ' Adjust number a 1; I The user can,set the value of a number. I, 1 ' Operation: I' 1' I ' 1' 1; HOW DO I... ...INCREMENTTHE NUMBER? The number is incremented by pressing the + key ...DECREMENT THE NUMBER?

3; ............................................................. 3 3 ;--- Enumerate states 3 3 StNum EQU 0 3 3 ;--- Map application events to BIOS events 3 3 EvIdle EQU EV IDLE 3 Evlnc EQU EV SW4 ON 3 EvDec EQU EV SW8 ON 3 EvFdr EQU EV FDR MOVE 3 3 ;---Build StateMatrix 3 3 STM BEGIN 3' State 0:StNum 3' Event NextSt,Act 3 3 3 3 3 STM_ROW Evldle, StNum, IDLE STM_ROW Evlnc, StNum,_NC STM_ROW EvDec, StNum,NUMDEC STM_ROWEvFdr, StNum,NUMFDR

1; The number is decremented by pressing the - key 1.; I ...ADJUST THE NUMBER WITH THE FADER? l; The numberis adjustedwiththe fader 1; ....................................................... I LCD Screen: I; )Number:_XXX [ where XXX= 1-256 i, t [ I ;......................................................... 1-;'Hardware: .1 ' This device uses the CPU board and one H/I board 1; .......................................................... 1; States: t StNum 1' I ' Actions: 1; IDLE 1 NUMINC 1 ' NUMDEC 1 ' NUMFDR 1, Setthenumber

3 STM END 4; ............................................................. 4 Application 4; ................................. ............................ 4 4 .CODE 4 .RELATIVE 4 APPLICATION: 4 4 ;--- Initialize variables 4 4 4 4 Ida sta #0 NUMBER ;default values

NoAction Incrementthe number Decrementthe number Set numbervalue withfader

4 ;--- Initialize display 4 4 4 4 4 4 4 4 4 4 4 4 4 ;greetthe human jsr LCD_CLEAR LCD_PUT S"Example..." Ida Idx jsr #0 #1 LCD GOTOXY

2; ............................................................ 2 Variables 2; ............................................................ 2 2 2 2 .PAGE0 .ABSOLUTE .DS I ;valueof the number

LCD_PUT_S "Adjust Number!" a jsr DELAY 1SEC ;Setup static labels jsr LCDCLEAR LCDPUT S"Number: "

2 NUMBER

4 4 4 4

3; ............................................................. 3' State Matrix

114

AES13th INTERNATIONAL CONFERENCE

EMBEDDED CONTROLLERS AUDIO FOR DEVICES

4 4 jsr NUMDISP ;updatedisplay 4 4 ;---Execute statemachine 4 4 jmp STM_RUN 5; ............................................................ 5 Actions 5; ............................................................ 5 5 ;--- action No 5 5 IDLE:ts r 5 5 ;---Increment Number 5 5NUMINC: 5 Ida NUMBER ;fetchnumber 5 inca ;incrementvalue 5 sta NUMBER ;save new value 5 jsr NUMDISP ;updatedisplay 5 rts 5 5 ;--- DecrementNumber 5 5 NUMDEC: 5 Ida NUMBER ;fetchnumber 5 deca ;decrement value 5 sta NUMBER ;savenew value 5 jsr NUMDISP ;update display 5 tis 5 5 ;--- Set number value with fader 5 5 NUMFDR: 5 Ida FDR 5 sta NUMBER 5 jsr NUMDISP 5 rts 5 5 ;--- Updatedisplay 5 5 NUMDISP: 5 Ida #15 5 ldx #0 5 5 5 5 jsr !da jsr rts LCD_GOTOXY NUMBER LCD_PUT_I ;fetchfader value ;save new value ;update display

6TIMERB: C 6 jmp TIMER_HOOKRET 6 6 SCI TX CB: 6 imp SC1 TXHOOKRET 6 6 SCI RX CB: 6 jmp SCI_RX HOOK RET 6 6SC1 RX CB S: 6 jmp SCI_RX OOK RET H S 6 6SCI RXCBDI: 6 imp SCI_RX HOOK D1 RET 6 6 SCI RX CB D2: 6 6 jmp SCI_RX HOOK D2RET

In the above example,the numbersat the left of each line indicate the six Applicationfile "ingredients." Uomment Header (1) Thecomment eader rovides h p alltheuseful nformation i about the application;the hardware configuration, operating instructions, LCDinformation, inputevents, and output actionsimplemented the statemachine. by Constants and [briables (2) This application defines one variable, NUMBER. No constantsare defined. State Matrix (3) State Matrix definitionbegins by defining a constant for thisapplication's onestate:StNum. hisconstant akes T m the StateMatrixeasierto read. Constants also are defined for each input event. The BIOS input events have generic names (EV_SW4_ON, EV_SW8_ON, and EV_FDR_MOVE). By.renaming these with applicationspecific names, he StateMatrixis easier read.Finally, t to theStateMatrix rowsaredefined withtheSTM ROW macro.Thismacroreceivesthe inputevent corresponding to each row, followed by the state/output actionpairs. You shouldbe ableto read the StateMatrix and understandthe operation of the application. btitialization (4) Executable code starts with the initializationsection which sets all variables (in this case, just NUMBER) to default alues v andinitializes thedisplay. isplay D initialization begins with a greeting message, and finishes . by writing the static text (in this case, the "Number:" label)inthe LCD. Callingthe BIOS STM RUN routine then executes the state machine. Output Actions (5) Thefirstaction, IDLE, oesn't d doanything; it'scalled

;positioncursor

;fetch number ;display it

6; ............................................................. 6 InterruptCallBacks 6; ............................................................. 6 6 6 IGNORE_IRQ SWI_SPI

AES3th 1 INTERNATIONAL CONFERENCE

115

BARTLETT

whenever the input event is idle (e.g., no switches were pressed and the fader hasn't moved). The other three actions, NUMINC, NUMDEC, and NUMFDR, adjust the value of NUMBER. Notice that each action calls the NUMD1SP routine, which writes the latest value of NUMBER into the LCD. btterrupt Call Backs (6) All interrupt call backs are serviced at the end of the file. They all return control back to the BIOS ISR. If we wanted to override a BIOS ISR, we could insert our own routine here. That's all it takes to create an application using this generic embedded control design. Of course, this application is not very exciting, but you will find that most applications are not significantly more complicated,

I,evel Comrol The level control is implemented as a digitally controllable attenuator, based on the Toshiba TC9213 integrated circuit. To set the level of attenuation, you send the chip data over the SPt bus. Mute Con/roi The mute control is implemented virtually, by setting the value of the level control to full off When the device is muted, level control changes must be screened out to avoid unmuting the channel erroneously. Meter The meter is implemented using a simple peak detector circuit feeding an 8-bit analog to digital converter (ADC). The ADC data is read over the SPI bus. It can be read manually by explicitly requesting an update, or by waiting for a timeout to execute an automatic update. State Machine Deft/fition The states, input events, and output actions of the state machine are listed below. States 0: Enabled 1:Muted
Events

USING THE GENERIC EMBEDDED CONTROL COMPUTER WITH AUDIO DEVICES Consider a simple mixer input, consisting of a level control, mute switch, and signal meter. A block diagram is shown in Figure 11; the schematic diagram is given inFigure 12.
AUDIO OUTPUT

AUDIO CONTROL Figure 11' Block Diagram of Mixer Input Channel

1-Set Mute On 3' Read Meter 4: Time Out Ac/ions O: Idle +15V 1' Write level to hardware 2: Turn hardware level off(mute)

INO

(_16

22_25

3: Report current meter (ADC) value

__22/2- 141_ SCK '

1-'_1.._3

51_ _

i
-15V luF ; Figure 12: Schematic Diagram of Input Channel

OOT
TO ADC

116

AES13th INTERNATIONAL CONFERENCE

EMBEDDED CONTROLLERS AUDIO FOR DEVICES State Diagram The state transition (bubble) diagram is given below. Possibh, Extensio,s This example is simple, but it illustrates how audio functions can be implemented with embedded control. Other signal processing functions could be added to this mixer input channel such as gain trim, equalization, and level controls for aux busses. The gain trim could be implemented by replacing the preamp's gain pot with a digitally controllable resistor ladder. The EQ filters could be implemented by replacing the pot in a standard analog EQ filtercircuitwitha digitally controlled attenuator (similar to the TC9213 used for the level control above). The other level controls could be implemented with more TC9213 chips, or with VCAs (such as the THAT 2150) controlled by digital to analog converters.

ENABLED 0

MUTED 1 CONCLUSIONS Embedded control addsfunctional power to analog circuit designs. The fundamentals are not difficult to master. Existing, freely distributed, generic development platforms (e.g., the MIDltools Computer) allow the analog designengineer a robust methodology for adding embeddedcontrol functions to audio equipment in a timely, cost-efficient manner.

Figure 13: Bubble Diagram for Audio Application


Stale Machine

The state matrix is shown below. State O: Enabled 0,1 1,2 0,0 0,3 0,3 State l: Muted 1,2 1,0 0,1 1,3 1,3

Events 0 1 2 3 4

REFERENCES [1]C. Anderton, Moses B. andG BartletC Digital Projects for Musicians, (AMSCO, New York, 1994) [2] M68HC05 Applications Guide, (Motorola, Motorola Part #M68HC05AG/AD, 1989) [3] J. Ganssle, The Art of Prograrnmmg Embedded 3),stems, (Academic Press, Inc., 1992) [4] EYnbeddedSystems Programming magazine, (Miller Freeman, Inc., Nashville)

Each event-state intersection in the matrix consists of a "next state","output action" code pair. For example, the top left comer cell tells us that an input event 0 ("Set level"), occurring during state 0 ("Enabled"), results in a state change to state 0 (still "Enabled") and execution of output action I ("Write level to hardware").

AES 13thINTERNATIONAL CONFERENCE

117

BARTLETT

k?'
U

> _1
Fo _,_. Go

E II,, i:5
:._ E to

_1

Ih,

co
o

II
_._-__ _,,, _I_ I '._. _-_I_E,,
gg

___

.I I T--P-.w.-a,,.

118

AES 13th INTERNATIONAL CONFERENCE

EMBEDDED CONTROLLERS FOR AUDIO DEVICES

E
03 C3 O ('O

(..) CO o m 0_ o

e.-

.-.I '1' co "o c-

O5
'lr--

._co
LL

--i

L _ I

AES 13th INTERNATIONAL CONFERENCE

119

Das könnte Ihnen auch gefallen