Controles Embebidos Para Dispositivos De Audio

download Controles Embebidos Para Dispositivos De Audio

of 21

Transcript of Controles Embebidos Para Dispositivos De Audio

  • 8/4/2019 Controles Embebidos Para Dispositivos De Audio

    1/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 canbe easily adaptedfor use in audio products and systems. The intent of the paper is to introduce simple developmentprocedures andtools for adding computer-controlled features to audio devices.

    INTRODUCTION MemoryThis is where data is stored to and taken from .Embedded control can open up a whole new world ofautomated applications for analog audio circuits. It is Arithmetic Logic Unit (ALU)simple to add this capability by adapting an existing This performs math and logic computations on the data.g eneric em bedded control circuit to your needs.

    Control theirT his directs th e com pu ter's activ ities by p ullingEMBEDDED CONTROL FUNDAMENTALS instructions out of memory to accomplish specific tasks.

    Central Processing th,ts (CPUs9 and microprocessorsEmbedded control requires an embedded computer, are combination ALU/Control Units.C om puters process num bers. Therefore, if your dev icesettings can be expressed as numbers, they can be Mput.'OUttnt!1'0)received, generated, and modified by your computer. Input devices (e.g ., pushbutton switches) allow humans

    to talk to computers. Output devices (e.g., liquid crystalEmbedded Control Computer Hardware displays) allow computers to talk to humans.A computer has four sections, shown in Figure 1. Memory,

  • 8/4/2019 Controles Embebidos Para Dispositivos De Audio

    2/21

    BARTLETT

    There are many types of memory devices, differing in execution. A necessary part of the control unit is itsfunctionality and fabrication technology, collection of registers, or special purpose memoryaddresses.I64NI)OM A( 'C'ESS M!':MORY(RAM)This read/writeable memory, is typically volatile -- i.e., if The Program Counter (PC) holds the address of the nextthe power is removed from the circuit, data is lost. RAM instruction to be executed. After the Control Unitis availablein several forms: fetchesan instruction, the PCis updated to point to the

    next instruction. The PC is the com puter's book m arker.19ynamicRAM (DRAM)Each cell consists of a capacitor. A charged capacitor The Accumulator (AC('I.D holds the inputs and outputsmight indicate 1, and a discharged capacitor 0. Since of ALU arithmetic and logical operations. Most Controlcapacitor charges dissipate, special circuitry is required Units contain one or two Accumulators.to refresh the charg e. This refresh process happenshundreds or thousands of times each second. Riding the Bus,Static I_M (SRAM) A bus is a group of related connections that tie togetherEach cell is a flip-flop circuit that does not require elements inside a computer. For example, the transfer ofrefreshing. Since flip-flop circu itry is m ore com plex than one data byte from one memory location to anotherDRAM cells, SRAM chips are physically larger than an occurs over aparallel data bus. An 8-bit byte requiresequivalent DRAM. However, they do not require an 8-wire parallel bus (one wire per bit).D RAM's refresh circuitry. Som e SRAM can be backedup with battery power to preserve data if the main power MIDI is an example of a serial bus, since data is sent onesourcegoesaway. bitafteranother.

    READ ONLYMEMORY (ROM) Parallel busses are faster than serial busses. Operating atThis memory is nonvolatile -- i.e., if the power is the same clock speed, an 8-bit parallel bus transmits aremoved from the circuit, data is preserved. ROM is complete byte in the time it takes one bit to travel over aavailablein several forms: serialbus. However, if the parallelbus connectionis

    m ade w ith a physical cable, one w ire is required for eachProgrammable ROM (PROM) bit, increasing cost and complexity.These devices can be programmed by the equipmentmanufacturer. Unlike RAM, which can be rewritten with Input/Output (1/O)data over and over, PROM data can be written once.

    Because so much happens in the outside world thatErasable PROMs (EPROMs) might interest your computer, there are many types ofBy shining ultraviolet light through a window on top of input and output devices.its package, EPROMs can be erased. They can beprogrammed, erased, and reprogrammed thousands of Each I/O device connects to your computer at aport.times, making them convenient for prototyping The simplest I/O ports are can be quickly configured asfirmware. In production, it costs !ess to use PROMs. either an input or output, often changing designationfrom one instruction to the next.Electrically erasable PROMs (EEPROMs)

  • 8/4/2019 Controles Embebidos Para Dispositivos De Audio

    3/21

    EMBEDDEDONTROLLERSORAUDIODEVICES

    Interrupts With the control turned fully clockwise (a), thepotentiometer (pot) output shows the maximum voltage

    External events happen unpredictably, often demanding (5V). At the full counterclockwise position (b), the potthe immediate attention of the computer. Such events shows the minimum voltage (0V). In between these twomust interrupt whatever the computer is doing and force extremes, the pot output differs between the analogit to service them. For example, your computer does not extremes. The ADC converts the pot voltage into aknow when the musician is going to play a note on a binary, number that is fed to the microprocessor, in thiskeyboard, sending a MID i message. When the note is way, the microprocessor "knows" the pot's position.played, your computer must stop what it is doing anddeal with the message. Digital to attalog converters (DA('._) provide the

    com plem entary, function to AD Cs by converting a digitalComputers support a special class ofl/O called number into an analog voltage. A typical DAC convertsinterrupts. When an interrupt occurs, the computer a one-byte number to a voltage, providing a resolution ofprogram 's normal execution is suspended. The computer 256 different analog voltages.executes a special block of software (an btterruptService Routine, or ISR) written to handle the interrupt. Latches are banks of flip-flops. Most latches are 8 bits

    w id e, storing one b yte external to the m icro proc esso r.Interrupts can be generated internally as well as from Once a byte is written to an external latch, the externalasynchronous data appearing at the I/O ports. For circuitry is free to do what it wants with the informationexample, the computer's internal timer can generate a (e.g., control an LED with each latched bit).tim er interrupt at specific intervals. The tim er ISR couldthen execute a periodic software routine, such as Latches can be parallel or serial, although serial latchesblinking a light or sending a MIDI clock message, are commonly known as sh/fi registers. Most shift

    reg isters have either a serial input and parallel output, orPeripherals a parallel input and serial output. These parts are usefulin connecting a bus from one circuit board to another.A microprocessor isa very generic building block. Since Rather than running eight separateconnectionstothey find their way into every conceivable application, no connect a byte-wide bus between each board, a parallel-single device could ever have all the I/0 and memory to-serial shift register can convert the eight lines to aneeded for all applications. Consequently, most special single serial line. A serial-to-parallel shift register thenI/0 functions are implemented in off-chip peripherals, converts back to parallel data at the other end.Analog to digital converters (ADC.s;)measure analog Universal A.synchronous Receiver Transmitterssignals from the real world (audio, temperature, fader (UARI;s;)are specialized shift registers used to sendposition, etc.) and translate the values into digital data. A digital data generated by one m icroprocessor to anothertypical ADC converts an analog voltage to a one-byte device over a communications link.binary num ber, giving a resolution of 256 differentvalues. Figure 3 shows how an ADC digitizes a While normal shift registers require synchronization, apotentiometer'sposition. UARTdoes not needa clock line.To provide

    sy nchroniz ation, the receiv er and transm itter ag ree ahead+5v of time on the rate at which bits will be exchanged. To

  • 8/4/2019 Controles Embebidos Para Dispositivos De Audio

    4/21

    BARTLETT

    messages,displayingdata, drawingpictures, andso on. do =23fine = 57l?mer peripherals allow the microprocessor to mark how = 16time. They are comprised of a free-running counter just = 01running at a known fi-equency.The microprocessor reads thank = 142the counter (converting the count to real seconds if you = 09required) w henever it w ants to. Som e timers providesophisticated functions that allow the microprocessor to We can now carry on a conversation w ith someone usingsound alarms, automatically set or reset I/O ports at this new language: 16 23 09 23? 01 57 142 09!predeterm ined tim es, etc. Tim ers can also interrupt themicroprocessor so it can perform a function periodically If you can decode the above exchange, then you can(just likean alarm clock), understandmachinelanguage.Machinelanguagesimply

    assigns a unique num ber to each of the computer'sMemory Peripherals are used when the microprocessor's instructions. For example, the 68HC705 assigns theinternal memory is too limiting. One example of a following (arbitrary) code numbers:memory peripheral is an EEPROM. The interfacebetweenthe EEPROMand themicroprocessors add= 171generally a serialbus. Memoryperipherals lookjust like subtract= 160a large bank of shift registers to the microprocessor. AND = 164OR = 170Microcontrollers Since w e also need the data that w ill be added,Despite the diversity of applications for embedded subtracted, ANDed and ORed, a complete machinecontrol computers, the hardware needed tO implement language instruction requires not just the operationmany of them is very similar. For example, the codes shown above, but also the data. Therefore, anmicroprocessor+UART+LCD+memory combination can example of a complete 68HC705 instruction that adds 23be found in many musical instruments and automobile to a number in memory is:dashboards. Therefore, chip designers offermicrocontrollers that integrate a microprocessor with 171 23peripherals. They are single-chip com puters w ith amicroprocessor, memory, FO , and peripheral devices. Each program is simply a sequence of such instructions.

    Performing (1+2) and storing the result in memoryThe generic embedded control computer introduced in address $1000 looks like:the next section uses a popular m icrocontroller called theMC68HC705C8 (68HC705). This microcontroller has Address Dataseveral general purpose I/O ports, a timer, a UART, aserial I/O port, memory, and other built-in functions. 0 10100001

    1 00000001Embedded Control Firmware 2 1010101 l3 00000010

    Your computer'spowerlies in its abilityto understand 4 1100011and performa list of instructions,knownas a computer 5 00010000program or.firmware. Different computers have different 6 00000000

  • 8/4/2019 Controles Embebidos Para Dispositivos De Audio

    5/21

    EMBEDDEDONTROLLERSORAUDIODEVICES

    Op code Operand Literal Meaning advancing the Program Counter as it does so.0) 10100001 1) 00000001 FETCH #1 After the execution cycle, the Program Counter now

    points one byte past the last byte of the operand, w hich2) 10101011 3) 00000010 ADD I to 2 is the first byte (op code) of the next instruction. Thecomputer loops back to perform the next fetch cycle,4) 11000111 5) 00010000 STORE result in and this two-step sequence repeats over and over until

    6) 00000000 address 00010000 0000000 the system power is turned off.(hex $1000)The speed of performing the fetch and execution cycles

    The first two instructions in the above example, at determines the computer's perceived speed. Most digitaladdresses 0) and 2), have one-byte operands. The third signal processor (DSP) chips, being in a special class ofinstruction, at address 4), has a two-byte operand, microprocessors, have special mechanisms that perform

    th e fetc h and exec utio n c yc les s imultan eo us ly .How do we decode this program? Application books foryour microprocessor will give a detailed list ofop codes. SubroutinesIn our exam ple, op code 10100001 means "fetch thenumber" given in the operand [2], which is binary Specific blocks of instructions often occur more than00000001 (decimal 1). The second instruction, op code once in a prog ram . Rather than rew rite this b lock several10101011, says "add the number fetched above to the times (wasting time, memory, and making futureoperand," which is b inary 00000010 (decimal 2). The maintenance of all the redundant versions a chore), wefinal instruction, op code 11000111, says "store the can create a subroutine that can be called and executedresult in t he address specified by the operand bytes," from any point in the program. When the subroutinewhich is binary 00010000 00000000 (hex $1000). Thus, ends, the prog ram resumes where it left off.this m achine lang uag e prog ram perform s the operation(1+2) and stores the result in the 16-bit address $1000. The process of executing a subroutine is called a jump to

    subroutine. M ost m icroprocessors hav e an instructionThe operand does not necessarily always hold the data for this. When a subroutine is called, the content of thefor an op code (as in the above example), but can Program Counter is stored so that the computer knowssometimes merely point at the data. Different addressing where to return when the subroutine ends.modes dictate where the op code finds its data. Eachm ic r o c o n t r o l l e r c a n u s e a n y o r a l l o f v a r i o u s a d d r e s s i n g A ss e m b ly L a n g u a g emodes, including inherent, immediate, direct, extended,indexed, or relative. The op code specifies the addressing While it's possible to write a program directly in yourmode, so your computer always knows which addressing computer's machine language, programming in numbersmode to use for a given instruction, has obvious limitations.For programs that work with

    tig ht tim ing or m em ory c onstraints, a ss emb ly l anguageBecause the computer knows the required addressing is o_en the best choice. Assembly language associates amode for each op code, it also knows how many more short name (called a mnemonic) with each machinedata bytes are in the operand and what to do with them . instruction. Instead of telling the computer to "$AB"

    ,(add tw o num bers), y ou say "add" in assem bly lang uage.Instruction Cycles Assembly languagenot only assignsnamesto machine

  • 8/4/2019 Controles Embebidos Para Dispositivos De Audio

    6/21

    BARTLE'I-r::'_ .....

    HighLevelLanguagesSolving real world problemsin assemblylanguagecanalsobe awkward, sincewe ilormally do not consider'problems from the perspective of binary datamanipulation. Moreover, sincedifferent computers Figure 4: The Termination Box Symbolgenerally speak different sets of m achine codeinstructions, a program written in assem bly language for The oval symbol in Figure 4 represents the beginning orone computer will seldom execute on other computers, end of a sequence of instructions. It is a termination box.H igh level languages such as C and BASIC (an acronymfor Beginner's All-purpose Symbolic Instruction Code)provide the programmer a set of instructions that more DoThisclosely resem ble a human language. For exam ple, som etypical instructions in BASIC include "PRIN T," "C =A+B,' and "IF this is true THEN do that."

    Figure 5: The Operation Box SymbolEventually, high level programs need to be translated tocomputer's machine code numbers. Special computer The operation box symbol in Figure 5 represents aprograms called compilers translate (compile) the high processing or command operation. It contains a fewlevel instructions into the low level (machine code) words explaining what operation is performed.instructions understood by the computer. As a result, ahighlevellanguagewillworkwithanycomputerthat has __a comp iler (tra nslator) av ailab le fo r th at lan gua ge .Back to the Basics: Creating FirmwareE fficient, eleg ant firm ware can be difficult to w rite. Theprog ram mer m ust follow three basic steps: Figure 6: The Decision Box Symbol(1 ) D e fin e a n d u n d e rs ta n d th e p ro b le m a n d s o lu tio n(2) Design a step-by-step approach to to the solution The decision box symbol in Figure 6 represents a(3) Translate the solution into a sequence of instructions decision point and usually asks a question. The answer

    to this question routes the program to one of two orExample: A MIDI Sequencer Remote Control more possible paths.Step 1: Define attd Understand the ProblemOur sequencer remote control should operate like a ii=,"-V CR remote control. Press Play and the sequencer startsto play; press Stop, and it stops. If you press Pause whilethe sequencer is playing, the sequencer pauses; if you pressPlay or Pausewhile the sequenceris paused,it will Figure 7: The Instruction Flow Symbol

  • 8/4/2019 Controles Embebidos Para Dispositivos De Audio

    7/21

    EMBEDDEDONTROLLERSORAUDIODEVICES

    CALL

    _.,_ Thiscallsa subroutine- anotherblockof instructionsom ew here else in the computer's memory. In thisexample, the READ_KEYS subroutine is a preexistingblock of instructions that reads the rem ote's keypad.IF...THEN1F the follow ing condition is true, TH EN do the actionspecified after the "THEN" part of the instruction.GOTOT his forces th e pro gram to start execu ting instru ctionsfrom the specified line num ber.Y ou'll notice that each line in the BASIC program startswith a unique number. These line numbers define theorder in w hich instructions are executed, from the low estnum ber to the highest. G OTO instructions specify linenumbers so the program knows where to go.

    Follow ing each block of lines is an explanation of what,_-_ _[]'-_ the lines mean. Here we go...

    t_l.%-.nu_ Rm_ 10 REM MIDI SEQUENCER REMOTE CONTROL20 REM 4DEC94 G BARTLETT30 REM

    Figure 8: MIDI Remote Control Flow Chart 40 REM SUBROUTINES CALLED ARE:50 REMStep 3: l?anslate the solution into instructions 60 REM READ_KEYS reads keys, loads NEWKEYTranslating the flow chart defined above into a list of 70 REM (where NEWKEY--vafiable with a codeinstructions the computer can understand is often called 80 REM corresponding to the key status.)coding, and represents the most varied element of 90 REMprogramming. There are many different computer 100 REM NEWKEY codes:languages and tools used to create code. The 110REM =0 No key is pressedprogrammer's choice of a language is left up to personal 120REM =1 Play key is pressedpreference and economics. Your options range from the 130REM =2 Pause key is pressedcomputer's native iow level machine language to many 140REM =3 Stop key is pressedgenerichighlevellanguages. 150REM160 REM MIDI START sends a MIDI STARTFirst we will write the MIDI sequencer remote control 170 REMprogram in BASIC, and then in 68HC705 assembly 180 REM MIDISTOP sends a MIDI STOPlanguage. Try to follow each program's flow of 190REMinstructions against the flow chart. 200 REM MIDl_CONT-sends a MIDI CONTINUE

  • 8/4/2019 Controles Embebidos Para Dispositivos De Audio

    8/21

    BARTLETT

    key is pressed (N EW KEY=0), the program keeps250REM---whichkey? loopingbackto line410.260 IF NEWKEY = 2 THEN GOTO 220270 IF NEWKEY=3 THEN GOTO 220 440 REM --- which key?280 REM --- send MID1 Start 450 IF NEWKEY = 3 THEN GOTO 220290 CALL MIDI START

    If the Stop key is now pressed, the program sends aIf the result of READ_KEYS was not 0, the program MIDI Stop command. After, the program jumps back todoes not go back to line 220 but instead keeps moving to line 220 and gets ready for the next button press.line 250. If READ_KEYS returns 2 or 3, the programnow goes back to line 220. However, if READ_KEYS 460 REM --- send MIDI Continuereturns 1(the Play key is pressed), the program goes to 470 CALL MIDI_CONTline 290, and sends a MIDI start command. 480GOTO 300300REM --- keypressed? What happens if READ_KEYSreturned a 1or 2back in310 CALL READ_KEYS line 420? The program skips lines 420-460, and sends a320 IF NEWKEY = 0 THEN GOTO 300 MIDI Continue command.We've now started the sequencer playing. It's time to Assembly Language Program Solutionc h e c k w h e th e r a n o th e r b u tto n h a s b e e n p re s s e d . IfREAD_KEYS now returns 0 (no key pressed), the This example is meant to give you an idea of what anprogram loops back to line 300 until READ_KEYS assembly language program looks like. Consider this anreturns somethingnon zero. introductiononly;for further details,look at the

    68H C705 program mer's m anual.[2]330 REM --- which key?340 IF NEWKEY = 1THEN GOTO 300 Since assembly language is a lower level language than350 IF NEWKEY = 2 THEN GOTO 390 BASIC, we'll need to use more types of instructions;

    they w ill hav e less intuitive m eaning s com pared toIf the NEWKEY variable is 1, the Play key has been BASIC. However, there are some similarities betweenpressed. Since the sequencer is already playing, the the two languages. Both languages support commentsprogram loops back to line 300 to read the keys and see for human eyes only (assembly language comments areifa value other than 0 or 1 shows up. lfthe NEWKEY typically prefaced with a semicolon rather than BASIC'svariable read by READ_KEYS is 2 (Pause has been REMs), both use subroutines to do the generic stuff, andpressed), the program jumps to line 390. If the variable is both follow the same flow chart.3 (the stop key has been pressed), the program m oves onto the next blockof code. Assemblylanguagedoes not use line numbers.

    Instructions are executed in the order they appear. In a360REM --- send MIDI Stop sense,the address of each instruction in memoryis its370 CALL MIDI_STOP line number. Labels refer to specific instructions that380GOTO220 markareasof the program.Programmerspreferto keep

    labels short (to keep the code readable), so labels oftenIf the variable was 3, the program sends a MIDI Stop resemble words on personalized license plates. Here we

  • 8/4/2019 Controles Embebidos Para Dispositivos De Audio

    9/21

    EMBEDDEDONTROLLERSORAUDIODEVICES

    ' =2 Pausekey ispressed' =3 Stopkeyispressed '---keypressed? MIDI START sends a MIDI START RDKY3' MIDI STOP sends a MIDI STOP jsr READ_KEYS ;read the key status MIDI CONTsendsa MIDICONTINUE Ida NEWKEY

    cmp /tO ;No key pressed?;---ProgramEntry beq RDKY3 ;yesBEGIN: '---whichkey?;---keypressed? crop /tI ;Stop?

    beq RDKY1 ;yes!RDKYI'jsr READ_KEYS ;readthe key status ;if we get here it must pause or playIda NEWKEY cmp /t0 ;No key pressed? ;--- send MIDI Continuebeq RDKY1 ;yes!

    jsr MIDI_CONT ;go to subroutine;--~which key? jmp RDKY2 :wait for stop/pause

    cmp /t2 ;Pause? '---programxitbeq RDKY1 ;yes!cmp tt3 ;Stop? ;actually, this program never endsbeq RDKYI ;yest ;butwewillcallthistheendanyway!;ifwegethereitmustbeplay rts ;traditionally,his

    program would'--- send MIDI Start ' have been called as a subroutine sojsr MIDISTART ;gotosubroutine executea"return from s ub ro utin e"

    ;---keypressed? ' whentends..RDKY2: Maybethisis notthemostbrilliantproseyou'veever

    jsr READ_KEYS ;read the key status seen. The important point is that we have defined ourIda NEWKEY ' problem,comeupwitha solution,and codedthatcmp #0 ;No keypressed? solution in a form the computer can understand.beq RDKY2 ;yesT

    Introducing State Machines'--- which key?cmp #1 ;Play? The flowchart is just oneway to documenta solutiontobeq RDKY2 ;yes! a particularproblemIt workswellfor problemsofcmp /t2 ;Pause? simpleor intermediatecomplexity.However,withmore

  • 8/4/2019 Controles Embebidos Para Dispositivos De Audio

    10/21

    BARTLETT

    And four output actions:The fundamental tenet of a state machine is that itsoutput is a function of its current state and inputs. Action 1' Send MIDI Start message

    Action 2: Send MID I Stop messageState Action 3: Send MIDI Continue messageThe state machine is always sitting in a known state. A Action 4: Idle (sit around and twiddle thumbs)state is a condition. The MID I sequencer rem ote controlhas three states: stopped, playing and paused. Each state After defining these states, events, and actions, we candefines what is happening fight now. draw a state transition (bubble) diagram of the state

    m achine. The bubble diagram consists of tw o symbols:ln pu t Ev en tsThe state machine responds to a set of input events. Our (1) A bubble represents a statesequencer remote control recognizes three input events: (2) An arrow represents a response to an input event

    Play button has been pushed Written adjacent to each arrow is the input eventStop button has been pushed corresponding to this arrow, and (separated by a slashPause button has been pushed symbol) the output action executed as the state machine

    transitions to the next state pointed to by the arrow . TheWhen any of these input events occur, the remote bubble diagram for our remote is given in Figure 9.control changes state. If necessary, it can "change" to

    the same state if it wants to. For example: when the _. P /Idb___ vsequencer is playing and you press Stop, the remote rmtenters the stopped state; w hen you press Play, it entersthe playing state, and so on. -,utputActions IStartOutput actions are the tasks performed by the device. Smj_/.=e , _ --_,_The sequencer remote control's actions are: send a MIDI / S_a/n_ St.o \Start message; send a MIDI Stop message; send a MIDI _'Le i _tiox_tn/MDl\

    _K

    Continue message. Since the state machine is always .-'_'_a_doing something, we also need to include the equivalent (;';"_})_J' I d"'Y_i ) )f twiddling our thumbs while waiting for something to P P Odo. We call this the idle action. _ P_m-_/l_rcii_&_ _/_... ..... /Output actions occur only in response to input events, xx-,,__/k_l S_This type of state machine is called a "MealyM achine."[ 1] Input ev ents cause tw o things to happen: Figure 9: State Transition (Bubble) Diagram.(1) The state machine changes state The bubble diagram fully describes the operation of the(2) It performs an output action state machine.If we know the current state (what we're

    doing now) and detect an input event, the bubbleState Machine Implementation: diagram tells us what to do (the output action) and what

  • 8/4/2019 Controles Embebidos Para Dispositivos De Audio

    11/21

    EMBEDDEDONTROLLERSORAUDIODEVICES

    states are represented by columns. Each column/row computer how to use the data found in a state matrix.intersection in the state m atrix dictates the next state andoutput action performed when that event occurs during A state machine operates in a simple loop, forever:th at state. Th e state m atrix:for th e sequen cer rem otecontrol would look as follows:. (1) Did we get an input event? No? goto 1: Yes? goto 2

    (2) L ook up output action from state m atrixEvents' I...................... States ....................... [ (3) Perform output action

    Stopped Playing Paused (4) Look up next state from state matrix(5) Transition to new statePlay Playing/ Playing/ Playing/ (6) Go back to number lpressed Send Start Idle Send Cont

    The entire program only requires these 6 lines of code,Pause Stopped/ Paused/ Playing/ the state matrix, and the simple output actions. The statepressed Idle Send Stop Send Cont machine is an efficient model for event-driven programs.Stop Stopped/ Stopped/ Stopped/ The generic embedded control design discussed in thepressed Idle Send Stop Idle next section is based on a state machine. Typical input

    events are pushbutton presses, data fader moves, andM ID I data reception. Typical states are "Select M ID I

    Each row/column intersection shows the resulting "next channel", "Select This", and "Transmit That". Typicalstate/output action" when the row's input event occurs output actions are "Send a message," "Write somethingwhile inthat column'sstate, into the LCDdisplay,""Set the MIDI Channelto thevalue specified by the data fader," and so on.The above state matrix completely describes theoperation of the sequencer remote control, just as the F irm ware D eve lopm entbubblediagramdid. You should be ableto read theentireoperation of the remote directly from it. Producing a tangible program involves severalsteps.The

    program mustbe written, converted to a list of machineNotice that thematrix is definedwith labels (groups of instructions the computer canunderstand,anddebugged.commonwords) corresponding to eachevent, state,and These stepsare almostalwaysperformed on a personalaction. Theselabelscanbeassignedunique numbersthat computer, requiring anassortment of software tools thatget programmed into the computer. If we usethe help you write and debugyour firmware.numbersoriginally assignedto the states,events, andactions of the sequencerremote (just before Figure 9), Source Codewe get thefollowing matrix:

    Regardlessof the languageusedto write firmware, it is2,1 2,4 2,3 initially written on a personal computer with a word1,4 3,2 2,3 processing program. The resulting file is the sottrce code1,4 1,2 1,4 file. This is the program's master record; future

    m odifications are m ade by m odifying the source code.Th is m atrix can be w ritten directly in to th e com puter'smemory as 2,1,2,4,2,3,1,4,3,2,2,3,1,4,1,2,1,4. Only 18 Assemblernum bers describe th e M ID 1 sequencer rem ote control'soperation! This is the beauty of the state machine. Source files written in assembly language require an

  • 8/4/2019 Controles Embebidos Para Dispositivos De Audio

    12/21

    BARTLETT

    IN T R O D U C IN G A G E N E R I C E M B E D D E DLinker CONTROL COMPUTERAn individual source code file frequently does not A generic embedded control computer was developed ascontain a com plete program . Program s are typically split a sim ple platform for MID I application developm ent.into several source code files that isolate certain parts of Known as the MIDItools Computer, it is a simple,the program. Each file covers only one particular inexpensive and accessible platform for developingresource or peripheral device contained in the com puter, embedded control applications. It was designed for:For example, one source file m ight contain all L CDsource code, another the Switch code. By partitioning a Generic operation -- Since this one computer waslarge program , several programmers can work on one intended to support many different applications, it had toproduct, and you can modify certain pieces without be flexible enough to accommodate them.disturbing the rest of the program . If w e want to changethe program to support a different LCD, we simply Modularity -- The computer is configured using areplace the LCD file, leaving the rest of the files alone, number of modular circuit boards. These provide a

    ?building block" approach so that auxiliary circuit boardsSince a program can consist of many source code files, can be designed, built, tested and changed independently.something needs to tie them all together before they canfeed the computer. This is the linker's job. Linkers link Simplicity -- The original design goal was to use thisobject code, so each source file must first be individually platform to create a set of useful MiDI devices.assem bled (assum ing they are assem bly lang uag e sourcefiles), and the resulting object files linked into one big Inexpensive and easy-to-findparts -- The parts requiredobject file. H igh level language compilers generally take to build the MIDItools Computer are common.care of linking for you.

    Block D iag ramDebugging The modules are the CPU board, the Standard H umanProgrammers like to say they are debugging, rather than Interface board (H/I board), and the Expansion board(s).admit they are fixing their mistakes. The circuit boards interconnect with standard 16-wirerib bo n c ables, e lim ina tin g p oin t-to -p oin t w irin g.There are a variety of debugging tools available thatgenerally aid the programmer in finding flaws in the Schematics for the MIDIt0ois Computer CPU andobject code, which must be fixed in the source code. Standard H/I boards are given in Figures 14 and 15 at

    the end of this text. Specifications can be obtained fromLoading and Running a Program 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 loadedinto your computer. If the program is destined for a

    small microprocessor-based embedded control board, the _ O_T T_RU I OPfinal Expansin Birdsource codeprogram is first written, assembled,andlinked on a personalcomputer. You then transfer the I MIDInterface Iresulting object code to a device called an EPROM _ I Expansiononnector

  • 8/4/2019 Controles Embebidos Para Dispositivos De Audio

    13/21

    EMBEDDEDONTROLLERSORAUDIODEVICES

    Electrically Erasable PROM (EEPROM)The CPU Board Turning offpower to the 68HC705 causes any data inRAM to disappear. The EEPROM stores up to 256The heart of the CPU board is Motorola's 68HC705 bytes of data external to the 68HC705 and is nonvolatile.microcontroller. The 68HC705 contains plenty of RAM It connects to the 68HC705 via the SPI bus.and ROM, lots of I/O ports, a Serial CommunicationsInterface (UART), and enough power for sophisticated Analog to Digital Converter (AD()MIDI processingfunctions. The potentiometer's position needs to be converted into

    digital inform ation before the com puter can use it. ThisHowever, the 68HC705 does not contain everything we is the j ob of the ADC: a four channel, 8 -bit dev ice. Thewant -- and we wouldn't want it to. Implementing some ADC converts analog signals ranging from 0 to +5V atresources outside the m icrocontroller allows for greater each of its four analog inputs to an 8-bit number. Itflexibility. Note that the components most likely to connects to the 68HC705 via the SPI bus. Each changechange from one application to another (switches, LEDs, of 19.5 mV (5V divided by 256) on an analog inputLCD, and ADC) are external to the microcontroller, corresponds to a change of I in the digital domain.Buses Liquid Crystal Display (LCD)

    The MIDItools C omputer uses a 2 row by 16 characterPeripherals connect to the 68HC705 via four buses. LCD for the human interface. It connects to the

    68H C705 via the parallel data bus. Fortunately, m ostSerial Peripheral blterface (SPI) Bus LCD manufacturers have standardized on one LCDThe SPI bus connects the 68HC705 to-dev ices w ith control interface that accommodates all different displayserial data interfaces. The SPI bus is especially useful for sizes, from 1 row by 8 character to the big 4 row by 80interfacing between circuit boards since it requires only character types. You can easily upgrade to one of thesethree wires for two-way data communication. The alternative sizes.dow nside is that each bit is sent serially , so data transferis slower than the Parallel Data bus. Light Emitting Diodes (LEDs)

    The computer controls up to 16 L ED s, which connect toParallel Data Bus' a latch that the 68HC705 controls via the SPI bus.The Parallel Data bus is a general purpose bidirectional(transmit and receive) bus that connects the 68HC705 to Switchesdevices with parallel data interfaces. It contains 8 lines. The MID Itools Com puter reads up to eight switches,each connected to the 68H C705 via the sw itch bus.SwitchBusThe Switch bus connects switches to the 68HC705. One Expansion Portpushbutton switch connects to each of the 8 bus lines. The Expansion Port connects the CPU board with

    op tional exp ansion b oards v ia a 16-w ire ribbon cable.Control Bus The port interface carries the important signals in theThe Control bus contains the control signals required to computer: the SPI bus, the Data bus, one input to theenablethe peripheraldevices. ADC, two general purpose control signals,and power.T hese sig nals allow for all kinds of expa nsion.C PU B oard P eriphera ls Although not shown in the block diagram, the followingHere are the peripheral devices on the main CPU board, peripherals also exist in the MID Itools Computer:

  • 8/4/2019 Controles Embebidos Para Dispositivos De Audio

    14/21

    BARTLETT

    FirmwareI 'ower Supp lyThe power supply consists of two parts: an external line Writing firmware involves judgment calls, just as atransformer and an internal rectifier/regulator circuit, painter judges how to mix paint and brush it onto acanvas. W hat follow s is not necessarily the "right" w ayThe Standard Human Interface Board to write software; it is just "a" way.The StandardHuman Interface board provides the The generic embeddedcontrol computer's firmware"control panel" for the computer user. It provides 8 follows three ground rules:pushbutton sw itches, 16 L ED s, and 1 potentiom eter. (1) Sim plicity -- so p eople at all levels of com puter,$h'i/ches literacy have a chance of understanding itThe switches connect to the 68H C705 via the switchbus. The standard switch is a normally open momentary (2) Flexibility -- so it can be adapted to many different .pushbutton switch. Other types of switches can be used applicationsas long as you pay attention to the voltages feeding the68HC705. The 68HC705 considers a logical I (+5V) on (3) Efficiency and reliability -- so the program does nota Switch bus line to represent the switch in its "ON" crash on you during usep osition; a log ical 0 (0V ) represents "O FF". One of the stumbling blocks to w riting a program is theLEDs sheer complexity of taking care of all the little details. ToThe 16LEDs are powered from two serial to parallel deal with this, the MIDItools Computer contains ashift registers. These accept a serial input from the SPI collection of basic input/output routines (the BIOS) thatbus, and convert the data to 8 parallel outputs. The contain the code needed to handle low-level actions --LEDs, connected to the register outputs, turn on or off e.g., put characters on the LCD. Relieved of dealing withas each bit is set to logical 1 or 0, respectively. The shift the messy parts, you are free to concentrate on writingregisters have 8 outputs each. Since the H/I board has 16 the application itself.L EDs, it t akes two of the chips to handle the L ED data.

    The State Matrix is crucial to w riting your ownPote,/iometer application using the modular circuit boards, as itThe Human Interface board's potentiometer feeds one represents a v ery simple and rapid way to define andADC input. Rotating the pot from one extreme to the solve a problem (your application). You'll recall that theother changes the voltage going to the ADC from 0V to basic procedure is to set up a matrix of input events5V. The ADC digitizes this voltage, taking a relative (button presses, MIDI data received at the MIDI input,reading of the pot's position. The pot controls device ADC readings) and output actions (characters to writeparameters in the computer, to the LCD, LEDs to light). At the intersectionof each

    inp ut ev ent (row ) and cu rrent state (colu mn), you tell theThree of the four ADC inputs connect to the Human computer what action to perform and where to go next.Interface board; two are currently unused. They can beconnected to other analog voltages between 0V to 5V . The MID Itool Computer's state machine recognizes

    three ty pes of input events from its peripherals: buttonExpansion Boards pushes, ADC (fader) changes, and MIDI data reception.

  • 8/4/2019 Controles Embebidos Para Dispositivos De Audio

    15/21

    EMBEDDEDONTROLLERSORAUDIODEVICES

    software is located in the BIOS. Interrupt Service RoutinesSom e peripheral dev ices issue interrupts. B IO S files that

    Applicatio, support such peripherals contain an additional type ofThe Application contains the routines unique to a routine, the Interrupt Service Routine (1SR). An ISR isparticular application. Since the BIOS is generic, executed whenever its associated interrupt occurs. Forcreating a new device (program) requires creating a new example, the Serial C omm unications Interface (SCI) willApplication file that contains the unique source code. issue an interrupt (if it's enabled) whenever the MIDI InOutput actions are defined in the Application file since port receives a byte. When this interrupt occurs, thethey define unique reactions to input events, program turns control over to the SCI ISR, located inthe MID1.ASM BIOS file.BIOS Module Bas ics ISRCall BacksThe BIOS module consists of 11 source code files. Ten You can override each BIOS ISR by using an ISRcallof the files govern resources in the computer. The back, which calls a custom routine at a known locationeleventh, MAIN.ASM, is the mother of all source code in the Application file. The first thing a BIOS ISR doesfiles; it specifies which BIOS files and Application to is j ump to this address. When the Application fileinclude (via linking) for the particular application. The receives control, it has the option of immediatelyBIOSfiles providedare: returning control to the BIOS ISP_or exeCUtingts own

    code. If y ou don't w ant to serv ice a particular interruptMAIN.ASM The main source code file in the Application fileyou just jump back to the BIOS.SY S05C 8.ASM 68HC 705 system routinesSPI.ASM SP1routines Even thoughthe MIDltoolsComputerhandlesa lot ofT1MER.ASM Timer routines resources of varying complexity,accessing and operatingMID1.ASM SCI (UART) and MIDI routines these resources is straightforward. Remember, you reallyLCD.ASM LCDroutines don't want to messwiththe private routines.Use theLED.ASM LEDroutines publicroutines;they giveyou fullaccess to eachSW.ASM Switchroutines resource,withnoheadaches.ADC.ASM ADCroutinesEEPROM.ASM EEPROM routines To add a new peripheral to the library, you simply defineSTMACH.ASM State machine routines a newBIOS file with private and public routines

    consistent w ith the rest of the resources. This keeps y ourEach BIOS file contains two classes of routines: private code clean, consistent, and maintainable. Your new fileroutines and public routines. To understand the would then need to be included in the MAIN.ASM filedifference, consider your telephone dial. It provides a to assure that it is l inked to the other BIOS files and thesimple interface to the telephone company's complex Application.labyrinth of cables, sw itches and routing technology. Thedial is your simple, public interface to the underlying The Application F ilesnetw ork. Y ou don't care about w hat fills telephonecompany buildings; all the complicated stuffis private. Although each Application file is unique, they follow the

    sam e form at. E ach file contains six ing redients:Private RoutinesPrivate routines hide the BIOS' most intimate operations. (1) A comment header at the top of the file thatThey generally transfer raw data between the 68HC705 describes what you need to know about the application

  • 8/4/2019 Controles Embebidos Para Dispositivos De Audio

    16/21

    BARTLE'fT

    service interrupts as needed, or return to the BIOS ISR 3; .............................................................3

    The actual code found in each of the above six 3 ;--- Enumerate statescategories in each Applicatlon file is unique. To design a 3new device, just fillin the six sections. In most cases, it 3 StNum EQU 0takes only a couple of hours to create a new device! 3

    3 ;--- Map application events to BIOS eventsThe following example Application file -- "Adjust a 3numberand displayit in the LCD" -- outlines the 3 EvIdle EQU EV IDLEprocess. The end of the listing has an explanation. 3 Evlnc EQU EV SW4 ON

    3 EvDec EQU EV SW8 ON1, 3EvFdr EQU EVFDRMOVEI EXAMPLE.ASMRev1.0 3I ' Adjustanumber 3;---BuildStateMatrix1; 3I The user can,set the value of a number. 3 STM BEGINI, 3 State:StNum1 ' Operation: 3' Event NextSt,ActI ' HOWDOI... 3 STM_ROWEvldle, StNum,DLE1' ...INCREMENTTHE NUMBER? 3 STM_ROW Evlnc, StNum,_NCI ' The number is incremented by pressing the + key 3 STM_ROW EvDec, StNum,NUMDEC1 3 STM_ROWEvFdr, StNum,NUMFDR1; ...DECREMENTTHENUMBER? 31; The number is decremented by pressing the - key 3 STM END1.;I ...ADJUST THE NUMBER WITH THE FADER? 4; .............................................................l; Thenumberis adjustedwiththe fader 4 Application1; ....................................................... 4; ................................. ............................I LCD Screen: 4I; )Number:_XXX [ where XXX= 1-256 4 .CODEi, t [ 4 .RELATIVEI ;......................................................... 4APPLICATION:1-;'Hardware: 4.1 ' This device uses the CPU board and one H/I board 4 ;--- Initialize variables1; .......................................................... 41; States: 4 Ida #0 ;defaultaluest StNum Setthenumber 4 sta NUMBER1 4I ' Actions: 4 ;--- Initialize display1; IDLE NoAction 41 NUMINC Incrementthe number 4 ;greetthe human1' NUMDEC Decrementthe number 4

  • 8/4/2019 Controles Embebidos Para Dispositivos De Audio

    17/21

    EMBEDDEDONTROLLERSORAUDIODEVICES

    4 6TIMERB:4 jsr NUMDISP ;updatedisplay 6 jmp TIMER_HOOKRET4 64 ;---Executestatemachine 6 SCI TX CB:4 6 imp SC1TXHOOKRET4 jmp STM_RUN 66 SCI RX CB:5;............................................................ 6 jmp SCI_RX HOOK RET5 Actions 65; ............................................................ 6SC1 RX CB S:5 6 jmp SCI_RXHOOKSRET5;---Noaction 65 6SCIRXCBDI:5IDLE:ts 6 imp SCI_RXHOOKD1RET5 65;---IncrementNumber 6SCIRXCBD2:5 6 jmp SCI_RXHOOKD2RET5NUMINC: 65 Ida NUMBER ;fetchnumber5 inca ;incrementvalue In the aboveexample,the numbersat the leftof each line5 sta NUMBER ;save newvalue indicate the sixApplicationfile "ingredients."5 jsr NUMDISP ;updatedisplay5 rts Uommenteader1)5 Thecommentheaderprovidesalltheusefulinformation5 ;--- DecrementNumber about the application;the hardware configuration,5 operatingnstructions,LCDnformation,nputevents,5NUMDEC: andoutputactionsimplementedbythe statemachine.5 Ida NUMBER ;fetchnumber5 deca ;decrement value Constants and [briables (2)5 sta NUMBER ;savenew value This application defines one variable, NUMBER. No5 jsr NUMDISP ;updatedisplay constantsare defined.5 tis5 StateMatrix3)5 ;--- Set number value with fader State Matrix definitionbegins by defininga constant for5 thisapplication'snestate:StNum.Thisconstantmakes5NUMFDR: the StateMatrixeasierto read.Constantsare also5 Ida FDR ;fetchfader value defined for each input event. The BIOS input events5 sta NUMBER ;save new value have generic names (EV_SW4_ON, EV_SW8_ON, and5 jsr NUMDISP ;update display EV_FDR_MOVE). By.renaming these with application-5 rts specificnames,theStateMatrixis easierto read.Finally,5 theStateMatrixowsaredefinedwiththeSTMROW5;---Updatedisplay macro.Thismacroreceivesthe inputevent5 corresponding to each row, followed by the state/output

  • 8/4/2019 Controles Embebidos Para Dispositivos De Audio

    18/21

    BARTLETT

    whenever the input event is idle (e.g., no switches were I,evel Comrolpressed and the fader hasn't moved). The other three The level control is implemented as a digitallyactions, NUMINC, NUMDEC, and NUMFDR, adjust controllable attenuator, based on the Toshiba TC9213the value of NUMBER. Notice that each action calls the integrated circuit. To set the level of attenuation, youNUMD1SP routine, which writes the latest value of send the chip data over the SPt bus.NUMBER into the L CD. Mute Con/roibtterrupt Call Backs (6) The mute control is implemented virtually, by setting theAll interrupt call backs are serviced at the end of the file. value of the level control to full off When the device isThey all return control back to the BIOS ISR. If we muted, level control changes must be screened out towanted to override a BIOS ISR, we could insert our avoid unmuting the channel erroneously.ow n routine here.

    MeterThat's all it takes to create an application using this The meter is implemented using a simple peak detectorgeneric embedded control design. Of course, this circuit feeding an 8-bit analog to digital converterapplication is not very exciting, but you will find that (ADC). The ADC data is read over the SPI bus. It canm ost applications are not significantly m ore com plicated, be read manually by explicitly requesting an update, orby waiting for a timeout to execute an automatic update.USING THE GENERIC EMBEDDED CONTROL State Machine Deft/fitionCOMPUTER WITH AUDIO DEVICES The states, input events,andoutput actionsof the statemachineare listed below.Consider a simple mixer input, consisting of a levelcontrol, mute switch, and signal meter. A block Statesdiagram is shown in Figure 11; the schematic diagram is 0: EnabledgivennFigure12. 1:Muted

    AUDIOOUTPUT Events

    AUDIO 1-SetMuteOnCONTROL 3' Read Meter

    4: Time OutFigure 11' Block Diagram of Mixer Input Channel Ac/ions

    O: Id le+15V 1' Write level to hardware

    2: T urn h ardware le vel o ff(m ute )

    INO [ I (_16 22_25 3: Report current meter (ADC) value

  • 8/4/2019 Controles Embebidos Para Dispositivos De Audio

    19/21

    EMBEDDEDONTROLLERSORAUDIODEVICESState Diagram Possibh, Extensio,sThe state transition (bubble) diagram is given below. This example is simple, but it illustrates how audiofunctions can be im plem ented w ith em bedded control.

    O ther signal processing functions could be added to thismixer input channel such as gain trim, equalization, andlevel controls for aux busses. The gain trim could beimplemented by replacing the preamp's gain pot with adigitally controllable resistor ladder. The EQ filters could

    ENABLED be implemented by replacing the pot in a standard analog0 EQfiltercircuitwitha digitallycontrolledattenuator(sim ilar to the TC 9213 used for the level control above).The other level controls could be im plem ented w ithmore TC9213 chips, or with VCAs (such as the THAT2150) co ntrolled by d ig ital to analog co nv erters.

    MUTED1 CONCLUSIONS

    Embedded control addsfunctional power to analogcircuit designs.The fundamentalsare not difficult tomas ter. E xistin g, freely d istrib uted, g en eric dev elo pmen tplatfo rm s (e.g ., the M ID ltools C om puter) allow theFigure 13: Bubble Diagram for Audio Application analog designengineera robust methodology for addingembeddedcontrol functions to audio equipment in a

    Stale Machine timely, cost-efficient manner.The state m atrix is show n below .StateO: State l:

    Events Enabled Muted REFERENCES0 0,1 1,21 1,2 1,0 [1]C.Anderton,B.MosesandG BartletCDigital2 0,0 0,1 Projectsfor Musicians, (AMSCO, New York, 1994)3 0,3 1,34 0,3 1,3 [2]M68HC05 Applications Guide, (Motorola, Motorola

    Part #M68HC05AG/AD, 1989)Each event-state intersection in the m atrix consists of a"next state","output action" code pair. For example, the [3] J. G anssle, The Art o f P ro gr a rnmmg Embeddedtop left comer cell tells us that an input event 0 ("Set 3),stems, (Academic Press, Inc., 1992)lev el"), occu rring during state 0 ("E nabled"), resu lts in astate change to state 0 (still "Enabled") and execution of [4] EYnbeddedSystems Programming magazine, (Milleroutput action I ("Write level to hardware"). Freeman, Inc., Nashville)

  • 8/4/2019 Controles Embebidos Para Dispositivos De Audio

    20/21

    B

    E

    k?U

    >

    E

    _

    I

    i5

    F

    :_

    __

    E

    G

    to

    _

    Ih

    co

    ___

    ___I._.

    ___E

    I

    gg

    -_

    -_

    .ITPw-a

    1

    A

    hNER

    OCOERN

  • 8/4/2019 Controles Embebidos Para Dispositivos De Audio

    21/21

    EMB

    CNRLEFORAODC

    \

    E03COOE(COom_o.E.-.I'1'c"cO5'--i._cLL

    I_I

    L_I

    A1hN

    ONCN

    1