Design of SD card FAT file system reading and writing based on HCS12X microcontroller

Publisher:Serendipitous33Latest update time:2010-11-18 Source: 单片机与嵌入式系统应用 Reading articles on mobile phones Scan QR code
Read articles on your mobile phone anytime, anywhere

With the rapid development of information technology, high-capacity storage chips are increasingly developing towards large capacity and small size, among which SD cards and Micro SD cards are prominent representatives. SD cards were jointly developed by Panasonic, Toshiba and SanDisk in August 1999. The SD card is as big as a stamp and weighs only 2 g, but it has high memory capacity, fast data transfer rate, great mobility and good security. By processing SD card information through a single-chip microcomputer, the information embedded industry can be developed towards a smaller size. Considering the stability and reading speed, the 16-bit single-chip microcomputer MC9S12XSl28MAA of Freescale Company was used in the study. In order to further meet the real-time debugging and application needs of embedded research, the reading of SD card and the reading and writing of FATl6 file system are transplanted to this single-chip microcomputer, so that the development and application have better scalability. This paper transplants the reading of FATl6 file system to the HCSl2X single-chip microcomputer for the first time, and reads and writes SD card through the SPI module of the HCSl2X single-chip microcomputer, and achieves good results.

1 Research platform and design concept

1.1 Platform Introduction

①MCS9S12XSl28MAA: A member of the HCSl2X family of 16-bit microcontrollers from Freescale. Compared with other HCSl2X microcontrollers, it removes the XGATE coprocessor, which greatly reduces the cost. This microcontroller has many embedded resources, including 128KB Flash, 4KB EEPROM, 16KBROM and multiple communication interfaces.

②Micro SD card: Designed with SD architecture, it is almost the size of a fingernail. It was jointly developed by Motorola and SanDisk and is an ultra-small card (11 mm×15 mm×1 ram), about 1/4 of the size of an SD card. It supports three transmission modes: SPI mode (independent serial input and serial output), 1-bit SD mode (independent command and data channels, unique
transmission format), and 4-bit SD mode (using additional pins and some re-set pins to support 4-bit wide parallel transmission).

③CodeWarrior: A programming environment developed by Freescale. CodeWarrior Special 5.0 For S12(X) used in this article is specially developed for HCSl2X microcontrollers. It can perform multiple functions such as program editing, compiling, linking and online debugging, and supports embedding assembly language in C language.

④Transplantation conditions: For the SD card reading and writing in this article, the user's microcontroller is recommended to use the HCSl2X series. The HCSl2 series can also be used, but the bus overclocking will be unstable, thus affecting the SD card reading and writing speed and stability.

1.2 Design Concept

Figure 1 shows the hardware and software architecture of the SD card FAT file system used in this article for parsing through MC9S12XS128MAA. The compiling and linking software uses CodeWarrior 5.0, and the hardware uses MC9S12XS128MAA microcontroller and Kingston's Micro SD card. The code consists of four parts: the user application part (written and controlled by the user, this article uses the MC9S12XS128MAA SCI serial port module for information debugging), the FAT file system reading and parsing part, the hardware control part (connected to the SD card through the microcontroller SPI module), and the microcontroller CPU initialization part. Among them, the hardware control part of the SPI module connecting to the SD card and the FAT file system reading and parsing part are the focus of this article.

a.JPG

Among them, Sd_SPI.h is the declaration of some macro definitions, constants and functions about the reading and writing of SD card; Sd_SPI.c includes the code for reading and writing SD card through SPI module; Fat.h is the global variables, macro definitions and function declarations about Fat file system parsing; Fat.c includes the code for Fat file system parsing; SimpleFat.c is the code for simply reading Fat file system information; SimpleFat.h is the declaration of its global variables and functions.

2 Hardware Design

SD card has two operation modes: SD card mode and SPI mode. SD card mode allows transmission via a 4-wire high-speed bus, but since most microcontrollers do not have this interface module, the SPI mode is selected. The HCSl2X series microcontrollers are all equipped with this synchronous serial peripheral interface (Serial Peripheral Interface, SPI). The microcontroller can form a synchronous network with a higher communication rate than SCI through the SPI system, so using the SPI mode can reduce the number of peripherals to a minimum. The disadvantage of the SPI mode relative to the SD card mode is the loss of transmission speed; however, the processing speed of current microprocessors is getting higher and higher, and the use of the SPI mode can mostly meet engineering needs.

The full-duplex 8-bit SPI module of the HCSl2X microcontroller has 4 pins, namely the master input slave output pin MISO, the master input slave output pin MOSI, the serial clock pin SCK, and the slave chip select pin SS. When the CS signal line is low, the host starts all bus transmissions. The data is synchronously input from the MOSI pin of the microcontroller to the DA pin of the Micro SD card, and the return data from the Micro SD card is synchronously input to the MISO pin of the microcontroller through the DO line. The data is synchronously input and output on the rising edge of the CLK signal.

3 Software Design

3.1 HCS12X bus clock overclocking

The default bus clock of MC9S12XSl28MAA is related to the external crystal oscillator, but the microcontroller bus can be overclocked by configuring the PLL phase-locked loop, thereby speeding up the SD card reading rate. In the experiment, the microcontroller bus frequency can be overclocked to 80MHz through the following code:

c.JPG

3.2 HCS12XSP1 module initialization

The MC9S12XS128MAA microcontroller contains two serial peripheral interfaces SPI, which can easily realize data transmission on the Micro SD card interface. In order to configure the clock and data length, it is necessary to set the SPI control register (SPCR1 and SPICR2), SPI baud rate register SPIBR and SPI data register SPIDR: enable the SPI module, set the MSTR position in SPICR1 to 1 to make the microcontroller work in the master mode, generate a serial clock to synchronize the shift registers of the master and slave, configure the SPI clock polarity bit and SPI clock phase control bit, enable the slave output selection; initialize the SPI baud rate register.

3.3 SD card initialization

The initial data transmission of the SD card needs to work at a frequency lower than 400 kb/s, so the SPI baud rate register is configured to work in low-speed mode. The chip select signal should be delayed for at least 74 clock cycles. The SD card uses the SD bus transmission protocol by default. The host needs to issue the command CMDO (CMD_GO_IDLE_STATE) to make the SD card work in SPI transmission mode. When the microcontroller returns 0x 01, it means that it has entered the IDLE state. At this time, CMD55+ACMD41 should be sent cyclically to confirm whether it is an SD card. If the response times out, CMDl (CMD_SEND_OP_COND) should be sent to confirm whether it is an MMC card. It has been found through experiments that Kingston's Micro SD card can be activated using CMD55+ACMD41 or CMDl. After activating the SD card's SPI mode, the SD card enters the ready state. At this time, send CMDl6 (CMD_SET_BLOCKLEN) to set the read and write block size of the SD card, and then reconfigure the SPI baud rate register SPIBR to make the microcontroller SPI work at a high-speed frequency. After a delay of 8 clock cycles, it returns to complete the SD card initialization. Figure 2 shows the SD card SPI high-speed mode initialization process.

b.JPG

3.4 Reading and writing single block data

To read a single block of data from the SD card, the MCU first sends the CMDl7 (CMD_READ_SINGLE_BLOCK) command, with the SD card specified data block start address as a parameter. If the read is successful, the SD card will return an R1 command as a response. Then send a start data command, followed by a single block of byte data and receive data in the SPI data register SPIDR, and finally a 2-byte CRC check.

d.jpg
The writing and reading of a single block of data from an SD card are similar. The MCU sends the CMD24 (CMD_WRITE_SINGLE_BLOCK) command with the SD card specified data block start address as a parameter. If the read is successful, the SD card will return an R1 command as a response. Then send a start data command, followed by a single block of bytes of data to be written, and finally a 2-byte CRC check.
3.5 FAT file system information reading

In order to facilitate the management of SD card file data and better compatibility with PC, and considering the capacity limitation of SD card itself, FATl6 file system is selected to manage SD card information.

In order to facilitate management and scalability development, the SD card is partitioned. The simulated hard disk mode creates the MBR area (master boot sector) and DBR area (operating system boot record area), and realizes the reading and writing of the partitioned SD card FAT file system while being backward compatible.

SD card data can be divided into 5 parts: MBR area, DBR area, FAT area, DIR area and DATA area. MBR area is the master boot area, located on the first single block of the entire SD card. In the total 512-byte master boot sector, MBR only occupies 446 bytes, the other 64 bytes are DPT (Disk Partition Table, partition table), and the last 2 bytes "55 AA" are the end mark of the partition. This constitutes the master boot sector of the SD card as a whole. DBR is the operating system boot record area, which is the first sector that the operating system can directly access. It includes a boot program and a partition parameter record table called BPB (Bios Parameter Block). The BPB parameter block records important parameters such as the starting sector, ending sector, file storage format, hard disk media descriptor, root directory size, FAT, number, and allocation unit size of this partition.

The partition of FAT file system consists of the following parts: reserved area, which stores important parameters and boot program of FAT file system; FAT table, which records cluster usage; root directory area, which records root directory information.

In this paper, the single-chip microcomputer uses the DPT partition table information on the MBR area to read and write the FAT system, which is used to find the FAT partition. Then, the root directory is found through the BPB partition parameter record table information on the DBR area of ​​the FAT partition, the root directory information is read, and the file management is realized through the file cluster information in the FAT table.

In order to facilitate the transplantation and optimization of the code, the read and write sector function pointer is pointed to the read and write function of the Micro SD card when the FAT is initialized, and two structures are used to store the MBR and DBR information of the SD card. However, in view of the memory capacity of the microcontroller itself, a SimpleFat.c program file is established to store only a few address constants required by the program: StartMbrAddress (MBR start address), StartDbrAddress (DBR start address), StartFatlAddress (FATl table start address) and SeePerClu (number of cluster sectors), which greatly reduces the memory overhead of the microcontroller.

e.jpg

3.6 Application layer function interface

The FAT file system has designed the following primary program interfaces for the application layer: Get FileInfo (UINT8*F Info, FileInfo*TempFileInfo) (get file information), OutPut _RootFileinfo (void) (output root directory file information), DirOr (UINT8 FileAttrib) (determine directory), Get Next Cluster (UINT16 TempCluster) (get next file cluster information), OutPutFileCluster (UINT16 TempStart Cluster) (output file cluster address), OutPutFile (UINT16 Temp StartCluster) (output file content), ShowClusterContent (UINT16 TempCluster) (output cluster content). Through these primary program interfaces, functions such as OpenDir (UINT16 TempStartCluster) (directory opening), FileDelete (file deletion), FileDataRead (file data reading), and FileCreate (UINT16 TempStartCluster, UINT32TempFileLength) (file creation) are implemented.

3.6.1 Directory reading and file information acquisition

The specific files and directory entries of the FAT file system are searched by reading the ROOT directory, so the FAT file layout is arranged in a tree structure. For FAT, directory entries and file entries in the same directory are both 32-byte attribute items. In the study, a data structure Filelnfo is used to store file information, and if(Temp_F_Info[0x0b]&0x l0) is used to distinguish between files and directories.

In the FAT file system, files are stored in the SD card in the form of clusters. The clusters are not arranged continuously. If a file is larger than a cluster, the FAT table must be used to find the location of all the clusters of the file to find the entire file. A directory generally only occupies the size of one cluster, which is equivalent to a small file smaller than one cluster in the FAT table, and the value is displayed as FF.

The directory is stored in the parent directory in the form of a file. The file information in the directory records the starting cluster of the file and the size of the file. Knowing the starting cluster of the file, the location of the next cluster of the file can be easily found through the information in the FAT table, and the end position of the file can be determined by the size of the file.

3.6.2 Reading and Writing Files

In the FAT file system, to read a file, you only need to know the starting cluster and size of the file to easily get the information of the entire file. The reading steps are: get the root directory information, find the cluster position of the next directory through the root directory information, recursively find the directory where the file is located through the next directory information, read the file information attributes, get the starting cluster position and file size of the file, recursively find all the cluster addresses of the file through the FAT table, and finally end with FF; determine the end position of the file according to the file size, and finally output the entire file.

The creation and writing of files is to search for unused empty clusters (value 00) through the FAT table, and after filling up 1 cluster, search for the next unused empty cluster, and update the FAT1 table and FAT2 table at the same time. Then add the file information to the directory information where the file is created, and finally realize the creation of the file.

3.6.3 Deleting files

In the FAT file system, deleting a file does not require clearing the entire file information. It only needs to clear the file cluster information in the FAT table and the file information in the directory, avoiding frequent reading and writing of the SD card and saving time.

Conclusion

This design applies the storage method of SD card to the single-chip microcomputer system, simplifies the storage design of complex file data, reduces the size of the system, improves the reliability of the system, and makes the single-chip microcomputer read and access files easily. The FAT reduction implements an embedded file system, improves the storage capacity of the system, and also enhances the communication capability between the single-chip microcomputer and the PC level, simplifying the tedious debugging. The serial peripheral interface SPI of the Freescale 16-bit single-chip microcomputer MC9S12XSl28MAA is used to access the SD card, which speeds up the design progress of the entire system. Practice has proved that the speed and stability of reading and writing SD card file information in this design meet the debugging requirements. This design can be directly applied to other storage media such as MMC cards and Micro SD cards by simply modifying the underlying driver.

Reference address:Design of SD card FAT file system reading and writing based on HCS12X microcontroller

Previous article:Design and Implementation of SPARC V8 Embedded Microprocessor Development Environment
Next article:Multi-task mechanism and its application based on 51 single chip microcomputer

Recommended ReadingLatest update time:2024-11-16 19:38

Mouser Electronics signs global distribution agreement with Menlo Micro to stock its Ideal Switch products
Mouser Electronics signs global distribution agreement with Menlo Micro to stock its Ideal Switch products November 24, 2022 – Mouser Electronics™, a renowned New Product Introduction (NPI) distributor focused on driving innovation in the industry, announced a global distribution agreement with Menlo Micro. Menlo Mi
[Internet of Things]
Mouser Electronics signs global distribution agreement with Menlo Micro to stock its Ideal Switch products
2020 Global Mini & Micro-LED Display Leaders Summit will bring you the latest market trends
  There is a solution for mass transfer, may it be mass-produced in 2022?   Due to the large number of transferred pixel particles (a 5-inch mobile phone screen with 500 PPI requires 8 million pixel particles) and extremely small size (requiring micron-level installation accuracy), this thin film transfer technolo
[Internet of Things]
2020 Global Mini & Micro-LED Display Leaders Summit will bring you the latest market trends
Latest Microcontroller Articles
  • Download from the Internet--ARM Getting Started Notes
    A brief introduction: From today on, the ARM notebook of the rookie is open, and it can be regarded as a place to store these notes. Why publish it? Maybe you are interested in it. In fact, the reason for these notes is ...
  • Learn ARM development(22)
    Turning off and on interrupts Interrupts are an efficient dialogue mechanism, but sometimes you don't want to interrupt the program while it is running. For example, when you are printing something, the program suddenly interrupts and another ...
  • Learn ARM development(21)
    First, declare the task pointer, because it will be used later. Task pointer volatile TASK_TCB* volatile g_pCurrentTask = NULL;volatile TASK_TCB* vol ...
  • Learn ARM development(20)
    With the previous Tick interrupt, the basic task switching conditions are ready. However, this "easterly" is also difficult to understand. Only through continuous practice can we understand it. ...
  • Learn ARM development(19)
    After many days of hard work, I finally got the interrupt working. But in order to allow RTOS to use timer interrupts, what kind of interrupts can be implemented in S3C44B0? There are two methods in S3C44B0. ...
  • Learn ARM development(14)
  • Learn ARM development(15)
  • Learn ARM development(16)
  • Learn ARM development(17)
Change More Related Popular Components

EEWorld
subscription
account

EEWorld
service
account

Automotive
development
circle

About Us Customer Service Contact Information Datasheet Sitemap LatestNews


Room 1530, 15th Floor, Building B, No.18 Zhongguancun Street, Haidian District, Beijing, Postal Code: 100190 China Telephone: 008610 8235 0740

Copyright © 2005-2024 EEWORLD.com.cn, Inc. All rights reserved 京ICP证060456号 京ICP备10001474号-1 电信业务审批[2006]字第258号函 京公网安备 11010802033920号