tv based crp

6
52 Issue 196 November 2006 CIRCUIT CELLAR ® www.circuitcellar.com dards—RS-170A and CCIR (typical- ly called NTSC and PAL for their color varieties)—that have different timings, lines per frame, and refresh rates. Note that the standard video sig- nal has a complex structure of sync pulses. Each video frame has two nonidentical fields (odd and even) with a fractional number of TV lines for each. Sometimes the struc- ture can be simplified (e.g., in the case of the identical odd and even fields). Normally, the TV accepts the nonstan- dard video format without glitches. As for generating the signal, the microcontroller must be programmed to output both the video bits and the sync pulses. This task was traditionally solved by software, but such a technique doesn’t produce enough elements in a TV line. Therefore, you must integrate the other tasks into the video-generating algorithm and calculate all of the durations to avoid the probable arti- facts and the synchronization glitches. VIDEO WITH THE LPC2138 In order to obtain high-resolution video, I had to generate a TV signal via the hardware as much as possible. The LPC2138 microcontroller has a PWM There are many low-cost solutions (e.g., sound card-based) based on USB stand-alone devices that will turn your PC into a digital storage oscillo- scope (DSO). All of them have a signif- icant disadvantage: when you use the PC for a measurement and other func- tions at the same time, you must click your mouse again and again to switch between applications. Of course, you may use a dedicated notebook, but the other disadvantages will remain. You could also use your old TV with a special add-on tool. Advanced micro- controllers have all the parts (e.g., ADC and RAM) for implementing such a tool with a single chip. I’ll describe a similar device in this article. My TV- based oscilloscope is built around a Keil MCB2130 evaluation board, which you can easily turn into a DSO with few pas- sive components. Note that this project requires a code size of only 16 KB, so you can use the evaluation version of the Keil CARM compiler. Implementing the oscilloscope was not my main task. I usually try new microcontrollers in video applications, so I figured this would be a good way to demonstrate the capabilities of the NXP (founded by Philips) LPC2138 microcon- troller for generating a high-resolution (512 × 240 pixels) video picture. SIMPLE VIDEO SIGNAL A standard video signal is a sequence of sync pulses and the analog waveform between them. When there are two gradations of brightness, the signal has three levels (see Figure 1). There are two basic monochrome stan- block and SPI communication mod- ule. The former can be used for gener- ating sync pulses. The latter can be used to generate the video stream! Want to know a secret? I already tried this with Cypress Semiconductor PSoC chips. Unfortunately, the capa- bilities of the PSoC SPI module did not allow me to obtain a horizontal resolution of more than 256 pixels. The useful feature of the LPC2138’s (also called the synchronous serial port (SSP)) SPI1 block is the fact that it can operate in a continuous SSI mode. It has an eight-frame FIFO buffer and can send 16-bit frames. This means that it can process a 128-bit block without participation from the software. Of course, to send more bits, the software must reload the FIFO buffer with additional data. An external DAC is required to mix both the video and sync puls- es. It can be built using a resistor matrix like the one shown in Figure 2. With a 3.3-V supply and a 75-Ω load (a TV), this matrix produces the sync and white lev- els of approximately 0.3 and 1 V. The output impedance of this sim- ple DAC is approximately 75 Ω FEATURE ARTICLE by Ilya Mamontov TV-Based Oscilloscope Ilya turned an ordinary TV into a digital storage oscilloscope with a sampling rate of 160 ksps. In this article, he explains how to use an LPC2138 microcontroller to build a high-resolution system of your own. White level Black level TV Line Horizontal sync Horizontal blanking interval Vertical blanking interval Vertical sync Figure 1This is the structure of a monochrome video sig- nal. This project uses the simplified structure of the vertical sync pulses (without equalization pulses). The number of TV lines per frame is even. SSP PWM LPC2138 Video bits Sync pulses R1 180 R2 390 R3 180 R TV = 75 Ω TV Figure 2SPP and PWM blocks generate video. The matrix of R1, R2, and R3 composes the external DAC. Circuit Cellar, the Magazine for Computer Applications. Reprinted by permission. For subscription information, call (860) 875-2199, or www.circuitcellar.com. Entire contents copyright ©2006 Circuit Cellar Inc. All rights reserved.

Upload: pratik-sharma

Post on 28-Oct-2015

37 views

Category:

Documents


5 download

DESCRIPTION

r

TRANSCRIPT

Page 1: Tv Based Crp

52 Issue 196 November 2006 CIRCUIT CELLAR® www.circuitcellar.com

dards—RS-170A and CCIR (typical-ly called NTSC and PAL for theircolor varieties)—that have differenttimings, lines per frame, andrefresh rates.

Note that the standard video sig-nal has a complex structure of syncpulses. Each video frame has twononidentical fields (odd and even)with a fractional number of TVlines for each. Sometimes the struc-ture can be simplified (e.g., in the caseof the identical odd and even fields).Normally, the TV accepts the nonstan-dard video format without glitches.

As for generating the signal, themicrocontroller must be programmedto output both the video bits and thesync pulses. This task was traditionallysolved by software, but such a techniquedoesn’t produce enough elements in aTV line. Therefore, you must integratethe other tasks into the video-generatingalgorithm and calculate all of thedurations to avoid the probable arti-facts and the synchronization glitches.

VIDEO WITH THE LPC2138In order to obtain high-resolution

video, I had to generate a TV signal viathe hardware as much as possible. TheLPC2138 microcontroller has a PWM

There are many low-cost solutions(e.g., sound card-based) based on USBstand-alone devices that will turnyour PC into a digital storage oscillo-scope (DSO). All of them have a signif-icant disadvantage: when you use thePC for a measurement and other func-tions at the same time, you must clickyour mouse again and again to switchbetween applications. Of course, youmay use a dedicated notebook, but theother disadvantages will remain.

You could also use your old TV witha special add-on tool. Advanced micro-controllers have all the parts (e.g., ADCand RAM) for implementing such atool with a single chip. I’ll describe asimilar device in this article. My TV-based oscilloscope is built around a KeilMCB2130 evaluation board, which youcan easily turn into a DSO with few pas-sive components. Note that this projectrequires a code size of only 16 KB, soyou can use the evaluation version ofthe Keil CARM compiler.

Implementing the oscilloscope wasnot my main task. I usually try newmicrocontrollers in video applications,so I figured this would be a good way todemonstrate the capabilities of the NXP(founded by Philips) LPC2138 microcon-troller for generating a high-resolution(512 × 240 pixels) video picture.

SIMPLE VIDEO SIGNAL A standard video signal is a

sequence of sync pulses and theanalog waveform between them.When there are two gradations ofbrightness, the signal has threelevels (see Figure 1). There aretwo basic monochrome stan-

block and SPI communication mod-ule. The former can be used for gener-ating sync pulses. The latter can beused to generate the video stream!Want to know a secret? I already triedthis with Cypress SemiconductorPSoC chips. Unfortunately, the capa-bilities of the PSoC SPI module didnot allow me to obtain a horizontalresolution of more than 256 pixels.

The useful feature of the LPC2138’s(also called the synchronous serialport (SSP)) SPI1 block is the fact thatit can operate in a continuous SSImode. It has an eight-frame FIFObuffer and can send 16-bit frames. Thismeans that it can process a 128-bitblock without participation from thesoftware. Of course, to send more bits,the software must reload the FIFObuffer with additional data.

An external DAC is required tomix both the video and sync puls-es. It can be built using a resistormatrix like the one shown inFigure 2. With a 3.3-V supply anda 75-Ω load (a TV), this matrixproduces the sync and white lev-els of approximately 0.3 and 1 V.The output impedance of this sim-ple DAC is approximately 75 Ω

FEATURE ARTICLE by Ilya Mamontov

TV-Based OscilloscopeIlya turned an ordinary TV into a digital storage oscilloscope with a sampling rate of 160 ksps.In this article, he explains how to use an LPC2138 microcontroller to build a high-resolutionsystem of your own.

White level

Black level

TV LineHorizontalsync

Horizontal blankinginterval

Vertical blanking interval

Vertical sync

Figure 1—This is the structure of a monochrome video sig-nal. This project uses the simplified structure of the verticalsync pulses (without equalization pulses). The number ofTV lines per frame is even.

SSP

PWMLPC2138

Video bits

Sync pulses

R1 180

R2 390

R3 180RTV = 75 Ω

TV

Figure 2—SPP and PWM blocks generate video. The matrix of R1,R2, and R3 composes the external DAC.

2609014-Mamontov.qxp 10/5/2006 9:57 AM Page 52

Circuit Cellar, the Magazine for Computer Applications. Reprintedby permission. For subscription information, call (860) 875-2199, orwww.circuitcellar.com. Entire contents copyright ©2006 CircuitCellar Inc. All rights reserved.

Page 2: Tv Based Crp

www.circuitcellar.com CIRCUIT CELLAR® Issue 196 November 2006 53

for compatibility with75-Ω coaxial cable. Inreality, the level of blackis a bit shifted up afterthe last and before thefirst video bit inside theTV line because the SSPblock has a high outputimpedance in Idle mode.

VIDEO ALGORITHMThe algorithm for gen-

erating a single TV line issimple. Every 64 µs forPAL (or 63.536 µs forNTSC), the PWM blockproduces a horizontalsync pulse and simulta-neously generates aninterrupt that initiatesthe sequence of SSPcycles for a single TV line.

Because the SSP module has only128 bits of its own memory (eight 16-bitFIFO frames), it can’t contain all thedata for a 512-pixel line. To create acontinuous bitstream, a new chunk ofdata should be loaded into the SSP assoon as there’s room for it. For thispurpose, I use the “half empty” inter-rupt. This means that every time theFIFO becomes half empty, it requiresthe new portion of data. I assignedboth the PWM and SSP interrupt

requests to the FIQ category becausethe FIQ has a high priority and thefastest possible latency (see Figure 3).The disadvantage is that the FIQ han-dler should first identify which sourceis requesting the interrupt. Althoughit isn’t a recommended method, this isa unique way to create a glitch-freevideo when the other tasks use thevectored interrupt controller. (In thiscase, they must use only the IRQ cate-gory of interrupts!)

As you can see in Figure 3, when

the FIQ is identified ascoming from the PWMmodule, the SSP mod-ule’s FIFO is completelyfilled and its interrupt isenabled. This meansthat the SSP starts tooutput the content bitby bit and frame byframe. When the FIQ isclassified as comingfrom the SSP module,this means that the FIFOis half empty and thenext data chunk shouldbe loaded into the FIFOagain. When all of thechunks for a single TVline have been processed,the SSP interrupt is dis-abled for the next inter-

rupt from the PWM.The SSP module has a specific

prescaler so a required bit rate can bechosen from fixed values: b = 60MHz/2n (i.e., b = 30, 15, 10, 7.5 Mbps,etc., where 60 MHz is the nominalclock of LPC2138). These values corre-spond to the horizontal resolutions of1,536, 768, 512, 320 pixels, and so on.(The horizontal blanking interval istaken into account.) I achieved all ofthe resolutions in practice. Note thatthe maximum resolutions of 1,536 and

768 aren’t applicable forcolor TVs because the colorcathode ray tubes have dis-crete three-color dots on thesurface of the screen.

To obtain the required TVframe structure, a TV linecounter is provided in thesoftware. The counter isincremented every time thePWM interrupt occurs. Thecurrent value of this count-er is compared with a spe-cific number to trigger aspecific operation at a par-ticular instant. Specificnumbers define a verticalposition, the height of thepicture, and the duration ofthe vertical sync.

TRICKS USEDThe SSP module begins to

send the bitstream immedi-

VideoController_Start

Fill array of parameters(according selected

mode)

Setup PWM andSSP blocks

Assign FIQto PWM and SSP

Enable PWM interrupts

Return

Fast interrupt request (FIQ)

FIQ ISR

Determine the source of FIQ

Increment TVline counter

50 ≤ TV linecounter ≤ 290?

TV line counter= 309?

TV line counter 312?

Fill FIFO of SSP,enable SSPinterrupts

Swap content ofPWMMR4 and

PWMMR5

Restore PWMMR4and PWMMR5,

clear TV line counter

Fill SSP FIFO

TV lineis over?

Disable SSPinterrupts

Return

Y

Y

Y

N

PWM SSP

N

Y

>–

N

N

Figure 3—The specific values for comparisons correspond to the PAL mode. NTSC uses dif-ferent values.

Figure 4—The oscilloscope’s layout is fairly simple. The Keil MCB2130 evaluation board is shown on the left. I didn’t includeunused components on the board.

2609014-Mamontov.qxp 10/5/2006 9:57 AM Page 53

Page 3: Tv Based Crp

54 Issue 196 November 2006 CIRCUIT CELLAR® www.circuitcellar.com

ately after the first word is loadedinto the FIFO. Any random devia-tions (caused by multitasking) ofdelay between the PWM interruptrequest and the writing into the SSPdata register will cause the jitter ofhorizontal lines.

To prevent this problem, I use a pairof PWM interrupts (instead of a singleone) with the minimum possible dura-tion between them. After the firstrequest, all of the interrupts (exceptthe PWM) are disabled and the CPUis forced into Idle mode. Next, thesecond interrupt from the PWM mod-ule resumes the CPU with a pre-dictable delay.

VERTICAL SYNC & RESOLUTIONAccording to the RS-170A and CCIR

standards, the vertical sync pulse is asequence of inverted horizontal syncpulses. In my program, they areobtained by inverting the PWM out-put. At the end of the TV frame, thecontent of the PWM matchregisters (defining the ris-ing/failing edge positions) istemporarily swapped.

In my project, the num-ber of TV lines per frame iseven, so equalization pulsesaren’t required. It seems allof the TV models admitsuch mockery.

The RS-170A standardprovides 242 theoreticalvisible lines between thevertical sync pulses. TheCCIR standard does 287. Idecided to use the samevertical resolution (240 pix-els) for both standards,although a value of 256 orhigher is more preferablefor CCIR.

Almost all of the TVsoverextend the raster to usethe all screen area. As aresult, the upper and lowerparts of a generated picturecan be invisible in RS-170A because the only twoblank lines (2 = 242 – 240)are reserved here. Try toadjust the vertical size ifyour TV has this option, orselect PAL mode if you

have a multisystem TV.

VIDEO FOR OTHER APPSThe video-generating routines are

located in the VideoController.c fileposted on the Circuit Cellar FTP site.The critical fragments are written inassembler. The VideoController_Start(mode) function starts thevideo stream for a specified TV stan-dard. (The parameter mode should be1 for CCIR in Europe and 2 for RS-170A in the U.S.) When developingyour own system, simply add the fileto your project and call the function atthe initialization section of your appli-cation. Use the VideoArray globalvariable for access to bitmap data. Justremember that the bitmap array has ahalf-word organization and is in bigEndian format.

I also wrote a collection of helpfulgraphic routines that include general-purpose routines (e.g., drawing lines,text, wallpaper, and bitmaps) and spe-

cific functions (e.g., drawing a grid andprinting stylized digits). All of thefunctions have comment headers. Thefonts are also present there.

OSCILLOSCOPEAs I mentioned, the LPC2138 (IC1) is

the heart of the system (see Figure 4, p.53). I used the Keil MCB2130 evalua-tion board with a soldered LPC2138, a3.3-V regulator, and in-system pro-gramming (ISP). The investigated sig-nal comes in from the BNC connector(J1) to the internal ADC of IC1. TheDC component can be removed fromsignal via the S1 switch. In this case,the potentiometer (R6) adjusts the ver-tical position of the graph.

Other components are used for con-trol. R7 adjusts a horizontal position.R8 sets a trigger level (a voltage whenthe collection cycle should be started).S2 through S5 are control buttonsused for setting the horizontal scaleor calling the Store menu. J3 selects

the European or U.S. videostandard. (The position ofjumper is read at power-on.) Resistors R2, R3, andR4 compose the videoDAC. J2 is an output RCAconnector.

The optional analoginputs (Input1 throughInput5) can be used asvoltmeters. For this pur-pose, the firmware contin-uously measures theseinputs and displays theresults on the TV screen.In this version, the rangeof input voltages must befrom 0 to 3.3 V becausethe supply voltage (3.3 V)is used as a reference.

IMPLEMENTATIONThe firmware consists of

two parts, one for thevideo controller and onefor the oscilloscope. All ofthe oscilloscope routinesare in the Oscilloscope.cfile posted on the CircuitCellar FTP site. The mainthread is in main.c file (seeFigure 5).

The main loop, which

ADC0 ISR

Data collection thread

ReadADC result

Compare withtrigger level and set the

phase of synchronization

Return

Process ADC resultwith N previous samples. Select maximum values.

Store data in array,increment pointer

(or not if array is filled)

Return

main.c

Ask position of J3 andstart video controller

Draw all items on screen

Start ADC0, ADC1, anddata collection thread

Is the new portionof data ready?

Draw plot using the current data

Start collection of new portion of data

Read data from ADC1: voltages from Input1…Input5, from potentiometers R7, R8. Show values on screen.

GetKey

Test the flag “Menu”

Case of “Menu” = 1(“Store” menu)

Case of “Menu” = 0(normal operating)

Changedata index

Save collecteddata to flash

memory usingcurrent index

Draw plot usingthe data from flashmemory (preview)

Clear flagmenu = 0

Changehorizontal scale

Show newvalue of

horizontal scale

Set flag Menu =1and show

store menu

Down Up

Code from“GetKey”

Down Up Store Not key pressed Store

N

Y

Figure 5—The GetKey procedure doesn’t suspend the loop; it just returns the code.Code = 0 when the keys aren’t pressed.

2609014-Mamontov.qxp 10/5/2006 9:57 AM Page 54

Page 4: Tv Based Crp

www.circuitcellar.com CIRCUIT CELLAR® Issue 196 November 2006 55

starts after initialization, managesdata collection, visualization, and thedevice control. The special Menu flagassigns the current action for theDown and Up buttons. This flag istoggled with the Store button.

During normal operation (the Menuflag is 0), the Down and Up buttonsmake the timebase (horizontal scale)one step faster or slower. It’s achievedby processing several ADC samples(the “N” in Figure 5) to obtain a singledisplay sample, not by a variation ofthe ADC sample rate. This allows thesystem to implement Envelope modein which the highest value and thelowest value are calculated for eachgroup of N ADC samples and stored asthe data of a single display sample. Onthe plot, a vertical line between the twovalues is drawn so glitches or other high-frequency components of the signal willalways be visible. A line between twoadjacent samples is also drawn.

The data collection thread fills thespecial array of samples and signals tothe main loop that the data is ready.The main loop then waits in the TVframe to start the visualization ofdata. This is necessary to prevent anyproblems caused by interferencebetween the video controller’s refreshrate and the data collection rate. Fourvisualization algorithms are used forthis purpose.

The first algorithm is for high datacollection rates (i.e., horizontal scales).It waits until the data array is com-

pletely filled for one record view. The second and third algorithms are

for middle and low rates. They imme-diately visualize the current portion ofdata, which is collected between twoadjacent TV frames. The differencebetween them is in a Trigger mode. Atlow collection rates, it isn’t necessaryto wait for the trigger event becausethere is enough time to consider thegraph. As a result, the trigger systemis off here.

The fourth algorithm (transientrecorder) is intended for super-slowdata collection rates. It immediatelydraws the new sample and also usesRoll mode. This means that the eachnew sample causes a change in therecord view offset and makes thespace for the new sample. For measur-ing slowly changing signals, it looksnicer than Scan mode, where the dis-play area is filled on the left sidewhen the graph reaches the right side.

The data collection thread is writtenas an ADC interrupt service routine(ISR) that’s rich in functionality. Itserves all of the visualization algo-rithms and uses the different condi-tions to start a data collection cycle.One condition is a trigger event thatoccurs when the signal crosses athreshold (trigger level). In this version,I detect the crossings of the rising partsof a curve. Comparing the currentsample value and the trigger levelvalue does this. The trigger value iscalculated using the voltage from the

ADC result < TrigLevel?

Firstphase

Increment counter

Clearcounter

Counter ≥ max ?

Secondphase

Thirdphase

ADC result > TrigLevel?Y N

YN

Y

Counter

Max

1

2

3

4

0Time

First phase

Second phase

Third phase

ADC result

Time

The false trigger is killed

True triggerevent

N

TrigLevel

Figure 6—This is the debouncing algorithm in the trigger mechanism.

2609014-Mamontov.qxp 10/5/2006 9:57 AM Page 55

Page 5: Tv Based Crp

rotating control located on thefront panel.

The real signal has a noisecomponent that causes falsetriggers near the cross points.The falling edge can berecognized as rising. To pre-vent this, I used a debouncingalgorithm like the one com-monly used for mechanicalswitches (see Figure 6, p. 55).Of course, this isn’t the onlysolution. Many devices usevariable hysteresis algo-

rithms or HF filters. The voltages from rotating controls

also have a noise component, butanother algorithm should be applied tokill it: math filtering. I implemented asimple procedure, moving average:

GetVoltages_TrigLevel=(GetVoltages

_TrigLevel+val)>>1; //New (filtered)

value of trigger level

Another function of the data collec-tion thread is to create a delaybetween the trigger event and thestart of data collection. This is equiv-alent to the beam offset function inanalog oscilloscopes. The value forthe delay is obtained like the valuefor a trigger level from the rotatingcontrol at the front panel.

The Store button stops the data col-lection process, captures the graph,and calls the Store menu. You can usethe Down and Up buttons to move thespecial cursor along the row of numbers.The stored graphs are shown when youmove the cursor to the required posi-tion. Each number corresponds to astored graph that can be replaced by thecurrent waveform when the Store but-ton is repeatedly pressed. The Exit posi-tion causes the return to normal oper-ation without saving anything.

Ample flash memory (512 KB in theLPC2138) enables you to implement alife-prolonging algorithm for a storagesystem. Normally, a single flashmemory block has a limited numberof erasure cycles. The data for onegraph (1 KB) is considerably less thana block size (32 KB), so one flashmemory block can contain a set of 32(32 KB/1 KB) stored graphs. I use thistechnique when the flash memory

56 Issue 196 November 2006 CIRCUIT CELLAR® www.circuitcellar.com

Photo 1a—Ribbon cables connect the MCB2130 evaluation board to the front panel. b—The triangular cursor on the left sidecorresponds to the position of the Trigger Level knob on the front panel.

a) b)

2609014-Mamontov.qxp 10/5/2006 9:57 AM Page 56

Page 6: Tv Based Crp

www.circuitcellar.com CIRCUIT CELLAR® Issue 196 November 2006 57

After graduating from the MoscowAviation Institute (Russian Federation)in 1989, Ilya Mamontov worked asspacecraft electronic engineer for sixyears. He presently works in the atom-ic industry. His technical interestsinclude designing, modernizing, repair-ing, and servicing measurementinstruments. You may contact Ilya [email protected]. (Type “CircuitCellar” in the subject line.)

PROJECT FILESTo download the code and additionalfiles, go to ftp://ftp.circuitcellar.com/pub/Circuit_Cellar/2006/196.

RESOURCEST. Martin, “The Insider’s Guide to thePhilips ARM7-Based Microcontrollers,”www.hitex.co.uk/arm/lpc2000book/.

NXP (founded by Philips), “LPC2131/2132/2138 User Manual,” 2004.

SOURCESARM7TDMI-S MicroprocessorARM www.arm.com

MCB2130 Evaluation board andµVision3 IDEKeil www.keil.com

LPC2138 MicrocontrollerNXP (founded by Philips)www.nxp.com

block isn’t erased every time a newgraph is stored. The new data is writ-ten in the free space, and the flashmemory block is completely erasedonly when it’s filled by all 32 graphs.For visualization, a procedure seeksthe last stored data and draws a graph.

CONSTRUCTION & RESULTSI put all of the components on the

front panel and connected it to theMCB2130 evaluation board with a flatribbon cable. I modified the evaluationboard by soldering an additional con-nector on the P0 empty position, and Iused two metal corners instead of theplastic holders in order to have amechanical junction with the frontpanel (see Photo 1a).

I can observe audio signals (or othersignals) with a fine resolution (seePhoto 1b). Of course, some additionalfunctions (e.g., different trigger modes,a hardware input voltage divider(volt/div control), signal processing,and communication with PC) wouldbe useful. I’ll definitely consider addingthese functions when I’m working onnew applications (spectrum analyzers,EKG scopes, polygraphs, video games,and so on). As an example, you canpress the F button to call the menuwith reserved functions where the sim-plest screensaver is only implemented.

GENERATE VIDEOWith special test code, I measured

the CPU load of the LPC2138 micro-controller with the video-generatingtask. It was approximately 21%. Thismeans that the microcontroller canspend 79% of the time with anotherapplication.

I challenge you to build your ownsystem. Good luck! I

2609014-Mamontov.qxp 10/5/2006 9:57 AM Page 57