1) Experimental platform: Punctual Atomic Pioneer FPGA Development Board
2) Excerpted from "Pioneer FPGA Development Guide" Follow the official WeChat account for more information: Punctual Atom
3) Full set of experimental source code + manual + video download address: http: //www.openedv.com/thread-13912-1-1.html
Chapter 39 SD card reading and writing test experiment
The SD memory card is a new generation of memory device based on semiconductor flash memory. It has the advantages of small size, fast transmission speed,
support for hot swapping, etc., and has been widely used in the field of portable devices, such as digital cameras, multimedia players, notebook computers, etc. In this chapter, we will use the FPGA development board to learn how to read and write the SD card and conduct the SD card read and write test
.
This chapter includes the following parts:
39.1 SD card introduction
39.2 Experimental tasks
39.3 Hardware design
39.4 Program design
39.5 Download verification
SD card introduction
The full English name of SD card is Secure Digital Card, which is secure digital. Card (also called secure digital card) is developed on the basis of MMC card
(Multimedia Card, multimedia card). It mainly adds two features: higher security and
faster reading and writing speed. The length and width of SD card and MMC card are both 32mm x 24mm. The difference is that the thickness of SD card is 2.1mm,
and the thickness of MMC card is 1.4mm. SD card is slightly thicker than MMC card to accommodate larger capacity. At the same time, the SD card has more
pins than the MMC card, and has an extra write-protect switch on the side. SD cards maintain upward compatibility with MMC cards. That is to say, MMC cards
can be accessed by new SD devices. The compatibility depends on the application software, but SD cards cannot be accessed by MMC devices. SD cards and
MMC cards can be distinguished by the markings on the cards. As shown in the figure below, the one marked "MultiMediaCard" with the letters
on the left side of the picture is an MMC card, and the one marked with the letters "SD" on the right side of the picture is an SD card.
Figure 39.1.1 MMC appearance (left) and SD card appearance (right)
The SD card on the right side of the picture above is actually an SDHC card. SD cards are divided into 3 levels in terms of storage capacity, which are: SD card,
SDHC card (Secure Digital High Capacity, high-capacity secure digital card) and SDXC card (SD eXtended Capacity,
expanded capacity secure memory card). The SD card is developed on the basis of the MMC card and uses the FAT12/FAT16 file system. The SD
card adopts the SD1.0 protocol specification, which stipulates that the maximum storage capacity of the SD card is 2GB; the SDHC card is a large-capacity storage SD card.
uses the FAT32 file system, and the SDHC card uses the SD2.0 protocol specification, which stipulates that the storage capacity range of the SDHC card is 2GB
to 32GB; the SDXC card is a newly proposed standard, which is different from the FAT file system used by SD cards and SDHC cards. , SDXC card uses exFAT
file system, which is the extended FAT file system. SDXC cards adopt the SD3.0 protocol specification, which stipulates that the storage capacity of SDXC cards ranges from 32GB to 2TB (2048GB). It is generally used for mid-to-high-end SLR cameras and high-definition cameras.
The following table shows the protocol specifications, capacity levels and supported file systems used by different types of SD cards.
Table 39.1.1 SD card types, protocol specifications, capacity levels and supported file systems
SD cards with different protocol specifications have different representation methods of speed levels. In the SD1.0 protocol specification (less used now),
uses "X" to indicate different speed levels; in the SD2.0 protocol specification, SpeedClass is used to indicate different speed levels; the
SD3.0 protocol specification uses UHS ( Ultra High Speed) represents different speed levels. In the SD2.0 specification, the speed levels of SD cards are divided into ordinary cards (Class2, Class4, Class6) and high-speed cards (Class10); in the SD3.0 specification, the speed levels of SD cards are divided into UHS speed levels 1 and 3. . The different levels of reading and writing speeds and applications are shown in the figure below.
Figure 39.1.2 Representation of different speed levels of SD cards The
SD card has a total of 9 pin lines and can work in SDIO mode or SPI mode.In SDIO mode, six signal lines CLK, CMD,
DAT[3:0] are shared; in SPI mode, CS (SDIO_DAT[3]), CLK (SDIO_CLK), MISO
(SDIO_DAT[0]), MOSI are shared (SDIO_CMD) four signal lines.
SD card interface definition and each pin function description are shown in Figure 39.1.3
.
Figure 39.1.3 SD card interface definition and each pin function description
In addition to standard SD cards on the market, there is also MicroSD card (formerly known as TF card), which is an extremely small flash memory card.
is produced by SanDisk ( Invented by SanDisk, mainly used in mobile phones. The MicroSD card can be converted into an SD card by inserting it into the Adapter, and its operation sequence is the same as that of an SD card. The MicroSD card interface definition and the function description of each pin are shown in Figure 39.1.4
.
Figure 39.1.4 MicroSD card interface definition and each pin function description
In the standard SD card version 2.0, the working clock frequency can reach 50Mhz. In SDIO mode, using 4-bit data width, it can theoretically reach 200Mbps (50Mx4bit) transmission rate; using 1-bit data width in SPI mode, theoretically
can reach a transmission rate of 50Mbps. Therefore, the transfer rate of the SD card in SDIO mode is faster, and its operation timing is also more complex.
For using the SD card to read music files and pictures, the transmission speed in the SPI mode can already meet our needs, so
we use the SPI mode of the SD card in this chapter to read and write the SD card. Before the
SD card can perform normal reading and writing operations, the SD card must be initialized. The initialization process of the SD card is to write the
command to the SD to make it work in the expected working mode. When reading and writing to the SD card, you also need to send write commands and read commands first,
. Therefore, the command format of the SD card is an important part of learning the SD card. The command format of the SD card consists of 6 bytes. When sending data, the high
bit comes first. The write command format of the SD card is as shown below:
Figure 39.1.5 SD card command format
Byte1: the first command word The byte is the command number (such as CMD0, CMD1, etc.), and the format is "0 1 x x x x x x". The highest bit of the
command number is always 0, which is the starting bit of the command number; the second highest bit is always 1, which is the sending bit of the command number; the lower 6 bits are the specific command number of
(such as CMD55, 8'd55 = 8' b0011_0111, the command number is 0 1 1 1 0 1 1 1 = 0x77).
Byte2~Byte5: command parameters. Some command parameters are reserved bits, and the content of the parameters is not defined. The reserved bits should be set to 0 for
.
Byte6: The first 7 bits are CRC (cyclic redundancy check) check bits, and the last bit is stop bit 0. The SD card does not enable CRC check by default in SPI mode, and enables CRC check in SDIO mode. That is to say, in SPI mode, the CRC check digit must be sent, but the SD card will automatically ignore the CRC check digit when it reads it, so all check digits can be set to 1. It should be noted that the SD
card is in SDIO mode by default when it is powered on. When receiving the response command returned by the SD card to CMD0, pull down the chip select CS and enter the SPI mode. So when
sends the CMD0 command, the SD card is in SDIO mode and CRC verification needs to be turned on. In addition, the CRC check of CMD8 is always enabled in
, and the CRC check also needs to be enabled. Except for these two commands, the CRC of other commands does not need to be verified. The commands of the
SD card are divided into standard commands (such as CMD0) and application-related commands (such as ACMD41). The ACMD command is a special command. The sending method of
is the same as the standard command. However, before sending the application-related command, the CMD55 command must be sent first to tell the SD card
that the next command is an application-related command, not a standard command. After sending the command, the SD card will return information in response to the command. Different CMD commands of
will have different types of return values. Commonly used return values are R1 type, R3 type and R7 type (the R7 type is dedicated to the
CMD8 command). The common commands of SD card are described in the following table (Table 39.1.2).
Table 39.1.2 SD card common command description
The SD card return type R1 data format is shown in the following figure:
Figure 39.1.6 SD card return type R1 data format
As can be seen from the above figure, the SD card return type R1 format returns a total of 1 Byte, the highest bit is fixed to 0, the other bits respectively represent the flags corresponding to the
status, and the high level is valid.
SD card return type R3 data format is shown in the following figure:
Figure 39.1.7 SD card return type R3 data format
As can be seen from the above figure, the SD card return type R3 format returns a total of 5 bytes, and the first word is returned first. The first section is the content of
R1 introduced earlier, and the remaining bytes are the content of
register of OCR (Operation Conditions Register, operating condition register).
The SD card return type R7 data format is as shown in the figure below:
Figure 39.1.8 SD card return type R7 data format
As can be seen from the above figure, the SD card return type R7 format returns a total of 5 bytes, and the first word is returned first. The section is the content of
R1 introduced earlier, and the remaining bytes include SD card operating voltage information and check bytes. The voltage range is an important parameter of
. Its specific content is as follows:
Bit[11:8]: operating voltage feedback
0: undefined
1: 2.7V~3.6V
2: low voltage
4: reserved bit
8: Reserved bit
Others: Undefined
Before the SD card can perform normal read and write operations, the SD card must be initialized to make it work in the expected working mode. There is a difference between the SD card
1.0 version protocol and the 2.0 version protocol during the initialization process. Only the SD card with the SD2.0 version protocol supports the CMD8 command
command, so the SD card that responds to this command can be judged to be of the SD2.0 version protocol. card, otherwise it is an SD card or
MMC card with SD1.0 protocol version; for the case where CMD8 does not respond, you can send the CMD55 + ACMD41 command. If 0 is returned, it means that the SD1.0 protocol version card is initialized successfully. If an error is returned , then it is determined to be an MMC card; after it is determined to be an MMC card, continue to send the CMD1
command to the card. If 0 is returned, the MMC card is initialized successfully, otherwise it is determined to be an incorrect card.
Since most SD cards on the market use the SD2.0 version protocol, we will only introduce the initialization process of the SD2.0 version protocol. The SD cards mentioned below all represent SDHC cards based on the SD2.0 version protocol. The detailed initialization steps are as follows:
1. After the SD card is powered on, the host FPGA first sends at least 74 synchronization clocks to the slave SD card. During the same
step of powering on, the chip select CS pin and MOSI pin must be High level (the MOSI pin is high level at all times except for sending commands or data);
2, pull down the chip select CS pin, send the command CMD0 (0x40) to reset the SD card, and wait after the command is sent. The SD card returns response data;
3, After the SD card returns the response data, it waits for 8 clock cycles and then pulls up the chip select CS signal. At this time, the returned response
data is judged. If the returned data is the reset completion signal 0x01, the chip select CS is low during the period of receiving the returned information.
At this time, the SD card enters the SPI mode and starts the next step. If the returned value is another value, re-execute the first step.
2 step;
4, pull down the chip select CS pin, send the command CMD8 (0x48) to query the version number of the SD card. Only the SD2.0 version of the card
supports this command. After the command is sent, wait for the SD card to return the response data;
5. After the SD card returns the response data, wait for 8 clock cycles before pulling up the chip select CS signal. At this time, the returned response
data is judged. If the returned voltage range is 4'b0001, which is 2.7V~3.6V, it means that the SD card is version 2.0, proceed to the next
step, otherwise re-execute step 4;
6, pull down the chip select CS pin, and send the command CMD55 (0x77) Tells the SD card that the next command sent is the application-related
command. After the command is sent, wait for the SD card to return the response data;
7. After the SD card returns the response data, wait for 8 clock cycles before raising the chip select CS signal. , at this time, the returned response
data is judged.If the returned data is idle signal 0x01, proceed to the next step, otherwise re-execute step 6.
8. Pull down the chip select CS pin, send the command ACMD41 (0x69) to check whether the SD card has been initialized. After sending the command
, wait for the SD card to return response data;
9. After the SD card returns the response data, wait for 8 clocks. The chip select CS signal is pulled high periodically, and the returned response
data is judged. If the returned data is 0x00, the initialization is completed, otherwise step 6 will be performed again.
SD card power-on and reset command timing is shown in the figure below:
Figure 39.1.9 SD card power-on and reset command timing diagram
At this point, the SD card has completed the reset and initialization operations and entered the read and write operations in SPI mode. It should be noted that when the SD
card is initialized, the clock frequency of SPI_CLK cannot exceed 400KHz. After the initialization is completed, switch the
clock frequency of SPI_CLK to the maximum clock frequency of the SD card. Although many SD cards currently on the market support
initialization at a faster clock frequency, in order to be compatible with more SD cards, the clock frequency cannot exceed 400KHz when the SD card is initialized. The amount of data read and written to the SD card once must be an integer multiple of 512 bytes, that is, the minimum amount of data required to read and write the SD card is 512
bytes. We can configure the data length of a single read and write operation through the command CMD16, so that the amount of data read and written each time is
(n*512) bytes (n≥1). This SD card read and write operation uses The default configuration of the SD card is that the amount of data
for a single read and write operation is 512 bytes. After the
SD card is initialized, you can perform a read and write test on the SD card. The read and write test on the SD card is to first write data to the SD card, and then
reads the data from the SD card and verifies the correctness of the data. The SD card write operation timing diagram is shown in the figure below:
Figure 39.1.10 SD card write operation timing diagram
The SD card write operation process is as follows:
1. Pull down the chip select CS pin and send the command CMD24 (0x58) to read a single Data block, after the command is sent, wait for the
SD card to return the response data;
2, after the SD card returns the correct response data 0x00, wait for at least 8 clock cycles, and start sending the data header 0xfe;
3, after sending the data header 0xfe, start next Send 512 bytes of data;
4. After the data is sent, send 2 bytes of CRC check data. Since CRC verification is not performed on the data in SPI mode
, just send two bytes of 0xff directly;
5. After the verification data is sent, wait for the SD card to respond;
6. After the SD card returns the response data, it will enter the write busy state. (MISO pin is low level), that is, no other operations are allowed at this time. When it is detected that the MISO pin is high, the SD card exits the write busy state;
7, pulls the CS pin high and waits for 8 clock cycles to allow other operations. The read operation timing diagram of
SD card is shown in the figure below:
Figure 39.1.11 SD card read operation timing diagram The read operation flow of
SD card is as follows:
1, pull down the chip select CS pin, send the command CMD17 (0x51) to read a single Data block, after the command is sent, wait for the response data returned by the
SD card;
2, after the SD card returns the correct response data 0x00, prepare to start parsing the data header 0xfe returned by the SD card;
3, after parsing the data header 0xfe, then receive the SD card The 512-byte data returned;
4. After the data parsing is completed, the two-byte CRC check value is received. Since the
CRC check is not performed on the data in SPI mode, these two bytes can be ignored directly;
5. After the verification data is received, wait for 8 clock cycles;
6. Pull the chip select CS pin high and wait for 8 clock cycles. Then allow other operations. In the SD card read and write operations introduced earlier,
uses the SPI mode of the SD card, that is, the SPI protocol is used for read and write operations.
SPI and IIC are both commonly used communication protocols on chips. SPI has a higher communication rate than IIC, but it also occupies more
pin lines. Next, let’s take a look at the SPI protocol and transmission timing.
SPI (Serial Peripheral interface) is a serial peripheral device interface defined by Motorola Company .
is a high-speed, full-duplex, synchronous communication bus that only requires four signal lines, saving pins. At the same time, it is beneficial to the layout of PCB
. It is precisely because of this simple and easy-to-use feature that more and more chips now integrate SPI communication protocols, such as FLASH,
AD converters, etc. The communication principle of
SPI is relatively simple. It works in a master-slave manner, usually with a master device (FPGA here) and one or more slave devices (SD card here). SPI communication requires four lines, namely SPI_CS, SPI_CLK, SPI_MOSI and
SPI_MISO. Among them, SPI_CS, SPI_CLK and SPI_MOSI are output from the host to the slave, while SPI_MISO is output from the slave to the master
machine. SPI_CS is used to control whether the chip is selected, which means that the operation of the chip is only effective when the chip select signal is valid (for SD cards, low level
is valid); SPI_CLK is a synchronous clock generated by the host, used Synchronous data; SPI_MOSI
and SPI_MISO are the data pins sent and received by the host.
Generally speaking, there are 4 different modes of SPI communication. Different slave devices are configured by the manufacturer as one of the modes when leaving the factory. The
mode is not allowed to be modified by the user. Master and slave devices must communicate in the same mode, otherwise data will be received incorrectly. The communication mode of
SPI is determined by CPOL (clock polarity) and CPHA (clock phase). The four communication modes are as follows:
mode 0: CPOL = 0, CPHA = 0;
mode 1: CPOL = 0, CPHA = 1;
mode 2: CPOL = 1, CPHA = 0;
mode 3: CPOL = 1, CPHA = 1.
CPOL controls the clock polarity of SPI_CLK. The clock polarity changes as shown in the figure below:
Figure 39.1.12 SPI_CLK clock polarity
As can be seen from the above figure, when CPOL = 1, SPI_CLK is high level when idle, initiating communication. The first clock edge after is the falling edge of
; when CPOL = 0, the SPI clock signal SPI_CLK is low level when idle, and the first clock edge after initiating communication is the rising edge of
.
CPHA is used to control the alignment mode of data and clock. The timing diagrams in different modes are as shown below:
Figure 39.1.13 Timing diagrams in different CPHA modes
As can be seen from the above figure, when CPHA = 1, the clock's A changing edge (rising edge or falling edge) data begins to change,
then means that the second changing edge of the clock (opposite to the first changing edge) latches the data; when CPHA = 0, the data
is in The first changing edge of the clock has changed before and remains stable, which means that the data is locked in
on the first changing edge of the clock. For the SPI mode of the SD card,
uses SPI communication mode 3, that is, CPOL = 1, CPHA = 1. In the SD
card version 2.0 protocol, the SPI_CLK clock frequency can reach 50Mhz.
The above is the entire content of the SD card introduction part. Here you also need to add knowledge about the FAT file system. If the read and write test of SD card
is just to write data, read data and verify the correctness of the data like EEPROM, there is no need for FAT file
system. SD cards are often used to access data on Windows operating systems, and must use the
FAT file system supported by Windows operating systems in order to be used normally on computers.
FAT (File Allocation Table) is a file system used by the Windows operating system. The development process of
has gone through three stages: FAT12, FAT16, and FAT32. The FAT file system uses "clusters" as data units. A "cluster" consists of a group of contiguous sectors, and a sector consists of 512 bytes. The number of sectors contained in the cluster must be the integer power of 2 of
, and the maximum number of sectors is 64, that is, 32KB (512Byte * 64 = 32KB). All clusters are numbered
starting from 2. Each cluster has its own address number. User files and directories are stored in the cluster. The basic structure of the
FAT file system is: partition boot record, file allocation table (FAT table 1 and FAT table 2), root directory
directory and data area.Partition boot record: The partition boot record area usually occupies the first sector of the partition, totaling 512 bytes. Contains four parts of
content: BIOS parameter record block BPB (BIOS Parameter Block), disk mark record table, partition boot record code
area and end mark 0x55AA.
file allocation table (FAT table 1 and FAT table 2): Files are stored in clusters on the disk, but the data
of the same file is not necessarily completely stored in a continuous area of the disk, and is often divided into several Clusters and FAT tables record the information about the connections between clusters in file storage
. This is the chain storage of files. For the FAT16 file system, each cluster uses 16Bit
to represent the file allocation table, while for the FAT32 file system, 32Bit is used to represent the file allocation table. This is the most important difference between the two.
root directory: The root directory is the first cluster number of the file or directory. In the FAT32 file system, there is no longer a rigid requirement for the location of the root directory
, and it can be stored in any addressable cluster within the partition. However, usually the root directory is the earliest established directory table (formatted to generate
) directory table, so what we see is basically that the first cluster of the root directory is next to FAT2, occupying the first cluster
in the cluster area sequence (i.e. Cluster No. 2).
data area: The data area follows the root directory and is where files and other data are stored, occupying most of the disk space.
Experimental Task
The experimental task in this section is to use the FPGA development board to write 512 bytes of data to the sector address specified in the SD card. After writing,
will read the data and verify whether the data is correct.
hardware design
Our Pioneer FPGA development board has an SD card slot for inserting SD cards. The schematic diagram is shown in Figure 39.3.1:
Figure 39.3.1 SD card interface schematic
is shown in the above figure It can be seen that in the SPI mode of the SD card, only the SDIO_D3 (SPI_CS), SDIO_CMD (SPI_MOSI),
SDIO_SCK (SPI_SCK) and SDIO_D0 (SPI_MISO) pins are used, while the other two pins are used in the SDIO mode of the SD card.
arrived.
In this experiment, the pin assignments of each port signal are as shown in the table below.
Table 39.3.1 SD card read and write test experimental pin allocation
Program design
From the SD card initialization, write operation and read operation introduced earlier, it can be seen that the three operations of the SD card are independent of each other and
cannot be performed at the same time. Therefore, we can divide the initialization, write operation and read operation of the SD card into three independent module
blocks, and finally instantiate these three modules in the controller module of the SD card to facilitate use in other engineering projects. Figure 39.4.1
is the system block diagram of the experiment in this chapter. The PLL clock module (PLL) provides a driving clock for each module. The SD card test data generation module
block generates test data and writes it to the SD card. After writing, the data is read from the SD card. , the final reading and writing test results are indicated by the LED display module controlling the display status of the LED light through
.
Figure 39.4.1 SD card read and write test system block diagram
The schematic diagram of the top-level module is shown below:
Figure 39.4.2 Top-level module schematic diagram
As can be seen from the above figure, the start writing signal generated by the SD card test data generation module (wr_start_en) and data (wr_data)
are connected to the SD card controller module. After the data is written, the start reading signal (rd_start_en) is output to read the data (rd_data) from
in the SD card controller. The result of the data test is error_flag Connect to the LED display module to complete data interaction between modules. The
FPGA top-level module (top_sd_rw) instantiates the following four modules: PLL clock module (pll_clk), SD card test
data generation module (data_gen), SD card controller module (sd_ctrl_top) and LED display module (led_alarm).
top-level module (top_sd_rw): The top-level module completes the instantiation of the other four modules. The start writing signal and data generated by the SD card test data generation module
block are connected to the SD card controller module. After the data is written, it is transferred from the SD card Read the data from the card controller,
and verify the correctness of the data, and connect the verification results to the LED display module.
PLL clock module (pll_clk): The PLL clock module is implemented by calling the phase-locked loop (PLL) IP core. It outputs a total of two
clocks with frequencies of 50Mhz, but the phase difference between the two clocks is 180 degrees. We know that the SPI communication mode of the SD card is CPOL=1,
CPHA=1; that is, SPI_CLK is high level when idle, and data is sent on the first edge of the clock, that is, SPI_CLK changes from high
level to low level. Flat transition, so data collection is on the rising edge and data transmission is on the falling edge. In order to use the rising edge of
in the program code, we use two clocks with a phase difference of 180 degrees to operate the SD card.
SD card test data generation module (data_gen): The start writing signal and data
generated by the SD card test data generation module are written into the SD card controller module. After the data is written, the data is read from the SD card controller and verified. For the correctness of the data, the result of verifying
will be sent to the LED display module.
SD card controller module (sd_ctrl_top): The SD card controller module instantiates the SD card initialization module (sd_init),
SD card write data module (sd_write) and SD card read data module (sd_read). The SD card initialization module completes the
power-on initialization operation of the SD card; the SD card writing data module completes the writing operation of the SD card; the SD card reading data module completes the reading operation of the SD card.
Since these three modules all operate the pin signals of the SD card, and these three modules will not operate at the same time at the same time, this
module implements the instantiation of the other three modules and the selection of the SD card. Pins are connected to one of the modules.
LED display module (led_alarm): The LED display module generates the verification result value output by the SD card test data from the module.
indicates it by controlling the display status of the LED light.
1) Experimental platform: Punctual Atomic Pioneer FPGA Development Board
2) Excerpted from "Pioneer FPGA Development Guide" Follow the official WeChat account for more information: Punctual Atom
3) Full set of experimental source code + manual + video download address: http: //www.openedv.com/thread-13912-1-1.html
Chapter 39 SD card reading and writing test experiment
The SD memory card is a new generation of memory device based on semiconductor flash memory. It has the advantages of small size, fast transmission speed,
support for hot swapping, etc., and has been widely used in the field of portable devices, such as digital cameras, multimedia players, notebook computers, etc. In this chapter, we will use the FPGA development board to learn how to read and write the SD card and conduct the SD card read and write test
.
This chapter includes the following parts:
39.1 SD card introduction
39.2 Experimental tasks
39.3 Hardware design
39.4 Program design
39.5 Download verification
SD card introduction
The full English name of SD card is Secure Digital Card, which is secure digital. Card (also called secure digital card) is developed on the basis of MMC card
(Multimedia Card, multimedia card). It mainly adds two features: higher security and
faster reading and writing speed. The length and width of SD card and MMC card are both 32mm x 24mm. The difference is that the thickness of SD card is 2.1mm,
and the thickness of MMC card is 1.4mm. SD card is slightly thicker than MMC card to accommodate larger capacity. At the same time, the SD card has more
pins than the MMC card, and has an extra write-protect switch on the side. SD cards maintain upward compatibility with MMC cards. That is to say, MMC cards
can be accessed by new SD devices. The compatibility depends on the application software, but SD cards cannot be accessed by MMC devices. SD cards and
MMC cards can be distinguished by the markings on the cards. As shown in the figure below, the one marked "MultiMediaCard" with the letters
on the left side of the picture is an MMC card, and the one marked with the letters "SD" on the right side of the picture is an SD card.
Figure 39.1.1 MMC appearance (left) and SD card appearance (right)
The SD card on the right side of the picture above is actually an SDHC card. SD cards are divided into 3 levels in terms of storage capacity, which are: SD card,
SDHC card (Secure Digital High Capacity, high-capacity secure digital card) and SDXC card (SD eXtended Capacity,
expanded capacity secure memory card). The SD card is developed on the basis of the MMC card and uses the FAT12/FAT16 file system. The SD
card adopts the SD1.0 protocol specification, which stipulates that the maximum storage capacity of the SD card is 2GB; the SDHC card is a large-capacity storage SD card.
uses the FAT32 file system, and the SDHC card uses the SD2.0 protocol specification, which stipulates that the storage capacity range of the SDHC card is 2GB
to 32GB; the SDXC card is a newly proposed standard, which is different from the FAT file system used by SD cards and SDHC cards. , SDXC card uses exFAT
file system, which is the extended FAT file system. SDXC cards adopt the SD3.0 protocol specification, which stipulates that the storage capacity of SDXC cards ranges from 32GB to 2TB (2048GB). It is generally used for mid-to-high-end SLR cameras and high-definition cameras.
The following table shows the protocol specifications, capacity levels and supported file systems used by different types of SD cards.
Table 39.1.1 SD card types, protocol specifications, capacity levels and supported file systems
SD cards with different protocol specifications have different representation methods of speed levels. In the SD1.0 protocol specification (less used now),
uses "X" to indicate different speed levels; in the SD2.0 protocol specification, SpeedClass is used to indicate different speed levels; the
SD3.0 protocol specification uses UHS ( Ultra High Speed) represents different speed levels. In the SD2.0 specification, the speed levels of SD cards are divided into ordinary cards (Class2, Class4, Class6) and high-speed cards (Class10); in the SD3.0 specification, the speed levels of SD cards are divided into UHS speed levels 1 and 3. . The different levels of reading and writing speeds and applications are shown in the figure below.
Figure 39.1.2 Representation of different speed levels of SD cards The
SD card has a total of 9 pin lines and can work in SDIO mode or SPI mode.In SDIO mode, six signal lines CLK, CMD,
DAT[3:0] are shared; in SPI mode, CS (SDIO_DAT[3]), CLK (SDIO_CLK), MISO
(SDIO_DAT[0]), MOSI are shared (SDIO_CMD) four signal lines.
SD card interface definition and each pin function description are shown in Figure 39.1.3
.
Figure 39.1.3 SD card interface definition and each pin function description
In addition to standard SD cards on the market, there is also MicroSD card (formerly known as TF card), which is an extremely small flash memory card.
is produced by SanDisk ( Invented by SanDisk, mainly used in mobile phones. The MicroSD card can be converted into an SD card by inserting it into the Adapter, and its operation sequence is the same as that of an SD card. The MicroSD card interface definition and the function description of each pin are shown in Figure 39.1.4
.
Figure 39.1.4 MicroSD card interface definition and each pin function description
In the standard SD card version 2.0, the working clock frequency can reach 50Mhz. In SDIO mode, using 4-bit data width, it can theoretically reach 200Mbps (50Mx4bit) transmission rate; using 1-bit data width in SPI mode, theoretically
can reach a transmission rate of 50Mbps. Therefore, the transfer rate of the SD card in SDIO mode is faster, and its operation timing is also more complex.
For using the SD card to read music files and pictures, the transmission speed in the SPI mode can already meet our needs, so
we use the SPI mode of the SD card in this chapter to read and write the SD card. Before the
SD card can perform normal reading and writing operations, the SD card must be initialized. The initialization process of the SD card is to write the
command to the SD to make it work in the expected working mode. When reading and writing to the SD card, you also need to send write commands and read commands first,
. Therefore, the command format of the SD card is an important part of learning the SD card. The command format of the SD card consists of 6 bytes. When sending data, the high
bit comes first. The write command format of the SD card is as shown below:
Figure 39.1.5 SD card command format
Byte1: the first command word The byte is the command number (such as CMD0, CMD1, etc.), and the format is "0 1 x x x x x x". The highest bit of the
command number is always 0, which is the starting bit of the command number; the second highest bit is always 1, which is the sending bit of the command number; the lower 6 bits are the specific command number of
(such as CMD55, 8'd55 = 8' b0011_0111, the command number is 0 1 1 1 0 1 1 1 = 0x77).
Byte2~Byte5: command parameters. Some command parameters are reserved bits, and the content of the parameters is not defined. The reserved bits should be set to 0 for
.
Byte6: The first 7 bits are CRC (cyclic redundancy check) check bits, and the last bit is stop bit 0. The SD card does not enable CRC check by default in SPI mode, and enables CRC check in SDIO mode. That is to say, in SPI mode, the CRC check digit must be sent, but the SD card will automatically ignore the CRC check digit when it reads it, so all check digits can be set to 1. It should be noted that the SD
card is in SDIO mode by default when it is powered on. When receiving the response command returned by the SD card to CMD0, pull down the chip select CS and enter the SPI mode. So when
sends the CMD0 command, the SD card is in SDIO mode and CRC verification needs to be turned on. In addition, the CRC check of CMD8 is always enabled in
, and the CRC check also needs to be enabled. Except for these two commands, the CRC of other commands does not need to be verified. The commands of the
SD card are divided into standard commands (such as CMD0) and application-related commands (such as ACMD41). The ACMD command is a special command. The sending method of
is the same as the standard command. However, before sending the application-related command, the CMD55 command must be sent first to tell the SD card
that the next command is an application-related command, not a standard command. After sending the command, the SD card will return information in response to the command. Different CMD commands of
will have different types of return values. Commonly used return values are R1 type, R3 type and R7 type (the R7 type is dedicated to the
CMD8 command). The common commands of SD card are described in the following table (Table 39.1.2).
Table 39.1.2 SD card common command description
The SD card return type R1 data format is shown in the following figure:
Figure 39.1.6 SD card return type R1 data format
As can be seen from the above figure, the SD card return type R1 format returns a total of 1 Byte, the highest bit is fixed to 0, the other bits respectively represent the flags corresponding to the
status, and the high level is valid.
SD card return type R3 data format is shown in the following figure:
Figure 39.1.7 SD card return type R3 data format
As can be seen from the above figure, the SD card return type R3 format returns a total of 5 bytes, and the first word is returned first. The first section is the content of
R1 introduced earlier, and the remaining bytes are the content of
register of OCR (Operation Conditions Register, operating condition register).
The SD card return type R7 data format is as shown in the figure below:
Figure 39.1.8 SD card return type R7 data format
As can be seen from the above figure, the SD card return type R7 format returns a total of 5 bytes, and the first word is returned first. The section is the content of
R1 introduced earlier, and the remaining bytes include SD card operating voltage information and check bytes. The voltage range is an important parameter of
. Its specific content is as follows:
Bit[11:8]: operating voltage feedback
0: undefined
1: 2.7V~3.6V
2: low voltage
4: reserved bit
8: Reserved bit
Others: Undefined
Before the SD card can perform normal read and write operations, the SD card must be initialized to make it work in the expected working mode. There is a difference between the SD card
1.0 version protocol and the 2.0 version protocol during the initialization process. Only the SD card with the SD2.0 version protocol supports the CMD8 command
command, so the SD card that responds to this command can be judged to be of the SD2.0 version protocol. card, otherwise it is an SD card or
MMC card with SD1.0 protocol version; for the case where CMD8 does not respond, you can send the CMD55 + ACMD41 command. If 0 is returned, it means that the SD1.0 protocol version card is initialized successfully. If an error is returned , then it is determined to be an MMC card; after it is determined to be an MMC card, continue to send the CMD1
command to the card. If 0 is returned, the MMC card is initialized successfully, otherwise it is determined to be an incorrect card.
Since most SD cards on the market use the SD2.0 version protocol, we will only introduce the initialization process of the SD2.0 version protocol. The SD cards mentioned below all represent SDHC cards based on the SD2.0 version protocol. The detailed initialization steps are as follows:
1. After the SD card is powered on, the host FPGA first sends at least 74 synchronization clocks to the slave SD card. During the same
step of powering on, the chip select CS pin and MOSI pin must be High level (the MOSI pin is high level at all times except for sending commands or data);
2, pull down the chip select CS pin, send the command CMD0 (0x40) to reset the SD card, and wait after the command is sent. The SD card returns response data;
3, After the SD card returns the response data, it waits for 8 clock cycles and then pulls up the chip select CS signal. At this time, the returned response
data is judged. If the returned data is the reset completion signal 0x01, the chip select CS is low during the period of receiving the returned information.
At this time, the SD card enters the SPI mode and starts the next step. If the returned value is another value, re-execute the first step.
2 step;
4, pull down the chip select CS pin, send the command CMD8 (0x48) to query the version number of the SD card. Only the SD2.0 version of the card
supports this command. After the command is sent, wait for the SD card to return the response data;
5. After the SD card returns the response data, wait for 8 clock cycles before pulling up the chip select CS signal. At this time, the returned response
data is judged. If the returned voltage range is 4'b0001, which is 2.7V~3.6V, it means that the SD card is version 2.0, proceed to the next
step, otherwise re-execute step 4;
6, pull down the chip select CS pin, and send the command CMD55 (0x77) Tells the SD card that the next command sent is the application-related
command. After the command is sent, wait for the SD card to return the response data;
7. After the SD card returns the response data, wait for 8 clock cycles before raising the chip select CS signal. , at this time, the returned response
data is judged.If the returned data is idle signal 0x01, proceed to the next step, otherwise re-execute step 6.
8. Pull down the chip select CS pin, send the command ACMD41 (0x69) to check whether the SD card has been initialized. After sending the command
, wait for the SD card to return response data;
9. After the SD card returns the response data, wait for 8 clocks. The chip select CS signal is pulled high periodically, and the returned response
data is judged. If the returned data is 0x00, the initialization is completed, otherwise step 6 will be performed again.
SD card power-on and reset command timing is shown in the figure below:
Figure 39.1.9 SD card power-on and reset command timing diagram
At this point, the SD card has completed the reset and initialization operations and entered the read and write operations in SPI mode. It should be noted that when the SD
card is initialized, the clock frequency of SPI_CLK cannot exceed 400KHz. After the initialization is completed, switch the
clock frequency of SPI_CLK to the maximum clock frequency of the SD card. Although many SD cards currently on the market support
initialization at a faster clock frequency, in order to be compatible with more SD cards, the clock frequency cannot exceed 400KHz when the SD card is initialized. The amount of data read and written to the SD card once must be an integer multiple of 512 bytes, that is, the minimum amount of data required to read and write the SD card is 512
bytes. We can configure the data length of a single read and write operation through the command CMD16, so that the amount of data read and written each time is
(n*512) bytes (n≥1). This SD card read and write operation uses The default configuration of the SD card is that the amount of data
for a single read and write operation is 512 bytes. After the
SD card is initialized, you can perform a read and write test on the SD card. The read and write test on the SD card is to first write data to the SD card, and then
reads the data from the SD card and verifies the correctness of the data. The SD card write operation timing diagram is shown in the figure below:
Figure 39.1.10 SD card write operation timing diagram
The SD card write operation process is as follows:
1. Pull down the chip select CS pin and send the command CMD24 (0x58) to read a single Data block, after the command is sent, wait for the
SD card to return the response data;
2, after the SD card returns the correct response data 0x00, wait for at least 8 clock cycles, and start sending the data header 0xfe;
3, after sending the data header 0xfe, start next Send 512 bytes of data;
4. After the data is sent, send 2 bytes of CRC check data. Since CRC verification is not performed on the data in SPI mode
, just send two bytes of 0xff directly;
5. After the verification data is sent, wait for the SD card to respond;
6. After the SD card returns the response data, it will enter the write busy state. (MISO pin is low level), that is, no other operations are allowed at this time. When it is detected that the MISO pin is high, the SD card exits the write busy state;
7, pulls the CS pin high and waits for 8 clock cycles to allow other operations. The read operation timing diagram of
SD card is shown in the figure below:
Figure 39.1.11 SD card read operation timing diagram The read operation flow of
SD card is as follows:
1, pull down the chip select CS pin, send the command CMD17 (0x51) to read a single Data block, after the command is sent, wait for the response data returned by the
SD card;
2, after the SD card returns the correct response data 0x00, prepare to start parsing the data header 0xfe returned by the SD card;
3, after parsing the data header 0xfe, then receive the SD card The 512-byte data returned;
4. After the data parsing is completed, the two-byte CRC check value is received. Since the
CRC check is not performed on the data in SPI mode, these two bytes can be ignored directly;
5. After the verification data is received, wait for 8 clock cycles;
6. Pull the chip select CS pin high and wait for 8 clock cycles. Then allow other operations. In the SD card read and write operations introduced earlier,
uses the SPI mode of the SD card, that is, the SPI protocol is used for read and write operations.
SPI and IIC are both commonly used communication protocols on chips. SPI has a higher communication rate than IIC, but it also occupies more
pin lines. Next, let’s take a look at the SPI protocol and transmission timing.
SPI (Serial Peripheral interface) is a serial peripheral device interface defined by Motorola Company .
is a high-speed, full-duplex, synchronous communication bus that only requires four signal lines, saving pins. At the same time, it is beneficial to the layout of PCB
. It is precisely because of this simple and easy-to-use feature that more and more chips now integrate SPI communication protocols, such as FLASH,
AD converters, etc. The communication principle of
SPI is relatively simple. It works in a master-slave manner, usually with a master device (FPGA here) and one or more slave devices (SD card here). SPI communication requires four lines, namely SPI_CS, SPI_CLK, SPI_MOSI and
SPI_MISO. Among them, SPI_CS, SPI_CLK and SPI_MOSI are output from the host to the slave, while SPI_MISO is output from the slave to the master
machine. SPI_CS is used to control whether the chip is selected, which means that the operation of the chip is only effective when the chip select signal is valid (for SD cards, low level
is valid); SPI_CLK is a synchronous clock generated by the host, used Synchronous data; SPI_MOSI
and SPI_MISO are the data pins sent and received by the host.
Generally speaking, there are 4 different modes of SPI communication. Different slave devices are configured by the manufacturer as one of the modes when leaving the factory. The
mode is not allowed to be modified by the user. Master and slave devices must communicate in the same mode, otherwise data will be received incorrectly. The communication mode of
SPI is determined by CPOL (clock polarity) and CPHA (clock phase). The four communication modes are as follows:
mode 0: CPOL = 0, CPHA = 0;
mode 1: CPOL = 0, CPHA = 1;
mode 2: CPOL = 1, CPHA = 0;
mode 3: CPOL = 1, CPHA = 1.
CPOL controls the clock polarity of SPI_CLK. The clock polarity changes as shown in the figure below:
Figure 39.1.12 SPI_CLK clock polarity
As can be seen from the above figure, when CPOL = 1, SPI_CLK is high level when idle, initiating communication. The first clock edge after is the falling edge of
; when CPOL = 0, the SPI clock signal SPI_CLK is low level when idle, and the first clock edge after initiating communication is the rising edge of
.
CPHA is used to control the alignment mode of data and clock. The timing diagrams in different modes are as shown below:
Figure 39.1.13 Timing diagrams in different CPHA modes
As can be seen from the above figure, when CPHA = 1, the clock's A changing edge (rising edge or falling edge) data begins to change,
then means that the second changing edge of the clock (opposite to the first changing edge) latches the data; when CPHA = 0, the data
is in The first changing edge of the clock has changed before and remains stable, which means that the data is locked in
on the first changing edge of the clock. For the SPI mode of the SD card,
uses SPI communication mode 3, that is, CPOL = 1, CPHA = 1. In the SD
card version 2.0 protocol, the SPI_CLK clock frequency can reach 50Mhz.
The above is the entire content of the SD card introduction part. Here you also need to add knowledge about the FAT file system. If the read and write test of SD card
is just to write data, read data and verify the correctness of the data like EEPROM, there is no need for FAT file
system. SD cards are often used to access data on Windows operating systems, and must use the
FAT file system supported by Windows operating systems in order to be used normally on computers.
FAT (File Allocation Table) is a file system used by the Windows operating system. The development process of
has gone through three stages: FAT12, FAT16, and FAT32. The FAT file system uses "clusters" as data units. A "cluster" consists of a group of contiguous sectors, and a sector consists of 512 bytes. The number of sectors contained in the cluster must be the integer power of 2 of
, and the maximum number of sectors is 64, that is, 32KB (512Byte * 64 = 32KB). All clusters are numbered
starting from 2. Each cluster has its own address number. User files and directories are stored in the cluster. The basic structure of the
FAT file system is: partition boot record, file allocation table (FAT table 1 and FAT table 2), root directory
directory and data area.Partition boot record: The partition boot record area usually occupies the first sector of the partition, totaling 512 bytes. Contains four parts of
content: BIOS parameter record block BPB (BIOS Parameter Block), disk mark record table, partition boot record code
area and end mark 0x55AA.
file allocation table (FAT table 1 and FAT table 2): Files are stored in clusters on the disk, but the data
of the same file is not necessarily completely stored in a continuous area of the disk, and is often divided into several Clusters and FAT tables record the information about the connections between clusters in file storage
. This is the chain storage of files. For the FAT16 file system, each cluster uses 16Bit
to represent the file allocation table, while for the FAT32 file system, 32Bit is used to represent the file allocation table. This is the most important difference between the two.
root directory: The root directory is the first cluster number of the file or directory. In the FAT32 file system, there is no longer a rigid requirement for the location of the root directory
, and it can be stored in any addressable cluster within the partition. However, usually the root directory is the earliest established directory table (formatted to generate
) directory table, so what we see is basically that the first cluster of the root directory is next to FAT2, occupying the first cluster
in the cluster area sequence (i.e. Cluster No. 2).
data area: The data area follows the root directory and is where files and other data are stored, occupying most of the disk space.
Experimental Task
The experimental task in this section is to use the FPGA development board to write 512 bytes of data to the sector address specified in the SD card. After writing,
will read the data and verify whether the data is correct.
hardware design
Our Pioneer FPGA development board has an SD card slot for inserting SD cards. The schematic diagram is shown in Figure 39.3.1:
Figure 39.3.1 SD card interface schematic
is shown in the above figure It can be seen that in the SPI mode of the SD card, only the SDIO_D3 (SPI_CS), SDIO_CMD (SPI_MOSI),
SDIO_SCK (SPI_SCK) and SDIO_D0 (SPI_MISO) pins are used, while the other two pins are used in the SDIO mode of the SD card.
arrived.
In this experiment, the pin assignments of each port signal are as shown in the table below.
Table 39.3.1 SD card read and write test experimental pin allocation
Program design
From the SD card initialization, write operation and read operation introduced earlier, it can be seen that the three operations of the SD card are independent of each other and
cannot be performed at the same time. Therefore, we can divide the initialization, write operation and read operation of the SD card into three independent module
blocks, and finally instantiate these three modules in the controller module of the SD card to facilitate use in other engineering projects. Figure 39.4.1
is the system block diagram of the experiment in this chapter. The PLL clock module (PLL) provides a driving clock for each module. The SD card test data generation module
block generates test data and writes it to the SD card. After writing, the data is read from the SD card. , the final reading and writing test results are indicated by the LED display module controlling the display status of the LED light through
.
Figure 39.4.1 SD card read and write test system block diagram
The schematic diagram of the top-level module is shown below:
Figure 39.4.2 Top-level module schematic diagram
As can be seen from the above figure, the start writing signal generated by the SD card test data generation module (wr_start_en) and data (wr_data)
are connected to the SD card controller module. After the data is written, the start reading signal (rd_start_en) is output to read the data (rd_data) from
in the SD card controller. The result of the data test is error_flag Connect to the LED display module to complete data interaction between modules. The
FPGA top-level module (top_sd_rw) instantiates the following four modules: PLL clock module (pll_clk), SD card test
data generation module (data_gen), SD card controller module (sd_ctrl_top) and LED display module (led_alarm).
top-level module (top_sd_rw): The top-level module completes the instantiation of the other four modules. The start writing signal and data generated by the SD card test data generation module
block are connected to the SD card controller module. After the data is written, it is transferred from the SD card Read the data from the card controller,
and verify the correctness of the data, and connect the verification results to the LED display module.
PLL clock module (pll_clk): The PLL clock module is implemented by calling the phase-locked loop (PLL) IP core. It outputs a total of two
clocks with frequencies of 50Mhz, but the phase difference between the two clocks is 180 degrees. We know that the SPI communication mode of the SD card is CPOL=1,
CPHA=1; that is, SPI_CLK is high level when idle, and data is sent on the first edge of the clock, that is, SPI_CLK changes from high
level to low level. Flat transition, so data collection is on the rising edge and data transmission is on the falling edge. In order to use the rising edge of
in the program code, we use two clocks with a phase difference of 180 degrees to operate the SD card.
SD card test data generation module (data_gen): The start writing signal and data
generated by the SD card test data generation module are written into the SD card controller module. After the data is written, the data is read from the SD card controller and verified. For the correctness of the data, the result of verifying
will be sent to the LED display module.
SD card controller module (sd_ctrl_top): The SD card controller module instantiates the SD card initialization module (sd_init),
SD card write data module (sd_write) and SD card read data module (sd_read). The SD card initialization module completes the
power-on initialization operation of the SD card; the SD card writing data module completes the writing operation of the SD card; the SD card reading data module completes the reading operation of the SD card.
Since these three modules all operate the pin signals of the SD card, and these three modules will not operate at the same time at the same time, this
module implements the instantiation of the other three modules and the selection of the SD card. Pins are connected to one of the modules.
LED display module (led_alarm): The LED display module generates the verification result value output by the SD card test data from the module.
indicates it by controlling the display status of the LED light.The code of the top-level module of
is as follows:
1 module top_sd_rw(
2 input sys_clk , //System clock
3 input sys_rst_n , //System reset, low level active
4
5 //SD card interface
6 input sd_miso , // SD card SPI serial input data signal
7 output sd_clk , //SD card SPI clock signal
8 output sd_cs , //SD card SPI chip select signal
9 output sd_mosi , //SD card SPI serial output data Signal
10 //LED
11 output [3:0] led //LED light
12 );
13
14 //wire define
15 wire clk_ref ;
16 wire clk_ref_180deg ;
17 wire rst_n ;
18 wire locked ;
19
20 wire wr_start_en ; //Start writing SD card data signal
21 wire [31:0] wr_sec_addr ; //Write data sector address
22 wire [15:0] wr_data ; //Write data
23 wire rd_start_en ; //Start writing SD card data signal
24 wire [31:0] rd_sec_addr ; //Read data sector address
25 wire error_flag ; //SD card read and write error flag
26
27 wire wr_busy ; //Write data busy signal
28 wire wr_req ; //Write data request signal
29 wire rd_busy ; //Read busy signal
30 wire rd_val_en ; //Data reading valid enable signal
31 wire [ 15:0] rd_val_data ; //Read data
32 wire sd_init_done ; //SD card initialization completion signal
33
34 //********************* *********************************
35 //** main code
36 //********** ************************************************
37
38 assign rst_n = sys_rst_n & locked;
39
40 //Phase locked loop
41 pll_clk u_pll_clk(
42 .areset (1'b0 ),
43 .inclk0 (sys_clk ),
44 .c0 (clk_ref ),
45 .c1 (clk_ref_180deg),
46 .locked (locked )
47 );
48
49 //Generate SD card test data
50 data_gen u_data_gen(
51 .clk (clk_ref) ,
52 .rst_n (rst_n),
53 . sd_init_done (sd_init_done),
54 .wr_busy (wr_busy),
55 .wr_req (wr_req),
56 .wr_start_en (wr_start_en),
57 .wr_sec_addr (wr_sec_addr),
58 .wr_data (wr_data) ,
59 .rd_val_en (rd_val_en),
60 .rd_val_data (rd_val_data),
61 .rd_start_en (rd_start_en),
62 .rd_sec_addr (rd_sec_addr),
63 .error_flag (error_flag)
64 );
65
66 //SD card top control module
67 sd_ctrl_top u_sd_ctrl_top(
68 .clk_ref (clk_ref),
69 .clk_ref_180deg (clk_ref_180deg),
70 .rst _n (rst_n),
71 //SD card interface
72 .sd_miso ( sd_miso),
73 .sd_clk (sd_clk),
74 .sd_cs (sd_cs),
75 .sd_mosi (sd_mosi),
76 //User Write SD card interface
77 .wr_start_en (wr_start_en),
78 . wr_sec_addr (wr_sec_addr),
79 .wr_data (wr_data),
80 .wr_busy (wr_busy),
81 .wr_req (wr_req),
82 //User reading SD card interface
83 .rd_start_en (rd_start_en),
84 .rd_sec_addr (rd_sec_addr),
85 .rd_busy (rd_busy),
86 .rd_val_en (rd_val_en),
87 .rd_val_data (rd_val_data),
88
89 .sd_init_done (sd_init_done)
90 );
91
92 / /led alert
93 led_alarm #(
94 .L_TIME (25'd25_000_000)
95 )
96 u_led_alarm(
97 .clk (clk_ref),
98 .rst_n (rst_n),
99 .led (led) ,
100 .error_flag (error_flag)
101 );
102
103 endmodule
The sd_init_done (SD card initialization completion signal) output by the SD card controller module is connected to the SD card test data generation module
block, only after the SD card initialization is completed (sd_ init_done is High level), the SD card can be read and written to test.The SD card
controller module encapsulates the initialization and read and write operations of the SD card into an interface that is convenient for users to call. The SD card test data generation module
only needs to operate the user interface of the SD card controller module to complete the processing of the SD card. Read and write operations.
defines a parameter (L_TIME) in line 94 of the code, which is used to control the LED flashing time when reading and writing test errors occur. The unit of
is 1 clock cycle. Because the input clock frequency is 50Mhz and the period is 20ns, 20 * 25'd25_000_000
= 500ms, so the LED light flashes every 500ms when reading or writing errors.The code of the
SD card controller module is as follows:
1 module sd_ctrl_top(
2 input clk_ref , //Clock signal
3 input clk_ref_180deg, //Clock signal, 180 degrees out of phase with clk_ref
4 input rst_n , //reset signal, Low level active
5 //SD card interface
6 input sd_miso , //SD card SPI serial input data signal
7 output sd_clk , //SD card SPI clock signal
8 output reg sd_cs , //SD card SPI chip select signal
9 output reg sd_mosi , //SD card SPI serial output data signal
10 //User writes SD card interface
11 input wr_start_en , //Start writing SD card data signal
12 input [31:0 ] wr_sec_addr , //Write data sector address
13 input [15:0] wr_data , //Write data
14 output wr_busy , //Write data busy signal
15 output wr_req , // Write data request signal
16 //User read SD card interface
17 input rd_start_en , //Start reading SD card data signal
18 input [31:0] rd_sec_addr , //Read data sector address
19 output rd_busy , //Read data busy signal
20 output rd_val_en , //Read data valid signal
21 output [15:0] rd_val_data , //Read data
22
23 output sd_init_done //SD card initialization complete signal
24 ) ;
25
26 //wire define
27 wire init_sd_clk ; //Low speed clock when initializing SD card
28 wire init_sd_cs ; //Initialization module SD chip select signal
29 wire init_sd_mosi ; //Initialization module SD data output signal
30 wire wr_sd_cs ; //Write data module SD chip select signal
31 wire wr_sd_mosi ; //Write data module SD data output signal
32 wire rd_sd_cs ; //Read data module SD chip select signal
33 wire rd_sd_mosi ; / /Read data module SD data output signal
34
35 //****************************************** ******************
36 //** main code
37 //****************************** ****************************
38
39 //SD card's SPI_CLK
40 assign sd_clk = (sd_init_done==1'b0) ? init_sd_clk : clk_ref_180deg;
41
42 //SD card interface signal selection
43 always @(*) begin
44 //Before the SD card initialization is completed, the port signal and the initialization module signal are connected
45 if(sd_init_done == 1'b0) begin
46 sd_cs= init_sd_cs;
47 SD_MOSI = INIT_SD_MOSI;
48 ND
49 f (WR_BUSY) Begin
50 SD_CS = WR_SD_CS;
51 SD_MOSI = WR_SD_MOSI ;
52 ND
53 LSE IF (rd_busy) begin
54 SD_CS = RD_SD_CS;
55 SD_MOSI = RD_SD_MOSI;
56 nd
57 HTMLSE Begin
588 sd_cs = 1'b1;
59 sd_mosi = 1'b1;
60 end
61 end
62
63 //SD card initialization
64 sd_init u_sd_init(
65 .clk_ref (clk_ref),
66 .rst_n (rst_n),
67
68 .sd_miso (sd_miso),
69 .sd_clk (init_sd_clk),
70 .sd_cs (init_sd_cs),
71 .sd_mosi (init_sd_mosi),
72
73 .sd_init_done (sd_init_done)
74 );
75
76 //SD card write data
77 sd_write u_sd_write(
78 .clk_ref (clk_ref),
79 .clk_ref_180deg (clk_ref_180deg),
80 .rst_n (rst_ n),
81
82 .sd_miso (sd_miso),
83 .sd_cs (wr_sd_cs),
84 .sd_mosi (wr_sd_mosi),
85 //Respond to the write operation after the SD card initialization is completed
86 .wr_start_en (wr_start_en & sd_init_done),
87 .wr_sec_addr (wr_sec_add r),
88 .wr_data (wr_data),
89 .wr_busy (wr_busy),
90 .wr_req (wr_req)
91 );
92
93 //SD card read data
94 sd_read u_sd_read(
95 .clk_ref (clk_ref),
96 .clk_ref_180deg (clk_ref_180deg),
97 .rst_n (rst_n),
98
99 .sd_miso (sd_miso),
100 .sd_cs (rd_sd_cs),
101 .sd_mosi (rd_sd_mosi),
102 //Respond to the read operation after the SD card initialization is completed
103 .rd_start_en (rd_start_en & sd_init_done),
104 .rd_sec_addr (rd_sec_addr),
105 .rd_busy (rd_busy),
106 .rd_val_en (rd _val_en),
107 .rd_val_data (rd_val_data)
108 );
109
110 endmodule
SD card controller The module instantiates the SD card initialization module (sd_init), SD card write data module (sd_write) and SD
card read data module (sd_read).Since these three modules all drive the pins of the SD card, the always block of
starting at line 42 of the code is used to select which module is connected to the pin of the SD card. In line 40 of the code, init_sd_clk is used to provide a slower clock when
initializes the SD card. After the SD card initialization is completed, the faster clock clk_ref_180deg is assigned
to sd_clk. sd_clk has always had a clock since it was powered on, and we said before that the clock of SPI_CLK is high or low when
is idle. In fact, in order to simplify the design, it is also possible for sd_clk to provide the clock when idle. Whether
is valid or not is mainly controlled by the chip select signal.
here mainly introduces how to use the SD card controller module. When the outside needs to read and write the SD card, first
must judge the sd_init_done (SD card initialization is completed) signal. Only after the signal is pulled high can the SD card be read and written; when
writes the SD card, only It is necessary to provide wr_start_en (start writing SD card data signal) and wr_sec_addr (write data
sector address). At this time, the SD card controller module will pull up the wr_busy signal and start writing commands to the SD card; after the command is issued
After success, the SD card controller module will output the wr_req (write data request) signal. At this time, we give wr_data (write data)
to write the data to the SD card; after all data is written, the wr_busy signal is pulled low. , you can initiate read and write operations again. The read operation of the
SD card is to give rd_start_en (rd_start_en) and rd_sec_addr (read data sector address). At this time, the
SD card controller will pull up the rd_busy (read data busy) signal and start to initiate a read command to the SD card; in the command After successful initiation, the
SD card controller module will output the rd_val_en (read data is valid) signal and rd_val_data (read data). After all data
has been read, it will pull down the rd_busy signal. It should be noted that the amount of data written and read out of the SD card in a single time is 512 bytes. Since
is an interface that encapsulates 16-bit data, there will be 256 16-bit data in a single read and write operation. The
SD card initialization module completes the power-on initialization operation of the SD card. We have introduced the initialization process of the
SD card in detail in the introduction section of the SD card. We only need to follow the initialization steps of the SD card to complete the initialization of the SD card. It can be seen from the initial
conversion process of the SD card that its steps are very suitable for state machine writing, and its state jump diagram is shown in Figure 39.4.3.
Figure 39.4.3 SD card initialization state jump diagram
As can be seen from the above figure, we define the SD card initialization process as 7 states, namely st_idle (initial state),
st_send_cmd0 (send software reset command), st_wait_cmd0 (wait for SD card response), st_send_cmd8 (send
CMD8 command), st_send_cmd55 (send CMD55 command), st_send_acmd41 (send ACMD41 command) and
st_init_done (SD card initialization is completed). Because the initialization of the SD card only needs to be executed once after power-on, the state machine has been in the st_init_done state after the initialization of
is completed.Part of the code of the
SD card initialization module is as follows:
112 //Receive the response data returned by the sd card
113 //Latch the data on the rising edge of div_clk_180deg(sd_clk) always @(posedge div_clk_180deg or negedge rst_n) begin
115 if( !rst_n ) begin
116 res_en = 1'b0;
117 res_data = 48'd0;
118 res_flag = 1'b0;
119 res_bit_cnt = 6'd0;
120 end
121 else begin
122 //sd_miso = 0 Start receiving response data
123 if(sd_miso == 1'b0 && res_flag == 1'b0) begin
124 res_flag = 1'b1;
125 res_data = {res_data[46:0],sd_miso};
126 res_bit_cnt = res_bit_cnt + 6'd1;
127 res_en = 1'b0;
128 end
129 else if(res_flag) begin
130 //R1 returns 1 byte, R3 R7 returns 5 bytes
131 //Here, the 6 bytes are uniformly received, and the extra word is Section is NOP (delay of 8 clock cycles)
132 res_data = {res_data[46:0],sd_miso};
133 res_bit_cnt = res_bit_cnt + 6'd1;
134 if(re s_bit_cnt == 6'd47) begin
135 res_flag = 1'b0;
136 res_bit_cnt = 6'd0;
137 res_en = 1'b1;
138 end
139 end
140 else
141 res_en = 1'b0;
142 end
143 end
The SD cardcontroller module encapsulates the initialization and read and write operations of the SD card into an interface that is convenient for users to call. The SD card test data generation module
only needs to operate the user interface of the SD card controller module to complete the processing of the SD card. Read and write operations.
defines a parameter (L_TIME) in line 94 of the code, which is used to control the LED flashing time when reading and writing test errors occur. The unit of
is 1 clock cycle. Because the input clock frequency is 50Mhz and the period is 20ns, 20 * 25'd25_000_000
= 500ms, so the LED light flashes every 500ms when reading or writing errors.
1) Experimental platform: Punctual Atomic Pioneer FPGA Development Board
2) Excerpted from "Pioneer FPGA Development Guide" Follow the official WeChat account for more information: Punctual Atom
3) Full set of experimental source code + manual + video download address: http: //www.openedv.com/thread-13912-1-1.html
Chapter 39 SD card reading and writing test experiment
The SD memory card is a new generation of memory device based on semiconductor flash memory. It has the advantages of small size, fast transmission speed,
support for hot swapping, etc., and has been widely used in the field of portable devices, such as digital cameras, multimedia players, notebook computers, etc. In this chapter, we will use the FPGA development board to learn how to read and write the SD card and conduct the SD card read and write test
.
This chapter includes the following parts:
39.1 SD card introduction
39.2 Experimental tasks
39.3 Hardware design
39.4 Program design
39.5 Download verification
SD card introduction
The full English name of SD card is Secure Digital Card, which is secure digital. Card (also called secure digital card) is developed on the basis of MMC card
(Multimedia Card, multimedia card). It mainly adds two features: higher security and
faster reading and writing speed. The length and width of SD card and MMC card are both 32mm x 24mm. The difference is that the thickness of SD card is 2.1mm,
and the thickness of MMC card is 1.4mm. SD card is slightly thicker than MMC card to accommodate larger capacity. At the same time, the SD card has more
pins than the MMC card, and has an extra write-protect switch on the side. SD cards maintain upward compatibility with MMC cards. That is to say, MMC cards
can be accessed by new SD devices. The compatibility depends on the application software, but SD cards cannot be accessed by MMC devices. SD cards and
MMC cards can be distinguished by the markings on the cards. As shown in the figure below, the one marked "MultiMediaCard" with the letters
on the left side of the picture is an MMC card, and the one marked with the letters "SD" on the right side of the picture is an SD card.
Figure 39.1.1 MMC appearance (left) and SD card appearance (right)
The SD card on the right side of the picture above is actually an SDHC card. SD cards are divided into 3 levels in terms of storage capacity, which are: SD card,
SDHC card (Secure Digital High Capacity, high-capacity secure digital card) and SDXC card (SD eXtended Capacity,
expanded capacity secure memory card). The SD card is developed on the basis of the MMC card and uses the FAT12/FAT16 file system. The SD
card adopts the SD1.0 protocol specification, which stipulates that the maximum storage capacity of the SD card is 2GB; the SDHC card is a large-capacity storage SD card.
uses the FAT32 file system, and the SDHC card uses the SD2.0 protocol specification, which stipulates that the storage capacity range of the SDHC card is 2GB
to 32GB; the SDXC card is a newly proposed standard, which is different from the FAT file system used by SD cards and SDHC cards. , SDXC card uses exFAT
file system, which is the extended FAT file system. SDXC cards adopt the SD3.0 protocol specification, which stipulates that the storage capacity of SDXC cards ranges from 32GB to 2TB (2048GB). It is generally used for mid-to-high-end SLR cameras and high-definition cameras.
The following table shows the protocol specifications, capacity levels and supported file systems used by different types of SD cards.
Table 39.1.1 SD card types, protocol specifications, capacity levels and supported file systems
SD cards with different protocol specifications have different representation methods of speed levels. In the SD1.0 protocol specification (less used now),
uses "X" to indicate different speed levels; in the SD2.0 protocol specification, SpeedClass is used to indicate different speed levels; the
SD3.0 protocol specification uses UHS ( Ultra High Speed) represents different speed levels. In the SD2.0 specification, the speed levels of SD cards are divided into ordinary cards (Class2, Class4, Class6) and high-speed cards (Class10); in the SD3.0 specification, the speed levels of SD cards are divided into UHS speed levels 1 and 3. . The different levels of reading and writing speeds and applications are shown in the figure below.
Figure 39.1.2 Representation of different speed levels of SD cards The
SD card has a total of 9 pin lines and can work in SDIO mode or SPI mode.In SDIO mode, six signal lines CLK, CMD,
DAT[3:0] are shared; in SPI mode, CS (SDIO_DAT[3]), CLK (SDIO_CLK), MISO
(SDIO_DAT[0]), MOSI are shared (SDIO_CMD) four signal lines.
SD card interface definition and each pin function description are shown in Figure 39.1.3
.
Figure 39.1.3 SD card interface definition and each pin function description
In addition to standard SD cards on the market, there is also MicroSD card (formerly known as TF card), which is an extremely small flash memory card.
is produced by SanDisk ( Invented by SanDisk, mainly used in mobile phones. The MicroSD card can be converted into an SD card by inserting it into the Adapter, and its operation sequence is the same as that of an SD card. The MicroSD card interface definition and the function description of each pin are shown in Figure 39.1.4
.
Figure 39.1.4 MicroSD card interface definition and each pin function description
In the standard SD card version 2.0, the working clock frequency can reach 50Mhz. In SDIO mode, using 4-bit data width, it can theoretically reach 200Mbps (50Mx4bit) transmission rate; using 1-bit data width in SPI mode, theoretically
can reach a transmission rate of 50Mbps. Therefore, the transfer rate of the SD card in SDIO mode is faster, and its operation timing is also more complex.
For using the SD card to read music files and pictures, the transmission speed in the SPI mode can already meet our needs, so
we use the SPI mode of the SD card in this chapter to read and write the SD card. Before the
SD card can perform normal reading and writing operations, the SD card must be initialized. The initialization process of the SD card is to write the
command to the SD to make it work in the expected working mode. When reading and writing to the SD card, you also need to send write commands and read commands first,
. Therefore, the command format of the SD card is an important part of learning the SD card. The command format of the SD card consists of 6 bytes. When sending data, the high
bit comes first. The write command format of the SD card is as shown below:
Figure 39.1.5 SD card command format
Byte1: the first command word The byte is the command number (such as CMD0, CMD1, etc.), and the format is "0 1 x x x x x x". The highest bit of the
command number is always 0, which is the starting bit of the command number; the second highest bit is always 1, which is the sending bit of the command number; the lower 6 bits are the specific command number of
(such as CMD55, 8'd55 = 8' b0011_0111, the command number is 0 1 1 1 0 1 1 1 = 0x77).
Byte2~Byte5: command parameters. Some command parameters are reserved bits, and the content of the parameters is not defined. The reserved bits should be set to 0 for
.
Byte6: The first 7 bits are CRC (cyclic redundancy check) check bits, and the last bit is stop bit 0. The SD card does not enable CRC check by default in SPI mode, and enables CRC check in SDIO mode. That is to say, in SPI mode, the CRC check digit must be sent, but the SD card will automatically ignore the CRC check digit when it reads it, so all check digits can be set to 1. It should be noted that the SD
card is in SDIO mode by default when it is powered on. When receiving the response command returned by the SD card to CMD0, pull down the chip select CS and enter the SPI mode. So when
sends the CMD0 command, the SD card is in SDIO mode and CRC verification needs to be turned on. In addition, the CRC check of CMD8 is always enabled in
, and the CRC check also needs to be enabled. Except for these two commands, the CRC of other commands does not need to be verified. The commands of the
SD card are divided into standard commands (such as CMD0) and application-related commands (such as ACMD41). The ACMD command is a special command. The sending method of
is the same as the standard command. However, before sending the application-related command, the CMD55 command must be sent first to tell the SD card
that the next command is an application-related command, not a standard command. After sending the command, the SD card will return information in response to the command. Different CMD commands of
will have different types of return values. Commonly used return values are R1 type, R3 type and R7 type (the R7 type is dedicated to the
CMD8 command). The common commands of SD card are described in the following table (Table 39.1.2).
Table 39.1.2 SD card common command description
The SD card return type R1 data format is shown in the following figure:
Figure 39.1.6 SD card return type R1 data format
As can be seen from the above figure, the SD card return type R1 format returns a total of 1 Byte, the highest bit is fixed to 0, the other bits respectively represent the flags corresponding to the
status, and the high level is valid.
SD card return type R3 data format is shown in the following figure:
Figure 39.1.7 SD card return type R3 data format
As can be seen from the above figure, the SD card return type R3 format returns a total of 5 bytes, and the first word is returned first. The first section is the content of
R1 introduced earlier, and the remaining bytes are the content of
register of OCR (Operation Conditions Register, operating condition register).
The SD card return type R7 data format is as shown in the figure below:
Figure 39.1.8 SD card return type R7 data format
As can be seen from the above figure, the SD card return type R7 format returns a total of 5 bytes, and the first word is returned first. The section is the content of
R1 introduced earlier, and the remaining bytes include SD card operating voltage information and check bytes. The voltage range is an important parameter of
. Its specific content is as follows:
Bit[11:8]: operating voltage feedback
0: undefined
1: 2.7V~3.6V
2: low voltage
4: reserved bit
8: Reserved bit
Others: Undefined
Before the SD card can perform normal read and write operations, the SD card must be initialized to make it work in the expected working mode. There is a difference between the SD card
1.0 version protocol and the 2.0 version protocol during the initialization process. Only the SD card with the SD2.0 version protocol supports the CMD8 command
command, so the SD card that responds to this command can be judged to be of the SD2.0 version protocol. card, otherwise it is an SD card or
MMC card with SD1.0 protocol version; for the case where CMD8 does not respond, you can send the CMD55 + ACMD41 command. If 0 is returned, it means that the SD1.0 protocol version card is initialized successfully. If an error is returned , then it is determined to be an MMC card; after it is determined to be an MMC card, continue to send the CMD1
command to the card. If 0 is returned, the MMC card is initialized successfully, otherwise it is determined to be an incorrect card.
Since most SD cards on the market use the SD2.0 version protocol, we will only introduce the initialization process of the SD2.0 version protocol. The SD cards mentioned below all represent SDHC cards based on the SD2.0 version protocol. The detailed initialization steps are as follows:
1. After the SD card is powered on, the host FPGA first sends at least 74 synchronization clocks to the slave SD card. During the same
step of powering on, the chip select CS pin and MOSI pin must be High level (the MOSI pin is high level at all times except for sending commands or data);
2, pull down the chip select CS pin, send the command CMD0 (0x40) to reset the SD card, and wait after the command is sent. The SD card returns response data;
3, After the SD card returns the response data, it waits for 8 clock cycles and then pulls up the chip select CS signal. At this time, the returned response
data is judged. If the returned data is the reset completion signal 0x01, the chip select CS is low during the period of receiving the returned information.
At this time, the SD card enters the SPI mode and starts the next step. If the returned value is another value, re-execute the first step.
2 step;
4, pull down the chip select CS pin, send the command CMD8 (0x48) to query the version number of the SD card. Only the SD2.0 version of the card
supports this command. After the command is sent, wait for the SD card to return the response data;
5. After the SD card returns the response data, wait for 8 clock cycles before pulling up the chip select CS signal. At this time, the returned response
data is judged. If the returned voltage range is 4'b0001, which is 2.7V~3.6V, it means that the SD card is version 2.0, proceed to the next
step, otherwise re-execute step 4;
6, pull down the chip select CS pin, and send the command CMD55 (0x77) Tells the SD card that the next command sent is the application-related
command. After the command is sent, wait for the SD card to return the response data;
7. After the SD card returns the response data, wait for 8 clock cycles before raising the chip select CS signal. , at this time, the returned response
data is judged.If the returned data is idle signal 0x01, proceed to the next step, otherwise re-execute step 6.
8. Pull down the chip select CS pin, send the command ACMD41 (0x69) to check whether the SD card has been initialized. After sending the command
, wait for the SD card to return response data;
9. After the SD card returns the response data, wait for 8 clocks. The chip select CS signal is pulled high periodically, and the returned response
data is judged. If the returned data is 0x00, the initialization is completed, otherwise step 6 will be performed again.
SD card power-on and reset command timing is shown in the figure below:
Figure 39.1.9 SD card power-on and reset command timing diagram
At this point, the SD card has completed the reset and initialization operations and entered the read and write operations in SPI mode. It should be noted that when the SD
card is initialized, the clock frequency of SPI_CLK cannot exceed 400KHz. After the initialization is completed, switch the
clock frequency of SPI_CLK to the maximum clock frequency of the SD card. Although many SD cards currently on the market support
initialization at a faster clock frequency, in order to be compatible with more SD cards, the clock frequency cannot exceed 400KHz when the SD card is initialized. The amount of data read and written to the SD card once must be an integer multiple of 512 bytes, that is, the minimum amount of data required to read and write the SD card is 512
bytes. We can configure the data length of a single read and write operation through the command CMD16, so that the amount of data read and written each time is
(n*512) bytes (n≥1). This SD card read and write operation uses The default configuration of the SD card is that the amount of data
for a single read and write operation is 512 bytes. After the
SD card is initialized, you can perform a read and write test on the SD card. The read and write test on the SD card is to first write data to the SD card, and then
reads the data from the SD card and verifies the correctness of the data. The SD card write operation timing diagram is shown in the figure below:
Figure 39.1.10 SD card write operation timing diagram
The SD card write operation process is as follows:
1. Pull down the chip select CS pin and send the command CMD24 (0x58) to read a single Data block, after the command is sent, wait for the
SD card to return the response data;
2, after the SD card returns the correct response data 0x00, wait for at least 8 clock cycles, and start sending the data header 0xfe;
3, after sending the data header 0xfe, start next Send 512 bytes of data;
4. After the data is sent, send 2 bytes of CRC check data. Since CRC verification is not performed on the data in SPI mode
, just send two bytes of 0xff directly;
5. After the verification data is sent, wait for the SD card to respond;
6. After the SD card returns the response data, it will enter the write busy state. (MISO pin is low level), that is, no other operations are allowed at this time. When it is detected that the MISO pin is high, the SD card exits the write busy state;
7, pulls the CS pin high and waits for 8 clock cycles to allow other operations. The read operation timing diagram of
SD card is shown in the figure below:
Figure 39.1.11 SD card read operation timing diagram The read operation flow of
SD card is as follows:
1, pull down the chip select CS pin, send the command CMD17 (0x51) to read a single Data block, after the command is sent, wait for the response data returned by the
SD card;
2, after the SD card returns the correct response data 0x00, prepare to start parsing the data header 0xfe returned by the SD card;
3, after parsing the data header 0xfe, then receive the SD card The 512-byte data returned;
4. After the data parsing is completed, the two-byte CRC check value is received. Since the
CRC check is not performed on the data in SPI mode, these two bytes can be ignored directly;
5. After the verification data is received, wait for 8 clock cycles;
6. Pull the chip select CS pin high and wait for 8 clock cycles. Then allow other operations. In the SD card read and write operations introduced earlier,
uses the SPI mode of the SD card, that is, the SPI protocol is used for read and write operations.
SPI and IIC are both commonly used communication protocols on chips. SPI has a higher communication rate than IIC, but it also occupies more
pin lines. Next, let’s take a look at the SPI protocol and transmission timing.
SPI (Serial Peripheral interface) is a serial peripheral device interface defined by Motorola Company .
is a high-speed, full-duplex, synchronous communication bus that only requires four signal lines, saving pins. At the same time, it is beneficial to the layout of PCB
. It is precisely because of this simple and easy-to-use feature that more and more chips now integrate SPI communication protocols, such as FLASH,
AD converters, etc. The communication principle of
SPI is relatively simple. It works in a master-slave manner, usually with a master device (FPGA here) and one or more slave devices (SD card here). SPI communication requires four lines, namely SPI_CS, SPI_CLK, SPI_MOSI and
SPI_MISO. Among them, SPI_CS, SPI_CLK and SPI_MOSI are output from the host to the slave, while SPI_MISO is output from the slave to the master
machine. SPI_CS is used to control whether the chip is selected, which means that the operation of the chip is only effective when the chip select signal is valid (for SD cards, low level
is valid); SPI_CLK is a synchronous clock generated by the host, used Synchronous data; SPI_MOSI
and SPI_MISO are the data pins sent and received by the host.
Generally speaking, there are 4 different modes of SPI communication. Different slave devices are configured by the manufacturer as one of the modes when leaving the factory. The
mode is not allowed to be modified by the user. Master and slave devices must communicate in the same mode, otherwise data will be received incorrectly. The communication mode of
SPI is determined by CPOL (clock polarity) and CPHA (clock phase). The four communication modes are as follows:
mode 0: CPOL = 0, CPHA = 0;
mode 1: CPOL = 0, CPHA = 1;
mode 2: CPOL = 1, CPHA = 0;
mode 3: CPOL = 1, CPHA = 1.
CPOL controls the clock polarity of SPI_CLK. The clock polarity changes as shown in the figure below:
Figure 39.1.12 SPI_CLK clock polarity
As can be seen from the above figure, when CPOL = 1, SPI_CLK is high level when idle, initiating communication. The first clock edge after is the falling edge of
; when CPOL = 0, the SPI clock signal SPI_CLK is low level when idle, and the first clock edge after initiating communication is the rising edge of
.
CPHA is used to control the alignment mode of data and clock. The timing diagrams in different modes are as shown below:
Figure 39.1.13 Timing diagrams in different CPHA modes
As can be seen from the above figure, when CPHA = 1, the clock's A changing edge (rising edge or falling edge) data begins to change,
then means that the second changing edge of the clock (opposite to the first changing edge) latches the data; when CPHA = 0, the data
is in The first changing edge of the clock has changed before and remains stable, which means that the data is locked in
on the first changing edge of the clock. For the SPI mode of the SD card,
uses SPI communication mode 3, that is, CPOL = 1, CPHA = 1. In the SD
card version 2.0 protocol, the SPI_CLK clock frequency can reach 50Mhz.
The above is the entire content of the SD card introduction part. Here you also need to add knowledge about the FAT file system. If the read and write test of SD card
is just to write data, read data and verify the correctness of the data like EEPROM, there is no need for FAT file
system. SD cards are often used to access data on Windows operating systems, and must use the
FAT file system supported by Windows operating systems in order to be used normally on computers.
FAT (File Allocation Table) is a file system used by the Windows operating system. The development process of
has gone through three stages: FAT12, FAT16, and FAT32. The FAT file system uses "clusters" as data units. A "cluster" consists of a group of contiguous sectors, and a sector consists of 512 bytes. The number of sectors contained in the cluster must be the integer power of 2 of
, and the maximum number of sectors is 64, that is, 32KB (512Byte * 64 = 32KB). All clusters are numbered
starting from 2. Each cluster has its own address number. User files and directories are stored in the cluster. The basic structure of the
FAT file system is: partition boot record, file allocation table (FAT table 1 and FAT table 2), root directory
directory and data area.Partition boot record: The partition boot record area usually occupies the first sector of the partition, totaling 512 bytes. Contains four parts of
content: BIOS parameter record block BPB (BIOS Parameter Block), disk mark record table, partition boot record code
area and end mark 0x55AA.
file allocation table (FAT table 1 and FAT table 2): Files are stored in clusters on the disk, but the data
of the same file is not necessarily completely stored in a continuous area of the disk, and is often divided into several Clusters and FAT tables record the information about the connections between clusters in file storage
. This is the chain storage of files. For the FAT16 file system, each cluster uses 16Bit
to represent the file allocation table, while for the FAT32 file system, 32Bit is used to represent the file allocation table. This is the most important difference between the two.
root directory: The root directory is the first cluster number of the file or directory. In the FAT32 file system, there is no longer a rigid requirement for the location of the root directory
, and it can be stored in any addressable cluster within the partition. However, usually the root directory is the earliest established directory table (formatted to generate
) directory table, so what we see is basically that the first cluster of the root directory is next to FAT2, occupying the first cluster
in the cluster area sequence (i.e. Cluster No. 2).
data area: The data area follows the root directory and is where files and other data are stored, occupying most of the disk space.
Experimental Task
The experimental task in this section is to use the FPGA development board to write 512 bytes of data to the sector address specified in the SD card. After writing,
will read the data and verify whether the data is correct.
hardware design
Our Pioneer FPGA development board has an SD card slot for inserting SD cards. The schematic diagram is shown in Figure 39.3.1:
Figure 39.3.1 SD card interface schematic
is shown in the above figure It can be seen that in the SPI mode of the SD card, only the SDIO_D3 (SPI_CS), SDIO_CMD (SPI_MOSI),
SDIO_SCK (SPI_SCK) and SDIO_D0 (SPI_MISO) pins are used, while the other two pins are used in the SDIO mode of the SD card.
arrived.
In this experiment, the pin assignments of each port signal are as shown in the table below.
Table 39.3.1 SD card read and write test experimental pin allocation
Program design
From the SD card initialization, write operation and read operation introduced earlier, it can be seen that the three operations of the SD card are independent of each other and
cannot be performed at the same time. Therefore, we can divide the initialization, write operation and read operation of the SD card into three independent module
blocks, and finally instantiate these three modules in the controller module of the SD card to facilitate use in other engineering projects. Figure 39.4.1
is the system block diagram of the experiment in this chapter. The PLL clock module (PLL) provides a driving clock for each module. The SD card test data generation module
block generates test data and writes it to the SD card. After writing, the data is read from the SD card. , the final reading and writing test results are indicated by the LED display module controlling the display status of the LED light through
.
Figure 39.4.1 SD card read and write test system block diagram
The schematic diagram of the top-level module is shown below:
Figure 39.4.2 Top-level module schematic diagram
As can be seen from the above figure, the start writing signal generated by the SD card test data generation module (wr_start_en) and data (wr_data)
are connected to the SD card controller module. After the data is written, the start reading signal (rd_start_en) is output to read the data (rd_data) from
in the SD card controller. The result of the data test is error_flag Connect to the LED display module to complete data interaction between modules. The
FPGA top-level module (top_sd_rw) instantiates the following four modules: PLL clock module (pll_clk), SD card test
data generation module (data_gen), SD card controller module (sd_ctrl_top) and LED display module (led_alarm).
top-level module (top_sd_rw): The top-level module completes the instantiation of the other four modules. The start writing signal and data generated by the SD card test data generation module
block are connected to the SD card controller module. After the data is written, it is transferred from the SD card Read the data from the card controller,
and verify the correctness of the data, and connect the verification results to the LED display module.
PLL clock module (pll_clk): The PLL clock module is implemented by calling the phase-locked loop (PLL) IP core. It outputs a total of two
clocks with frequencies of 50Mhz, but the phase difference between the two clocks is 180 degrees. We know that the SPI communication mode of the SD card is CPOL=1,
CPHA=1; that is, SPI_CLK is high level when idle, and data is sent on the first edge of the clock, that is, SPI_CLK changes from high
level to low level. Flat transition, so data collection is on the rising edge and data transmission is on the falling edge. In order to use the rising edge of
in the program code, we use two clocks with a phase difference of 180 degrees to operate the SD card.
SD card test data generation module (data_gen): The start writing signal and data
generated by the SD card test data generation module are written into the SD card controller module. After the data is written, the data is read from the SD card controller and verified. For the correctness of the data, the result of verifying
will be sent to the LED display module.
SD card controller module (sd_ctrl_top): The SD card controller module instantiates the SD card initialization module (sd_init),
SD card write data module (sd_write) and SD card read data module (sd_read). The SD card initialization module completes the
power-on initialization operation of the SD card; the SD card writing data module completes the writing operation of the SD card; the SD card reading data module completes the reading operation of the SD card.
Since these three modules all operate the pin signals of the SD card, and these three modules will not operate at the same time at the same time, this
module implements the instantiation of the other three modules and the selection of the SD card. Pins are connected to one of the modules.
LED display module (led_alarm): The LED display module generates the verification result value output by the SD card test data from the module.
indicates it by controlling the display status of the LED light.The code of the top-level module of
is as follows:
1 module top_sd_rw(
2 input sys_clk , //System clock
3 input sys_rst_n , //System reset, low level active
4
5 //SD card interface
6 input sd_miso , // SD card SPI serial input data signal
7 output sd_clk , //SD card SPI clock signal
8 output sd_cs , //SD card SPI chip select signal
9 output sd_mosi , //SD card SPI serial output data Signal
10 //LED
11 output [3:0] led //LED light
12 );
13
14 //wire define
15 wire clk_ref ;
16 wire clk_ref_180deg ;
17 wire rst_n ;
18 wire locked ;
19
20 wire wr_start_en ; //Start writing SD card data signal
21 wire [31:0] wr_sec_addr ; //Write data sector address
22 wire [15:0] wr_data ; //Write data
23 wire rd_start_en ; //Start writing SD card data signal
24 wire [31:0] rd_sec_addr ; //Read data sector address
25 wire error_flag ; //SD card read and write error flag
26
27 wire wr_busy ; //Write data busy signal
28 wire wr_req ; //Write data request signal
29 wire rd_busy ; //Read busy signal
30 wire rd_val_en ; //Data reading valid enable signal
31 wire [ 15:0] rd_val_data ; //Read data
32 wire sd_init_done ; //SD card initialization completion signal
33
34 //********************* *********************************
35 //** main code
36 //********** ************************************************
37
38 assign rst_n = sys_rst_n & locked;
39
40 //Phase locked loop
41 pll_clk u_pll_clk(
42 .areset (1'b0 ),
43 .inclk0 (sys_clk ),
44 .c0 (clk_ref ),
45 .c1 (clk_ref_180deg),
46 .locked (locked )
47 );
48
49 //Generate SD card test data
50 data_gen u_data_gen(
51 .clk (clk_ref) ,
52 .rst_n (rst_n),
53 . sd_init_done (sd_init_done),
54 .wr_busy (wr_busy),
55 .wr_req (wr_req),
56 .wr_start_en (wr_start_en),
57 .wr_sec_addr (wr_sec_addr),
58 .wr_data (wr_data) ,
59 .rd_val_en (rd_val_en),
60 .rd_val_data (rd_val_data),
61 .rd_start_en (rd_start_en),
62 .rd_sec_addr (rd_sec_addr),
63 .error_flag (error_flag)
64 );
65
66 //SD card top control module
67 sd_ctrl_top u_sd_ctrl_top(
68 .clk_ref (clk_ref),
69 .clk_ref_180deg (clk_ref_180deg),
70 .rst _n (rst_n),
71 //SD card interface
72 .sd_miso ( sd_miso),
73 .sd_clk (sd_clk),
74 .sd_cs (sd_cs),
75 .sd_mosi (sd_mosi),
76 //User Write SD card interface
77 .wr_start_en (wr_start_en),
78 . wr_sec_addr (wr_sec_addr),
79 .wr_data (wr_data),
80 .wr_busy (wr_busy),
81 .wr_req (wr_req),
82 //User reading SD card interface
83 .rd_start_en (rd_start_en),
84 .rd_sec_addr (rd_sec_addr),
85 .rd_busy (rd_busy),
86 .rd_val_en (rd_val_en),
87 .rd_val_data (rd_val_data),
88
89 .sd_init_done (sd_init_done)
90 );
91
92 / /led alert
93 led_alarm #(
94 .L_TIME (25'd25_000_000)
95 )
96 u_led_alarm(
97 .clk (clk_ref),
98 .rst_n (rst_n),
99 .led (led) ,
100 .error_flag (error_flag)
101 );
102
103 endmodule
The sd_init_done (SD card initialization completion signal) output by the SD card controller module is connected to the SD card test data generation module
block, only after the SD card initialization is completed (sd_ init_done is High level), the SD card can be read and written to test.The SD card
controller module encapsulates the initialization and read and write operations of the SD card into an interface that is convenient for users to call. The SD card test data generation module
only needs to operate the user interface of the SD card controller module to complete the processing of the SD card. Read and write operations.
defines a parameter (L_TIME) in line 94 of the code, which is used to control the LED flashing time when reading and writing test errors occur. The unit of
is 1 clock cycle. Because the input clock frequency is 50Mhz and the period is 20ns, 20 * 25'd25_000_000
= 500ms, so the LED light flashes every 500ms when reading or writing errors.The code of the
SD card controller module is as follows:
1 module sd_ctrl_top(
2 input clk_ref , //Clock signal
3 input clk_ref_180deg, //Clock signal, 180 degrees out of phase with clk_ref
4 input rst_n , //reset signal, Low level active
5 //SD card interface
6 input sd_miso , //SD card SPI serial input data signal
7 output sd_clk , //SD card SPI clock signal
8 output reg sd_cs , //SD card SPI chip select signal
9 output reg sd_mosi , //SD card SPI serial output data signal
10 //User writes SD card interface
11 input wr_start_en , //Start writing SD card data signal
12 input [31:0 ] wr_sec_addr , //Write data sector address
13 input [15:0] wr_data , //Write data
14 output wr_busy , //Write data busy signal
15 output wr_req , // Write data request signal
16 //User read SD card interface
17 input rd_start_en , //Start reading SD card data signal
18 input [31:0] rd_sec_addr , //Read data sector address
19 output rd_busy , //Read data busy signal
20 output rd_val_en , //Read data valid signal
21 output [15:0] rd_val_data , //Read data
22
23 output sd_init_done //SD card initialization complete signal
24 ) ;
25
26 //wire define
27 wire init_sd_clk ; //Low speed clock when initializing SD card
28 wire init_sd_cs ; //Initialization module SD chip select signal
29 wire init_sd_mosi ; //Initialization module SD data output signal
30 wire wr_sd_cs ; //Write data module SD chip select signal
31 wire wr_sd_mosi ; //Write data module SD data output signal
32 wire rd_sd_cs ; //Read data module SD chip select signal
33 wire rd_sd_mosi ; / /Read data module SD data output signal
34
35 //****************************************** ******************
36 //** main code
37 //****************************** ****************************
38
39 //SD card's SPI_CLK
40 assign sd_clk = (sd_init_done==1'b0) ? init_sd_clk : clk_ref_180deg;
41
42 //SD card interface signal selection
43 always @(*) begin
44 //Before the SD card initialization is completed, the port signal and the initialization module signal are connected
45 if(sd_init_done == 1'b0) begin
46 sd_cs= init_sd_cs;
47 SD_MOSI = INIT_SD_MOSI;
48 ND
49 f (WR_BUSY) Begin
50 SD_CS = WR_SD_CS;
51 SD_MOSI = WR_SD_MOSI ;
52 ND
53 LSE IF (rd_busy) begin
54 SD_CS = RD_SD_CS;
55 SD_MOSI = RD_SD_MOSI;
56 nd
57 HTMLSE Begin
588 sd_cs = 1'b1;
59 sd_mosi = 1'b1;
60 end
61 end
62
63 //SD card initialization
64 sd_init u_sd_init(
65 .clk_ref (clk_ref),
66 .rst_n (rst_n),
67
68 .sd_miso (sd_miso),
69 .sd_clk (init_sd_clk),
70 .sd_cs (init_sd_cs),
71 .sd_mosi (init_sd_mosi),
72
73 .sd_init_done (sd_init_done)
74 );
75
76 //SD card write data
77 sd_write u_sd_write(
78 .clk_ref (clk_ref),
79 .clk_ref_180deg (clk_ref_180deg),
80 .rst_n (rst_ n),
81
82 .sd_miso (sd_miso),
83 .sd_cs (wr_sd_cs),
84 .sd_mosi (wr_sd_mosi),
85 //Respond to the write operation after the SD card initialization is completed
86 .wr_start_en (wr_start_en & sd_init_done),
87 .wr_sec_addr (wr_sec_add r),
88 .wr_data (wr_data),
89 .wr_busy (wr_busy),
90 .wr_req (wr_req)
91 );
92
93 //SD card read data
94 sd_read u_sd_read(
95 .clk_ref (clk_ref),
96 .clk_ref_180deg (clk_ref_180deg),
97 .rst_n (rst_n),
98
99 .sd_miso (sd_miso),
100 .sd_cs (rd_sd_cs),
101 .sd_mosi (rd_sd_mosi),
102 //Respond to the read operation after the SD card initialization is completed
103 .rd_start_en (rd_start_en & sd_init_done),
104 .rd_sec_addr (rd_sec_addr),
105 .rd_busy (rd_busy),
106 .rd_val_en (rd _val_en),
107 .rd_val_data (rd_val_data)
108 );
109
110 endmodule
SD card controller The module instantiates the SD card initialization module (sd_init), SD card write data module (sd_write) and SD
card read data module (sd_read).Since these three modules all drive the pins of the SD card, the always block of
starting at line 42 of the code is used to select which module is connected to the pin of the SD card. In line 40 of the code, init_sd_clk is used to provide a slower clock when
initializes the SD card. After the SD card initialization is completed, the faster clock clk_ref_180deg is assigned
to sd_clk. sd_clk has always had a clock since it was powered on, and we said before that the clock of SPI_CLK is high or low when
is idle. In fact, in order to simplify the design, it is also possible for sd_clk to provide the clock when idle. Whether
is valid or not is mainly controlled by the chip select signal.
here mainly introduces how to use the SD card controller module. When the outside needs to read and write the SD card, first
must judge the sd_init_done (SD card initialization is completed) signal. Only after the signal is pulled high can the SD card be read and written; when
writes the SD card, only It is necessary to provide wr_start_en (start writing SD card data signal) and wr_sec_addr (write data
sector address). At this time, the SD card controller module will pull up the wr_busy signal and start writing commands to the SD card; after the command is issued
After success, the SD card controller module will output the wr_req (write data request) signal. At this time, we give wr_data (write data)
to write the data to the SD card; after all data is written, the wr_busy signal is pulled low. , you can initiate read and write operations again. The read operation of the
SD card is to give rd_start_en (rd_start_en) and rd_sec_addr (read data sector address). At this time, the
SD card controller will pull up the rd_busy (read data busy) signal and start to initiate a read command to the SD card; in the command After successful initiation, the
SD card controller module will output the rd_val_en (read data is valid) signal and rd_val_data (read data). After all data
has been read, it will pull down the rd_busy signal. It should be noted that the amount of data written and read out of the SD card in a single time is 512 bytes. Since
is an interface that encapsulates 16-bit data, there will be 256 16-bit data in a single read and write operation. The
SD card initialization module completes the power-on initialization operation of the SD card. We have introduced the initialization process of the
SD card in detail in the introduction section of the SD card. We only need to follow the initialization steps of the SD card to complete the initialization of the SD card. It can be seen from the initial
conversion process of the SD card that its steps are very suitable for state machine writing, and its state jump diagram is shown in Figure 39.4.3.
Figure 39.4.3 SD card initialization state jump diagram
As can be seen from the above figure, we define the SD card initialization process as 7 states, namely st_idle (initial state),
st_send_cmd0 (send software reset command), st_wait_cmd0 (wait for SD card response), st_send_cmd8 (send
CMD8 command), st_send_cmd55 (send CMD55 command), st_send_acmd41 (send ACMD41 command) and
st_init_done (SD card initialization is completed). Because the initialization of the SD card only needs to be executed once after power-on, the state machine has been in the st_init_done state after the initialization of
is completed.Part of the code of the
SD card initialization module is as follows:
112 //Receive the response data returned by the sd card
113 //Latch the data on the rising edge of div_clk_180deg(sd_clk) always @(posedge div_clk_180deg or negedge rst_n) begin
115 if( !rst_n ) begin
116 res_en = 1'b0;
117 res_data = 48'd0;
118 res_flag = 1'b0;
119 res_bit_cnt = 6'd0;
120 end
121 else begin
122 //sd_miso = 0 Start receiving response data
123 if(sd_miso == 1'b0 && res_flag == 1'b0) begin
124 res_flag = 1'b1;
125 res_data = {res_data[46:0],sd_miso};
126 res_bit_cnt = res_bit_cnt + 6'd1;
127 res_en = 1'b0;
128 end
129 else if(res_flag) begin
130 //R1 returns 1 byte, R3 R7 returns 5 bytes
131 //Here, the 6 bytes are uniformly received, and the extra word is Section is NOP (delay of 8 clock cycles)
132 res_data = {res_data[46:0],sd_miso};
133 res_bit_cnt = res_bit_cnt + 6'd1;
134 if(re s_bit_cnt == 6'd47) begin
135 res_flag = 1'b0;
136 res_bit_cnt = 6'd0;
137 res_en = 1'b1;
138 end
139 end
140 else
141 res_en = 1'b0;
142 end
143 end
Since these three modules all drive the pins of the SD card, the always block ofstarting at line 42 of the code is used to select which module is connected to the pin of the SD card. In line 40 of the code, init_sd_clk is used to provide a slower clock when
initializes the SD card. After the SD card initialization is completed, the faster clock clk_ref_180deg is assigned
to sd_clk. sd_clk has always had a clock since it was powered on, and we said before that the clock of SPI_CLK is high or low when
is idle. In fact, in order to simplify the design, it is also possible for sd_clk to provide the clock when idle. Whether
is valid or not is mainly controlled by the chip select signal.
here mainly introduces how to use the SD card controller module. When the outside needs to read and write the SD card, first
must judge the sd_init_done (SD card initialization is completed) signal. Only after the signal is pulled high can the SD card be read and written; when
writes the SD card, only It is necessary to provide wr_start_en (start writing SD card data signal) and wr_sec_addr (write data
sector address). At this time, the SD card controller module will pull up the wr_busy signal and start writing commands to the SD card; after the command is issued
After success, the SD card controller module will output the wr_req (write data request) signal. At this time, we give wr_data (write data)
to write the data to the SD card; after all data is written, the wr_busy signal is pulled low. , you can initiate read and write operations again. The read operation of the
SD card is to give rd_start_en (rd_start_en) and rd_sec_addr (read data sector address). At this time, the
SD card controller will pull up the rd_busy (read data busy) signal and start to initiate a read command to the SD card; in the command After successful initiation, the
SD card controller module will output the rd_val_en (read data is valid) signal and rd_val_data (read data). After all data
has been read, it will pull down the rd_busy signal. It should be noted that the amount of data written and read out of the SD card in a single time is 512 bytes. Since
is an interface that encapsulates 16-bit data, there will be 256 16-bit data in a single read and write operation. The
SD card initialization module completes the power-on initialization operation of the SD card. We have introduced the initialization process of the
SD card in detail in the introduction section of the SD card. We only need to follow the initialization steps of the SD card to complete the initialization of the SD card. It can be seen from the initial
conversion process of the SD card that its steps are very suitable for state machine writing, and its state jump diagram is shown in Figure 39.4.3.
Figure 39.4.3 SD card initialization state jump diagram
As can be seen from the above figure, we define the SD card initialization process as 7 states, namely st_idle (initial state),
st_send_cmd0 (send software reset command), st_wait_cmd0 (wait for SD card response), st_send_cmd8 (send
CMD8 command), st_send_cmd55 (send CMD55 command), st_send_acmd41 (send ACMD41 command) and
st_init_done (SD card initialization is completed). Because the initialization of the SD card only needs to be executed once after power-on, the state machine has been in the st_init_done state after the initialization of
is completed.Part of the code of the
SD card initialization module is as follows:
112 //Receive the response data returned by the sd card
113 //Latch the data on the rising edge of div_clk_180deg(sd_clk) always @(posedge div_clk_180deg or negedge rst_n) begin
115 if( !rst_n ) begin
116 res_en = 1'b0;
117 res_data = 48'd0;
118 res_flag = 1'b0;
119 res_bit_cnt = 6'd0;
120 end
121 else begin
122 //sd_miso = 0 Start receiving response data
123 if(sd_miso == 1'b0 && res_flag == 1'b0) begin
124 res_flag = 1'b1;
125 res_data = {res_data[46:0],sd_miso};
126 res_bit_cnt = res_bit_cnt + 6'd1;
127 res_en = 1'b0;
128 end
129 else if(res_flag) begin
130 //R1 returns 1 byte, R3 R7 returns 5 bytes
131 //Here, the 6 bytes are uniformly received, and the extra word is Section is NOP (delay of 8 clock cycles)
132 res_data = {res_data[46:0],sd_miso};
133 res_bit_cnt = res_bit_cnt + 6'd1;
134 if(re s_bit_cnt == 6'd47) begin
135 res_flag = 1'b0;
136 res_bit_cnt = 6'd0;
137 res_en = 1'b1;
138 end
139 end
140 else
141 res_en = 1'b0;
142 end
143 end