skip navigational linksPJRC
Shopping Cart Checkout Shipping Cost Download Website
Home MP3 Player 8051 Tools All Projects PJRC Store Site Map
You are here: MP3 Player Technical Docs Using The STA013

PJRC Store
Main Board, $150
LCD & Pushbuttons, $42
LCD/Backlight/PB, $77
IDE Cable, $9
Complete Parts List
MP3 Player
Main Page
Detailed Info
User Photo Gallery
Connecting The Board
Firmware Download
Side Projects
Technical Docs
Freq. Asked Questions
FAQ #2
News And Updates

How To Use The STA013 MP3 Decoder Chip

Sections Within This Page:

STA013 Chip Details

This page's mission is to help you understand how to use the STA013 MP3 decoder chip in order to design your own MP3 player. The player design described at the rest of these pages uses the STA013, but this page is intended to help you understand the STA013 itself, to use it in your own MP3 player design project.

STA013 Chip
Figure 1: STA013 MP3 Decoder Chip

You can purchase the STA013 and CS4334 directly from PJRC:

Using the STA013 for a "Normal" MP3 Player

The STA013 datasheet (and other info from ST) is terse and can be difficult to understand, partly because the STA013 is highly configurable. The goal here is to focus on one "normal" usage, only the essential requirements, and one useful configuration, so that this material is as easy to understand as possible. Here are the basic assumptions:
  • Multimedia Mode: in this mode, the STA013 automatically detects the bitrate of your MP3 data, and gives you a signal requesting more data. You feed data into the STA013 as rapidly as possible (well, up to 20 Mbit/sec), as long as it keeps asserting its data request signal. The MP3's sample rate (32, 44.1, 48 kHz) is also automatically detected, and the correct clock and data waveforms are created for the DAC. It is possible to ask the STA013 what it has detected while it's playing, though that's outside the scope of this simple-as-possible introduction (see the datasheet). There is also a broadcast mode that requires you to feed data at the correct bitrate. Broadcast mode is much more difficult to use and isn't very useful for most MP3 player designs. All the information here is focused only on multimedia mode.
  • OCLK Output: the STA013 can create all the signals needed to drive a Digital to Analog Converter (DAC). The STA013 can also accept an external DAC clock, but for most applications this is unnecessary and more difficult. All of the examples here assume the OCLK will be created by the STA013, which is a lot simpler than adding external circuitry.
  • CS4334 DAC, 14.7456 MHz Crystal: it is possible to configure the STA013 to work with many different DAC chips and crystals, but the examples here will focus only on a 14.7456 MHz crystal, which is inexpensive and a standard value (that also happens to be an exact multiple of standard baud rates). The examples also use the CS4334, which provides excellent quality line-level audio output, and also includes 4X interpolation and a continuous time analog output filter that eliminates the need for external opamps and complex output filtering. The CS4334 makes it simple and easy to obtain excellent quality line-level audio output without adding noise.
  • Essential Commands/Queries Only: there are many options and parameters available in the STA013, but only the most important ones are covered here, in the interest of keeping this page simple and easy to understand. A long and detailed list appears in the datasheet, but most MP3 player designs will only need to use the ones mentioned here, at least for their basic functioning.
The hope is that this limited focus will allow this page to explain how to use the STA013 much more clearly, for the common application in a media-based MP3 player. More advanced applications (real-time low-latency radio reception, audio data fed into another processor, etc) may need to use other features, but this page still may be a good place to start, particularly if the STA013 datasheet is a bit confusing.

Connecting The Chip

The first problem with using the STA013 for a prototype MP3 player is that it is a surface mount part. Unfortunately, it is not made in any through-hole packages. The two basic approaches are to buy or make an adaptor board, or to solder wires to each pin.

STA013 Chip and Aries Adaptor
Figure 2: STA013 Chip and Aries SOP to DIP Adaptor Board

Aries makes adaptors that are ideal for connecting the STA013 in a prototype, which DIP pins are easier to use. The adaptor shown in Figure 2 is available at DigiKey (P/N: A323-ND). This is actually a 32 pin adaptor, so 4 pins are unused with the 28 pin STA013. While an adaptor circuit board is easier, it is also possible to solder wires to all the pins. Here's a student project by Peter D'Antonio and Danial Riiff, with 28 wires soldered.

TODO: contact Peter and Daniel (anyone know their email address??) to ask for permission to display their soldered wires photo.

Update: Scott McNab wrote this nice page with instructions to make your own adaptors.

Power Supply Issues, 5 Volt to 3 Volt Interface

The STA013 is a 3 volt chip. The data sheet claims is can run between 2.7 to 3.6 volts (and separately mentions 2.4 volts for some unknown reason). It must not be used at 5 volts. Creating a 3 volt power supply is not difficult. Interfacing the 3 volt STA013 to 5 volt microcontrollers and DACs (CS4334) requires attention to make sure that they are properly received and to prevent damage to the 3 volt STA013. If your player uses a 3 volt microcontroller and 3 volt logic, then there is nothing to worry about and you should skip this section. If a 5 volt microcontroller is to be used, there are some simple ways to connect the chips, as long as the microcontroller inputs have TTL compatible input thresholds (nearly all microcontrollers do).

Connecting the STA013 output pins to TTL level input pins is simple, because the STA013 will output at least 85% of it's power supply for a logic high, and a maximum of 0.4 volts for a logic low. Even if the STA013 is run at 2.7 volts, it will still output 2.3 volts, which will satisfy the 2.0 input requirement of a TTL level input pin. The four CS4334 input signals are all TTL level.

3V Out to 5V TTL In, Direct Connect
Figure 3: Interfacing 3 Volt Output to 5 Volt TTL Input: DATA_REQ, SDO, SCKT, LRCKT, OCLK

The outputs from a 5 volt powered chip must not be directly connected to the STA013 input pins. The STA013 inputs are not 5 volt tolerant. Each pin has a pair of input protection diodes. These diodes may conduct a small current. The simplest and easiest way to interface a 5 volt output to the STA013 input pins is with a series resistor, that will limit the current when the 5 volt output is high. There is some input capacitance (3.5 pF) on the input pins, so adding a small capacitor in parallel with the resistor will allow the rapid edge to properly drive the input pin. The value of the resistor and capacitor are not critical, Figure 4 shows 4.7K and 47pF, which limits the steady-state current to less than 1/2 mA, and has been tested. The capacitor is not really necessary if the pin doesn't need to be driven rapidly, such as the RESET pin.

5V Out to 3V In, 4.7K Resistor and 47pF Capacitor
Figure 4: Interfacing 5 Volt Output to 3 Volt Input: SCL, SDI, SCKR, RESET

Connecting the SDA signal from a 5 volt microcontroller to the STA013 is a bit more complex, though a simple circuit can often be used. The SDA line is bidirectional, where either device can pull down, and a resistor provides the pull-up. Most microcontrollers have TTL thresholds, so a pullup to the 3 volt supply will easily satisfy the 2.0 volt input high requirement. If the microcontroller will never drive the line high (only pull low or tri-state), then no other parts are probably required. This may be the case if the microcontroller has a dedicated I²C pin. In most cases, the microcontroller can drive the line high, and an additional resistor should be added to prevent damage to the STA013. This current limiting resistor should be small, as it will form a resistor divider with the pullup when the microcontroller drives low. If the pin can be put in a tri-state mode, the firmware should be written to use the tri-state for a logic high, or at least tri-state the SDA signal when not transmitting data, to save power.

5V I²C SDA to 3V I²C SDA, 270 Ohm and 4.7K Pullup on 3V Side
Figure 5: Interfacing 5V to 3V Bidirectional I²C SDA Signal

Philips suggest a somewhat more complex 5V to 3V connection involving a pair of mosfet transistors. Their solution is a much better approach for a general purpose bus. The pair of resistors shown here should only be used with a single microcontroller and the STA013. If you have a N-channel mosfet transistor, the Philips circuit would be better. This is only necessary on the SDA line, since the microcontroller will always generate the clock, so the circuit in Figure 4 will work well for the SCL signal.

Where to Connect The Pins

The good news is that thirteen pins connect to ground or the +3 volt power supply, five connect to simple resistors, capacitors, and the crystal, leaving you only ten pins to worry about. These 10 signals can be grouped into four categories:
  • I²C Control: 2 pins, SDA and SCL will connect to whatever will control the MP3 decoder. These pins use the I²C protocol to send commands and query parameters, to initialize the chip and to control it while it's decoding data.
  • MP3 Input: 3 pins, SDI (data), SCKR (clock), and DATA_REQ (ready) will connect to the MP3 data source. When the DATA_REQ pins indicates that the chip is ready, the source inputs the MP3 bits, as rapidly as it can, until the STA013's buffer is nearly full and DATA_REQ says the chip can't accept any more input. Technically, a fourth pin, BIT_EN is in this group, but it usually isn't used.
  • DAC Output: 4 pins, SDO, SCKT, LRCKT, and OCLK are the decoded audio data. These signals can be directly connected to a CS4334 DAC chip.
  • Reset: RESET must be held low at startup, or at least briefly before using the chip.
The 5 pins requiring resistors, capacitors and the crystal are simple. These are FILT, XTO, XTI, PVDD and PVSS. Just connect them to resistors, capacitors and the crystal, as shown in Figure 6.

STA013/CS4334 Schematic
Figure 6: Typical Connection of STA013 and CS4334

The resistors connected to PVDD and PVSS are 4.7 Ohm (not 4.7k). Any value near a few ohms is ok, if 4.7 ohms is not available. The capacitors connected to the crystal may need to be changed to match the resonance of the crystal. Values are usually in the range of 15 to 47 pF, and many crystals are not very sensitive to the exact capacitor values used. The inductor shown on the CS4334 power supply is intended to block noise from digital circuitry that's also connected to that line. The value of the inductor is not critical, so 100 µH would probably work well. In no inductor is available, and alternative is to create a separate ("clean") supply for the CS4334 with a LM7805 or similar linear-mode voltage regulator.

From Deckx Kevin:
Because of the way your circuit is drawn it's very easy to switch up pin 17 and 18 and cause a 9-10 ohm resistance path from Vcc to the ground. My sta013 only survived because of current limiting around 100mA.

Here's a table listing how each pin should be connected, which can be used as a "check off" list while wiring the chip on a breadboard.

PinPin NameGroupIn/OutHow To Connect
1VDD_1-Power+3 Volts
2VSS_1-PowerGround
3SDAI²C ControlIn/OutTo microcontroller, I²C Data
4SCLI²C ControlInTo microcontroller, I²C Clock
5SDIMP3 InputInConnect to Data Source (Data)
6SCKRMP3 InputInConnect to Data Source (Clock)
7BIT_EN-In+3 Volts
8SCR_INT-In+3 Volts
9SDODAC OutputOutTo CS4334 SDATA, Pin 1
10SCKTDAC OutputOutTo CS4334 DEM/SCLK, Pin 2
11LRCKTDAC OutputOutTo CS4334 LRCK, Pin 3
12OCLKDAC OutputOutTo CS4334 MCLK, Pin 4
13VSS_2-PowerGround
14VDD_2-Power+3 Volts
15VSS_3-PowerGround
16VDD_3-Power+3 Volts
17PVDDMiscPower+3 Volts through RC filter
18PVSSMiscPowerGround through RC filter
19FILTMiscOutConnect Resistor and two Capacitors
20XTOMiscOutConnect Crystal Circuit
21XTIMiscInConnect Crystal Circuit
22VSS_4-PowerGround
23VDD_4-Power+3 Volts
24TESTEN-In+3 Volts
25SCANEN-InGround
26RESETResetInLow = Reset, High = Able To Run
27VSS_5-PowerGround
28DATA_REQMP3 InputOutConnect to Data Source (Ready)

Communication And Configuration Via I²C

The STA013 requires initialization by I²C communication. This step can not be avoided. Part of the required initialization is to send a group of 2007 writes provided by ST in the file p02_0609.bin. A frequently asked question is "do I really need to use I²C and the file from ST?". The answer is Yes!, the STA013 will not work without being properly initialized. The config file from ST is part of this process. There does not appear to be a way to make the chip work properly without it. Fortunately, the initialization step isn't difficult, and you will find working example code at the end of this page.

First, a little background about I²C. I²C is a 2-wire protocol, created by Philips. One line acts as a clock (SCL) and the other data (SDA). The protocol defines the ability to have multiple masters initiate communication, but here we'll only worry about the simple and common case where the microcontroller is the only device that controls the bus, and all the other chips (like the STA013) respond to queries initiated by the microcontroller. There are many sites with detailed info about this protocol.

TODO: add more useful I²C links If you have a link or two, please email them to me. I particularly want to add links to app notes and free code that implements I²C.

Simple I²C, Four Basic Operations

For simple applications (like using the STA013), there are four fundamental operations. Only these four operations are needed to build routines that access the STA013 chip:
  • Start Condition: This is a high-to-low transition of the SDA line, while SCL is high. Normally SDA only changes when SCL is low. When SDA changes while SCL is high, it means either the start or stop of a communication, instead of data transfer.
  • Send A Byte, Get ACK Bit: Eight bits are sent by the microcontroller, each write to SDA occurs while SCL is low. A ninth clock is given and the microcontroller receives an ACK bit from the STA013. If the STA013 received the byte, it will send a zero in this bit.
  • Receive A Byte, Send ACK Bit: The microcontroller gives eight clocks on SCL, and after each low-to-high clock transition, a bit is read from the STA013. During a ninth clock, the microcontroller pulls SDA low to acknowledge that it received the byte.
  • Stop Condition: This is a low-to-high transition of the SDA line, while SCL is high. After the stop condition, both lines are left high, which is the idle state of the I²C bus.
Source code to implement these four function is provided in the example at the end of this page. The example code uses two 8051 port pins. Some 8051s and many other microcontrollers have built-in hardware to implement I²C communication, which can make the process faster than manipulating port pins.

Reading From The STA013, "sta013_read" Function

Using these four basic I²C operations, a function to read from the STA013 can be built as follows:
  1. Start Condition
  2. Send A Byte The value is 0x86 (134). The seven most significant bits instruct the STA013 to listen (because there may be other chips connected to SDA and SCL). The LSB is clear, telling the STA013 that will will be writing an address.
  3. Send A Byte The value is the address where we need to read data. The main program will pass the address to our sta013_read function.
  4. Stop Condition
  5. Start Condition
  6. Send A Byte The value is 0x87 (135). Again, the upper bits select the STA013, and the LSB sets up the next access to read.
  7. Receive A Byte Read the byte from the STA013. This will be returned to the main program.
  8. Stop Condition
The code that implements these steps should check the ACK bit returned by each byte transmit, and return an error to the main program if there is no ACK bit received.

Writing To The STA013, "sta013_write" Function

Writing to the STA013 is even easier. Here are the steps.
  1. Start Condition
  2. Send A Byte The value is 0x86 (134). The seven most significant bits instruct the STA013 to listen. The LSB is clear, telling the STA013 that will will be writing.
  3. Send A Byte The value is the address within the STA013 where we write the data. The main program will pass the address to our sta013_write function.
  4. Send A Byte The value is the data passed from the main program to write into the STA013.
  5. Stop Condition
The code that implements these steps should check the ACK bit returned by each byte transmit, and return an error to the main program if there is no ACK bit received.

There are other faster and somewhat more complex ways to communicate with the STA013, such as writing to multiple consecutive locations. These optimizations are usually of little benefit with the STA013.

Actually Using These Functions To Configure The STA013

Now that you've read (or perhaps skipped over) the above section about basic I²C routines, from here forward "writing" will mean writing a byte to a particular address using the steps of "sta013_write" and "reading" will mean reading a byte from a particular address, using the steps of "sta013_read".

The first step should be to check that the STA013 is actually present. Just read from address 0x01. If the read routine returns with an error, then no device sent an ACK bit and there is no chip installed. If there is an ACK, the data returned should always be 0xAC. Any other value means that the STA013 (or the code implementing the communication) isn't working properly. It is also possible to read the STA013 revision code at address 0, but ST gives not useful info about what this means, so it's probably not worth the trouble. The important step is to verify the ACK and 0xAC data at address 1, which means that the STA013 is present and communicating properly.

If you don't get the ACK, check the connections to the STA013, and verify that the STA013 got a good reset pulse and has its crystal oscillating.

The next step is to transmit the "p02_0609.bin" config file provided by ST. This file consists of 2007 address and data pairs. Sending the file is simple, just write a loop that passes each pair to the "sta013_write" function. Each ACK should be checked and the process aborted if any write doesn't receive any of its ACKs.

The exact purpose of the p02_0609.bin file is a bit of a mystery. ST calls it a "config" file on their website. In the app note, they describe it as a "Patch File". Most of the addresses used in the file are registers that are not defined in the data sheet. Probably only a few engineers at ST, who've certainly signed NDAs, really know what this file does. If you, dear reader, have any solid information (not guesswork or speculation), please contact me so I can update this section. Also, if you manage to get a STA013 chip running properly without using p02_0609.bin, please send me an email with details and the date code from your chip, so that I can update this page. Update: a couple people have reported being able to play low-bitrate files without loading the p02_0609 data.

Update, March 15, 2001: burried deep within the p02_0609.bin is a write to address 16. Address 16 is the soft reboot regsiter. A brief delay is probably required after writing to this register. I've found that the vast majority of STA013 chips work without this delay, but some don't initialize properly and their data request pin stays stuck either high or low. The example code below does not have this delay, and it worked properly with the chip on the protoboard shown in the photo. Hundreds of these chips have worked without this delay on the MP3 player boards, but a few have not been so fortunate. Many people have reported success designing with the STA013 based on this page. This problem appears to be rare, but it does happen. It may be more prone to happen with a really fast mircocontroller, like the Atmel AVR or some 16 bit chips. Code with this delay will appear in the MP3 player's 0.6.2 firmware release, inside the "drivers.asm" file. If you're having a similar problem before the 0.6.2 release, contact me for the code. It's just a simple 0.6 ms delay after sta013_write if the address was 16. Also in 0.6.2 is some code which sends a tiny 1/2 second MP3 of silence to the STA013 and measures how long it takes for the STA013 to consume it. This appears to be the only effective way to detect if a STA013 has been misconfigured, as it will properly respond to I²C queries while it's in this funny state.

Update, April 4, 2010: Raghavendra Talekar send this message with insight about the likely origin and purpose of the config file.

The p02_0609.bin file is actually a simple ASCII text file. Why ST used a ".bin" extension is also a mystery. Each line contains two numbers, the first is the address and the second is the data to write to the chip. Here's the first several lines of the file:

58 1                             
42 4
40 0
41 0
32 0
33 0
34 0

The example code near the end of this page contains a perl script to convert this data format into intel-hex, which can be programmed into a EEPROM or downloaded to a monitor program. The perl script also adds a length count and simple checksum, which can be used to check the data before sending to the the chip.

Once the config file is sent, the board specific settings must be sent. Here are the settings used in this example, for 14.7456 MHz crystal and the CS4334 DAC:

Register Addr Data Comment
PCMDIVIDER 84 1 256X oversample, 32 bit words (allows 24 bit output)
PCMCONF 85 33 I2S format for CS4334
PLLCTL 7 0 Default is zero, not in Table 10, but is zero in ConfigPLL v1.0
PLLCTL 6 12 14.7456 MHz Clock, 256 Oversample, Table 10 in Datasheet
??? ("reserved") 11 3 14.7456 MHz Clock, 256 Oversample, Table 10 in Datasheet
MFSDF_441 80 16 14.7456 MHz Clock, 256 Oversample, Table 10 in Datasheet
PLLFRAC_441_L 81 0 14.7456 MHz Clock, 256 Oversample, Table 10 in Datasheet
PLLFRAC_441_H 82 4 14.7456 MHz Clock, 256 Oversample, Table 10 in Datasheet
MFSDF 97 15 14.7456 MHz Clock, 256 Oversample, Table 10 in Datasheet
PLLFRAC_L 100 85 14.7456 MHz Clock, 256 Oversample, Table 10 in Datasheet
PLLFRAC_H 101 85 14.7456 MHz Clock, 256 Oversample, Table 10 in Datasheet
PLLCTL 5 161 14.7456 MHz Clock, 256 Oversample, Table 10 in Datasheet
DATA_REQ_ENABLE 24 4 Enable data request pin

It is possible to use the STA013 with other crystals. For example, to use a 10 MHz crystal, use the values in Table 5 from datasheet, and to use a 14.31818 MHz crystal, use Table 7. ST also provides a ConfigPLL v1.0 utility to compute these parameters for other crystals. It's interesting that register 7 is shown in ConfigPLL, but not in the tables of the datasheet. ConfigPLL seems to always set it to zero. Likewise, the tables list register 5, but ConfigPLL does not. All the tables show register 5 at 161, so perhaps that's the right setting for any crystal. One thing is certain, the settings shown here (same as in the example code) have been tested and are known to work with the 14.7456 MHz crystal and CS4334 DAC, so using them with 14.7456 MHz and a CS4334 is a very safe bet!

The easiest way to send these setting it to just add them on to the end of the p02_0609.bin file, and let the loop that sends that file do the work. The last several lines of that file are actually writes to some of these registers, so they can be removed and replaced with the configuration you need. The copy of p02_0609.bin in the download section has these settings added, so you can use it with a CS4334 and 14.7456 MHz crystal without any changes.

After you've checked the 0xAC, and sent the config file (with config data appended), then all that's left it telling the chip to start running. This could perhaps be added to the config file as well, though the example shown below does it separately. Just write a 1 to address 114 to tell the STA013 to start running, and then a 1 to address 19 to tell it to start playing. The DATA_REQ pin should be asserted, and when you start feeding valid MP3 data in, the chip will detect the MP3 sample rate, create the correct clocks for the DAC, and start pushing data into it.

Sending MP3 Data

Sending MP3 data to the STA013 is simple. The basic idea is to give the STA013 data when it requests more. You do not need to be concerned about the MP3 bitrate, the STA013 chip will determine what the bitrate is, consume the data at the correct speed, and give you the request signal when it needs more. As you transfer the bits, it will end the request when its buffer is nearly full. Variable bit rate files are automatically handled. It also automatically detects the required sample rate (44.1 kHz, 48 kHz, etc) from the MP3 data and automatically adjusts the DAC clock. All you have to do is give it more data when requested. The speed that you actually input the bits doesn't matter, usually you'd send them as fast as possible, as long as it's under 20 Mbit/sec.

The STA013 is designed so that your project never needs to "know" anything about the MP3 file. When the chip requests more data, you need to respond in a timely manner, and feed the data in as rapidly as possible until the STA013 de-asserts its request signal. The chip will make requests more frequently at faster bitrates. The combination of your response time and data rate, if they are slow, may limit the maximum bitrate that can be played. The good news is that most VBR encodings only use fast bitrates (256 and 320 kbps) for brief times, so in many cases the STA013's input buffering will allow a design that couldn't supply 256 kbps contant bit rate to play variable bit rate files which contain brief bursts at these high speeds.

The STA013 will ignore non-MP3 data (producing no sound), so it's safe to feed entire MP3 files, which may contain ID3 tags, into the STA013 without concern for which part of the file is MP3 bitstream and what portion is the ID3 tag. The chip will just keep requesting more data until it sees valid MP3 information. It's also safe to feed damaged MP3 streams into the STA013, for example truncated files due to partial download. Most damaged MP3 data is completely ignored. Some damaged files will produce a brief chirp sound (usually depending on what follows immediately after the damaged part), but the STA013 will rapidly sync back to good data that's sent after a corrupted part.

One final thing to keep in mind is that the STA013 doesn't "know" about files. You may decide to issues I²C commands between each file, but that is not necessary. A simple player may just send the contents of file after file to the chip, and the STA013 will automatically adjust its settings when it sees data that specifies a different bitrate, sample frequency, mono or stereo mode, etc.

This section was contributed by Ed Schlunder (zilym@NOSPAM.yahoo.com). Ed's examples are written in C. I'll add a comment or two in this smaller green text.

There are three signal lines used for sending the MP3 data to the STA013 decoder: SDI (DATA), SCKR (CLOCK), and DATA_REQ. The STA013 asserts the DATA_REQ line when more MP3 data is needed from the host controller. The host controller then feeds MP3 data, most significant bit first, on the SDI line. Each bit placed on SDI is clocked, by the controller, into the STA013 with the SCKR signal line. Some example code for sending MP3 data follows:


char          mp3data[]; /* imagine that this buffer is already full of data */
unsigned long mp3ptr = 0;

for(;;) {
  while(DATA_REQ) {
     /* STA013 is requesting more data, send a byte */
     for(short j = 7; j >= 0; j--) {
       SCKR = 0;
       SDI = (mp3data[mp3ptr] >> j) & 1;
       SCKR = 1;
     }
     mp3ptr++;
  }

  /* do anything you want here... but don't take too long at it :-) */
}

The example code near the end of this page has a very similar function named "xmit_mp3_clip" implemented in 8051 assembly. It contains 8 copies instead of a loop, which nearly doubles the speed. Also keep in mind that if something goes wrong with the STA013 and it doesn't assert DATA_REQ, this will turn into an infinite loop. For a "real" player design, some sort of timeout should be added.

The above code assumes that whenever the STA013 asserts DATA_REQ, it can accept at least eight bits of data. The STA013 datasheet never explicitly says this is the case (AFAIK), however, in the practice it does seem to hold true. Which is very good, because this lets us use the 8051 serial mode 0 to send data more efficiently...

In 8051 serial mode 0, the RxD pin shifts data out of the serial buffer (special function register SBUF) as the TxD pin provides clocking for each bit transmitted. If you hooked the STA013 SDI pin to the 8051 RxD pin and STA013 SCKR to 8051 TxD, you could in theory now use the 8051's UART hardware to do the bit shifting that we had to do manually in the code example before.

However, there's a catch: the 8051 UART shifts out data least significant bit first, which is the opposite of what the STA013 is expecting. Therefore, before writing a byte of MP3 data to the SBUF register, we must reverse the bits so that the STA013 receives the bits in the order it expects:


/* swaps bits MSB<->LSB to put bits in correct order for STA013 SDI */
unsigned char swapbits(unsigned char i) {
  return i >> 7
       | (i & 0x40) >> 5
       | (i & 0x20) >> 3
       | (i & 0x10) >> 1
       | (i & 0x08) << 1
       | (i & 0x04) << 3
       | (i & 0x02) << 5
       | i << 7;
}

char          mp3data[]; /* imagine that this buffer is already full of data */
unsigned long mp3ptr = 0;

SCON = 0; /* go into serial mode 0 */

for(;;) {
  while(DATA_REQ && TI) {
    /* STA013 is requesting more data and our serial port isn't busy */

    TI = 0; /* clear transmit flag -- serial port busy */
    SBUF = swapbits(mp3data[mp3ptr++]);
  }

  /* do anything you want here, but don't take too long... ;-) */
}
Martin Frost also suggested this code to swap the bits
	unsigned char swapbits (unsigned char i)
	{
	    i = ((i & 0xAA) >> 1) | ((i & 0x55) << 1);  /* 67452301 */         
	    i = ((i & 0xCC) >> 2) | ((i & 0x33) << 2);  /* 45670123 */
	    return (i >> 4) | (i << 4);                 /* 01234567 */
	}
If you have enough memory, it would be fastest to build a 256 byte lookup table ahead of time that will let you swap bits without running the swapbits() function on each byte transmitted.

The lookup table should be implemented in code-space (MOVC). The 8051 serial mode 0 is so fast that the checks on the TI bit are unnecessary... you can't get the data and do a fast table lookup bit swap before all of the previous bits are sent. My old player design used this approach, and you can look at it's code, including the "flip_bits" lookup table, to save you the effort of regenerating this table. Look at the code in "idle_loop" for a timing analysis, best case is 13 cycles, and 8051 mode 0 takes 9 cycles to transmit.

A microcontroller with a dedicated SPI port would be even better because the SPI interface will send data in the proper bit order by default. So, use SPI instead of you have the option.

End of Ed's section. Thanks Ed, that really helped.

The fastest and most efficient method, but also by far the most difficult to design, is to build dedicated hardware to send large blocks of data to the STA013 automatically, without any CPU overhead. The new MP3 player does this using a Xilinx FPGA chip. The basic idea is that the CPU writes the address and length of a block of MP3 data that resides in memory, and then writes to a "go" bit. The hardware automatically detects when the CPU doesn't need to access the memory, and reads the MP3 data into a shift register, which sends the bits to the STA013 as it requests them. The bits are shifted at about 7 Mbit/sec (very fast, but the STA013 can handle 20 Mbit/sec). Each time the shift register is empty, the hardware makes another read from the next memory location, as soon as there is an opportunity to access the memory when the CPU doesn't need it. When all of that block has been sent, the hardware gives the CPU an interrupt, so that the CPU can give it the next block's addr/len to transmit. For some more details about how this is done, take a look at the memory map page for the new player design. This design allows even a slow (low power) CPU to easily play the fastest MP3 streams (320 kbps), but it is a very difficult approach.

While it is possible to design a very high performance data transfer, the example code below uses the simplest possible method, directly manipulating the port pins. The intention of the example code is to be simple and easy to understand.

STA013's Input Buffer Capacity

A common question about the STA013 chip is "how big is the input buffer?". ST's datasheet isn't much help, but with a really fast transfer to the chip and a slow MP3 bitrate, we can try to measure it. Figure 7 shows the fast SCKR signal generated by the dedicated hardware used in the MP3 player board shown at the rest of these pages. A 64 kbps/sec MP3 file was being played during this test, to limit the number of bits played while the DATA_REQ signal was asserted and each burst of data was loaded.

Oscilloscope Screen Photo
5 ms/div, 1 volt/div
(two ~206 byte transfers)
Oscilloscope Screen Photo
50 µs/div, 1 volt/div
(one ~206 byte transfer)
Oscilloscope Screen Photo
1 µs/div, 1 volt/div
(three 16 bit transfers)
Figure 7: Fast SCKR Signal, Effective Transfer Speed 5 Mbit/sec

The left photo shows a burst of transfer every 26 ms, which suggest that an average of 1664 bits are transfered into the buffer each time, to maintain 64 kbps throughput. Our sony mavica camera uses approx 15 ms shutter speed in this lighting, which made the left photo very difficult... it's either a way-too-bright spot a few divisions long, or a weak image if the shutter happens to open between traces (as in the one I finally ended up using). That's why you see a weak trace, when a slow sweep is usually a bright and annoyingly flashing image.

The center photo shows that the bursts are about 345 µs long. The right photo shows the effective bit rate. Bursts of 16 bits are sent at 7.37 MHz, with a delay between each 16 bits while the control state machine arbitrates for access and then reads the DRAM. 32 bits are sent in approx 6.4 µs, for a bit rate of 5 Mbit/sec, which suggests about 1725 bits are loaded into the STA013's input buffer during the 345 µs burst. This second method probably over-estimates the buffer size slightly, since the control state state machine must sometimes wait during the bus arbitration (the slight "ghost" image in the right photo), causing the effective bit rate to be somewhat less than 5 Mbit/sec. Still, 1664 and 1725 bits is a 3.7% error (if you assume 1664 is closer to the truth)... not bad for counting divisions on the 'scope screen!

These waveforms only measure the input buffer between the point where the STA013 asserts and releases DATA_REQ, which is says that the buffer is at least 206 bytes.

Simple Example System

TODO: draw schematic that exactly matches breadboard wiring... very similar to figure 6, add LM317 and 3/5 volt interface parts (figures 3,4,5), re-label I/O with 8051 port pin names. For now, check the ASM source comments for which port pins connect to what signals.

TODO: write some descriptive text... the pictures show what it looks like and the screen dumps shown how to run with PM2 monitor. See comments in the code for making a stand-alone version or using with a different development system.

Simple Example System

Example Breadboard Wiring

Example Breadboard Wiring

Here's a typical session using the example code. The code is written to run with the PM2 monitor program. It can be easily modified to run under a different development system, or stand-alone. See the comments in the source code for details. The example uses the 8051 development board.

Here, the board is booted and the memory and flash are cleared. It's not really necessary to clear the memory, but if anything is residing in the flash memory (other than MP3 data), it must be erased.


               Welcome to PAULMON2 v2.1, by Paul Stoffregen

  See PAULMON2.DOC, PAULMON2.EQU and PAULMON2.HDR for more information.         


Program Name                     Location      Type
  List                             1000      External command
  Single-Step                      1400      External command
  Memory Editor (VT100)            1800      External command
  STA013 Example                   2000      Program

PAULMON2 Loc:2000 > Clear memory

First Location: 2000
Last Location:  3FFF
Are you sure?

PAULMON2 Loc:2000 > Erase flash rom

Erase flash rom, Are you sure?

Flash rom erased

Three files must be downloaded. The "sta013.hex" was sent first in this example (794 bytes of data). Then the "p02_0609.hex" file was transmitted next, and finally one of the MP3 test clips was sent. In this example, it was "faith_hill_clip.mp3", which is several seconds from a well known song.

The example code uses the following memory:

  • 0x2000 to 0x232D: STA013.HEX, the simple code example
  • 0x3000 to 0x3FBA: P02_0609.BIN, sta013 config and settings
  • 0x8000 to 0xFFFF: MP3 Data to play
This memory arrangement fits the memory map of the 8051 development board. For other 8051 boards, the intel-hex files may need to be recreated at different memory ranges, depending on the board's memory map. With the PJRC 8051 development board, the example code will run without and modifications.

Any MP3 data could be downloaded, but the four test clips in the download section are encoded at very low bit rates, so that a 32 kbyte clip can play for several seconds. At the usual 128 kbit/sec MP3 bitrate, 32 kbytes will play for only 2 seconds.

PAULMON2 Loc:2000 > ^...................................................
Download completed

Summary:
 51  lines received
 794  bytes received
 794  bytes written
No errors detected


PAULMON2 Loc:2000 > ^...........................................................
....................................................................
Download completed

Summary:
 127  lines received
 4026  bytes received
 4026  bytes written
No errors detected


PAULMON2 Loc:2000 > ^...........................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
.....
Download completed

Summary:
 1024  lines received
 32735  bytes received
 32735  bytes written
No errors detected

Once all three files are loaded into memory, just run the program. The example code does some checks to make sure that a valid STA013 config file is present. It does not check the validity of the MP3 data... whatever is in the 0x8000 to 0xFFFF memory range is sent to the STA013 chip.

PAULMON2 Loc:2000 > Run program

  A - STA013 Example
run which program(A-A), or ESC to quit: A

STA013 MP3 Decoder Test Program
Reseting STA013
Reading IDENT register: AC  Ok
Checking p02_0609 (config data) at 0x3000  Ok                                   
Downloading Config Data to STA013 chip:  Ok
Sending RUN Command:   Ok
Sending PLAY Command:   Ok
Playing MP3 Clip From Memory:   Ok

Press any key to restart: 

Downloadable Free Code And Supporting Files

The four short MP3 clips are encoded at lower-than-usual bitrates (with some attempt to still have reasonable sound) so that the example STA013 test program can play a recognizable line of a song from the small 32 kbyte test memory.

Testing and troubleshooting custom-built circuitry can be difficult and frustrating. The idea behind these MP3 clips is to provide a ready-to-use test for the STA013 and this example code, already converted to intel-hex format for loading into the flash. If data is sent to the STA013 that's been incorrectly translated, it will detect that it's not a valid MP3 stream and do nothing. Having known-to-work MP3 test clips in the correct format eliminates (or at least reduces the likelyhood of) one more potential source of trouble. All four of these intel-hex format clips were tested on the example hardware shown.

These four MP3 clips are short sections of well-known copyrighted works. I believe that providing these clips is a fair use of the copyrighted material, because the purpose and character of the use is educational, the amount and substantiality of the portion used in relation to the copyrighted work as a whole is a 5 to 8 second clip of a 3-5 minute song, and the effect of the use upon the potential market for or the value of the copyrighted work is effectively zero.

AVR, PIC, HC11 & Other Microcontrollers

I receive a good number of emails from people using these other microcontroller chips (usually Atmel AVR and Microchip PIC), where they have problems using the STA013. The most common description involves the I2C able to read 0xAC, but the chip doesn't begin operating and assering the demand signal after they download the file and give it the run command. If you are in this situation, and you're read this page, the ST datasheets, and looked your code over and over, and you are completely stuck, there are two basic approaches you can take:
  1. Build or buy an 8051-based board that will run the known-to-work example code from this web page. You can buy a suitable 8051-based board from PJRC, which lets you easily run the example code from this page to get the chip to work. Complete design information for these boards are available at this site, so building it yourself is also an option.
  2. Try to find someone's known-to-work code implemented with your microcontroller of choice, and compare their approach to what you have done.
Sites with source code for other processors:
  • Javier Saiz's Reproductor Mp3PuBliC Rev B con STA013 y CS4334 - Uses a PIC16F877. Site is in Spanish, but the "Estado de funcionamiento del Firmware" has complete PIC source code!
  • Steve Butler's Spastic MP3 Player - Uses Rabbit 2000 (Z-80) Microcontroller. Steve provides complete source code in C. His player uses a 74HC165 shift register and other logic to transfer the bitstream quickly.
  • Markus Schorer's mp3redux card. A PC/104 (ISA bus) card with the STA013, LCD and Radio interfaces. ISA bus interface uses a programmable logic chip (he provides the code for download). Linux-based drivers and user space utilities including mpg123 interface emulation (so linux-based apps can use the STA013).
  • Nasif's ZipAmp Project using the Atmel AVR AT90S8515. Nasif is now providing complete C source code (CodeVision compiler) including STA013 initialization and FAT filesystem reading.
  • Pascal Stang's Procyon AVRlib. A library of C code (intended for the AVR) which includes a driver for the STA013 chip, and many other useful functions.

 

 

 

TODO: add a wrap-up section, with some suggestions about what to do next, links to new and old player.


MP3 Player, Using The STA013 Chip, Paul Stoffregen.
http://www.pjrc.com/tech/mp3/sta013.html
Last updated: February 23, 2005
Questions, Comments?? <paul@pjrc.com>