As a project of SD cards and CCS C compiler, this topic shows how to use the CCS C MMC/SD card driver and FAT library (not the original ones) with PIC18F4550 microcontroller in order to read and write files and folders from and to SD card formatted with FAT32 file system.
CCS C MMC/SD card driver and FAT library download links are in the topic below, the names of the two files (with the extension) respectively are: mmcsd_m.c and fat_m.c. After downloading just add the two files to the project folder:
SD Card driver and FAT Library for CCS C compiler
This topic shows 2 circuit schematics that tested in hardware, also Proteus simulation is provided with small testing video.
This project shows how to create folders and files, and how to write to text file and read from it again.
Hardware Required:
This is a list of the basic components required for this project (all components are shown in the circuit diagrams)
- PIC18F4550 microcontroller —> datasheet
- FAT32 formatted SD card (MMC, SD, SDHC, microSD ….)
- 8MHz crystal oscillator
- 2 x 22pF ceramic capacitors
- Breadboard
- 5V source
- Jumper wires
- PIC MCU programmer (PICkit 3, PICkit 4 …)
To connect the microcontroller with the laptop (PC) we need (one of the following):
—> USB to serial UART converter such as FTDI232RL module, or
—> an Arduino UNO board (connect reset pin to GND, Arduino GND to PIC GND, TX to TX and RX to RX), here the PIC18F4550 can be supplied from the Arduino board, or
—> USB-to-RS232 converter (if the PC doesn’t have a RS232 com port), MAX232 chip, RS232 female connector and four 10 uF capacitors.
The easiest way is to use the FTDI232RL module, using Arduino UNO is also easy.
Interfacing PIC18F4550 with SD card circuit:
The circuit schematic diagrams below can be used for this project. But it is recommended to add a voltage level translator to MISO line in order to step up the 3.3V which comes from the SD card into 5V which goes to SDI pin (#33) of the PIC18F4550 microcontroller, here we can use the integrated circuit 74HCT125 from Texas Instruments.
In the first circuit I used micro SD card module, this module is supplied with 5V, it contains the AMS1117-3V3 voltage regulator which is used to supply the SD card with 3.3V. Also this module contains an IC which is 74LVC125A and it is used as level translator (from 5V to 3.3V).
The 2nd working circuit is shown below. In this circuit I used 3 voltage divider for SS (RD3), MOSI (RC7) and SCK (RB1) lines. Each voltage divider consists of two resistors (2.2k and 3.3k), the voltage divider here steps down the 5V into 3V which is enough for SD card data lines. the MISO is connected directly from the MCU to the SD card.
Note that all grounded terminals are connected together.
In both circuits the microcontroller runs with an external crystal oscillator of 8MHz and MCLR pin is configured as a digital input pin (in the software). The SD card is connected to hardware SPI module pins (SCK, MOSI and MISO) and SS pin is connected to RD3.
To connect the microcontroller to the laptop we need a USB to serial UART convert module such as the FT232RL module.
It also can be implemented using MAX232 IC, four 10 uF capacitors and USB to RS232 converter (if the PC doesn’t have COM port).
An example of the FT232RL module is shown below:
Read and write files from and to SD card with PIC18F4550 CCS C code:
The C code below is for CCS C compiler, it was tested with compiler version 5.051 and 5.076.
As mentioned above, to be able to compile the C code below we need MMC/SD driver and FAT library (mmcsd_m.c and fat_m.c), they can be downloaded from the above link.
The compilation of the project C code may give some warnings, just ignore them!
With the 8MHz and PLL2 the microcontroller becomes working at 48MHZ (12 MIPS) which is the highest speed of the PIC18F4550 and its hardware SPI module.
The hardware SPI and hardware UART modules share the same pin (RC7), therefore I used software UART on pins RC0 and RC1 for TXD and RXD respectively.
Used functions:
#use rs232(baud=9600, xmit=PIN_C0, rcv=PIN_C1): initializes UART protocol.
fat_init(): initializes the media card (MMC, SD …) as well as the FAT library, returns 0 if OK, non-zero if there was an error.
mk_dir: creates a new directory (folder), returns 0 if OK, non-zero if there was an error.
mk_file: creates a new file, returns 0 if OK, non-zero if there was an error.
fatopen: opens a file, returns 0 if OK, non-zero if there was an error.
fatputs: puts a string into the opened file, returns 0 if OK, non-zero if there was an error.
fatclose: closes the opened file, after writing to the file we must call this function, returns 0 if OK, non-zero if there was an error.
fatprintf: printf ‘ s the content of the opened file.
Full CCS C code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 | // Read and write files to and from SD card using PIC18F4550 microcontroller // C code for CCS C compiler // https://simple-circuit.com/ // SD card module connections #define MMCSD_SPI_HW // Use hardware SPI module #define MMCSD_PIN_SELECT PIN_D3 // End SD card module connections #include <18F4550.h> #device PASS_STRINGS = IN_RAM #fuses NOMCLR HSPLL PLL2 CPUDIV1 #use delay(clock = 48MHz) #use rs232(baud=9600, xmit=PIN_C0, rcv=PIN_C1) // Initialize software UART #use fast_io(D) // Include MMC/SD card driver source file #include <mmcsd_m.c> // Include FAT library source file #include <fat_m.c> void main(void) { int8 i; FILE myfile; printf("\r\n\nInitialize FAT library ... "); delay_ms(2000); // Initializing the FAT library as well as the SD card ---> returns 0 if OK i = fat_init(); if(i != 0) printf("Error initializing FAT library!"); else { printf("FAT Library initialized"); delay_ms(2000); // Display SD card type ---> MMC, SDSC or SDHC printf("\r\n\r\nCard Type: "); switch(g_card_type) { case MMC: printf("MMC"); break; case SDSC: printf("SDSC"); break; case SDHC: printf("SDHC"); } delay_ms(2000); // Create folder 'Test Dir' printf("\r\n\r\nCreate 'Test Dir' folder ... "); if(mk_dir("/Test Dir/") == 0) printf("OK"); else printf("error creating folder"); delay_ms(2000); // Create a text file 'log.txt' printf("\r\n\r\nCreate 'log.txt' file ... "); if(mk_file("/log.txt") == 0) printf("OK"); else printf("error creating file"); delay_ms(2000); // Open the last created file 'log.txt' with write permission ('w') printf("\r\nOpen 'log.txt' file ... "); if(fatopen("/log.txt", "w", &myfile) != 0) printf("error opening file"); else { printf("OK"); delay_ms(2000); // Write some thing to the text file printf("\r\nWriting to the text file 'log.txt' ... "); if(fatputs("Hello,\r\nThis is a text file created using PIC18F4550 microcontroller and CCS C compiler\r\nHave a nice day ...", &myfile) == 0) printf("OK"); else printf("writing error"); delay_ms(2000); // Now close the file printf("\r\nClosing the file 'log.txt' ... "); if(fatclose(&myfile) == 0) printf("OK"); else printf("closing error"); } delay_ms(2000); // Reading 'log.txt' file printf("\r\n\r\nReading 'log.txt' file:"); delay_ms(2000); // Open 'log.txt' file with read permission ('r') printf("\r\nOpen 'log.txt' file ... "); if(fatopen("/log.txt", "r", &myfile) != 0) printf("error opening file"); else { printf("OK"); delay_ms(2000); // Print the whole file printf("\r\nPrint 'log.txt' file:\r\n\r"); delay_ms(2000); fatprintf(&myfile); delay_ms(2000); // Now close the file printf("\r\n\r\nClosing the file 'log.txt' ... "); if(fatclose(&myfile) == 0) printf("OK"); else printf("closing error"); } } delay_ms(2000); printf("\r\n\r\n***** END *****"); while(TRUE) ; } // End of code |
I made a video of less than 4 minutes shows how the project should work, this video shows Proteus simulation of the project. Note that the hardware circuit is not similar to the simulation circuit, so don’t make your your real hardware circuit as the one shown in the video, the working real hardware circuits are shown above.
To open, extract and edit the SD card image file use image software’s such as UltraISO, WinImage, PowerISO …..
In this project I tested 2 micro SD cards, the first one is Samsung 8GB SDHC and the second one is Samsung 2GB SDSC, both cards are formatted with FAT32.
The result of my hardware circuit is shown in the image below where the created folder (Test Dir) and text file (log.txt) with its content are shown:
SD Card file is FAT32 image file, it can be downloaded from the link below:
SD Card FAT32 image
Proteus simulation file download link:
PIC18F4550 + SD card
Discover more from Simple Circuit
Subscribe to get the latest posts sent to your email.
Elinize sağlık çok güzel olmuş
can you help me please? ” Pointer types do not match ” error , what can i do? error in both application and simulation.
…
>>> Warning 240 “C:\Users\ELMAN Teknoloji\Desktop\sd\fat_m.c” Line 3298(71,72): Pointer types do not match
>>> Warning 240 “C:\Users\ELMAN Teknoloji\Desktop\sd\fat_m.c” Line 3299(57,60): Pointer types do not match
>>> Warning 240 “C:\Users\ELMAN Teknoloji\Desktop\sd\fat_m.c” Line 3307(57,60): Pointer types do not match
Memory usage: ROM=64% RAM=35% – 56%
0 Errors, 32 Warnings.
Hola!!
gracias por la información!!!
Una pregunta: Realicé el mismo circuito en físico y tuve la siguiente respuesta:
Initialize FAT library … FAT Library initialized
Card Type: SDSC
Create ‘log.txt’ file … OK
Open ‘log.txt’ file … OK
Writing to the text file ‘log.txt’ … writing error
Closing the file ‘log.txt’ … closing error
Reading ‘log.txt’ file:
Open ‘log.txt’ file … error opening file
***** END *****
Intenté solucionar el problema formateando la memoria con el programa que sugeriste pero no funcionó. Podrías darme tu opinión de este error??
Estoy usando un PIC18F4550 y una memoria microSD SanDisk de 2Gb (con adaptador), intenté usar una memoria SDHC 10 de 16Gb SanDisk pero en el caso de esta memoria tengo error desde la inicialización de la librería FAT.
No se porque sucede esto si en teoría las librerías soporta tarjetas del tipo SDHC
saludos!!
Hello friend,
The Lib and have some problem with DSpic 16bit. I tried with Dspic 30F6015 and 33FJ32GP202.
Both of them can Initialized but can’t make the .txt file.
Hope you checking its and help to clear the problem.
Many thanks.
below is the MS i’m testing.
FAT initialization … Good
Card Type: SDSC
Making file ‘/log.txt’: Error creating file
Interesante su proyecto. Su trabajo esta muy bien detallado. Probé el código con el mismo hardware que ha utilizado, funcionando correcto en Proteus, pero en hardware no logra crear el archivos en la sd. La sd utilizada es una Sandisk de 8gb. ¿Como podria solucionar este inconveniente?
Be careful, some unoriginal SD cards do not support SPI mode, try with different one.
Before using the SD card, format it (FAT32) using Windows or use this tool:
https://drive.google.com/open?id=1549xFkgNvY5GPFh2qVKBwv4tMuBbJC3L
Also check your circuit connection.
Hola, buena noche. Estoy implementando su Código con las librerias que acabo de descargar, y me da un error al utilizar la function mk_dir y mk_file. Basicamente el error es el siguiente: Attempt to create a pointer to a constant.
Espero pueda ayudarme con lo siguiente.
Can you tell me which compiler version are you using?
Hello!
I have read your code and asked if it is necessary to work with 48 Mhz. Can I work with another frequency?
Yes, you can!
The higher MCU frequency, the higher SPI transfer rate.
What changes should I do in the above code so that it will work for device PIC24FJ128GA006? How is SPI configured in above code?
Actually it was tested only with PIC18, I’ve no such example for PIC24 right now.
Hello friend, I am testing your code, it works, it detects the FAT but when creating files or folders the pic is frozen, and you can never create files or folders on the SD card.
What type of SD card do you use? because I use a SanDisk of 512Mb and it does not detect the FAT, but if I put another 2Gb in this memory the PIC detects the FAT but does not create the files or the folders.
Regards
hello sir, I want to read my sd card. there is a file and I can open it but I want to get some integers and some texts(words) not all text. how can I get it? thank u
Open fat_m.c file with a text editor like Notepad and read the commented header, you will find all user functions.
hello again, now i have a problem with the function fat_init, i made the circuit also i formated the sd card in fat32 format, the frequency its in 48Mhz, but now i want to know what kind of error retruns the function, i tried to printf the variable “i”, but it returns me diferent values and i dont know how to interpret its, what do you thing its happening?
why do you use a 48MHz instead 4Mhz?
i need to acoplate to a lsd and a matricial key and this components works on the 4MHz frecuency, what sould i do?
I used 48MHz for faster read/write data from/to the SD card. The 48MHz is the highest frequency which the PIC18F4550 MCU can work. In this example a 8MHz crystal oscillator is connected to the MCU and with PLL (PLL2) enabled the MCU frequency becomes 48MHz.
Hello,
I’m using the exactly same hardware, but i have error to initialize fat library, i applied the fix for MBR support on mmsd_m but i’m still getting errors at fat initialization.
Thanks in advance.
right.
so I’ll use the 18f4550.
Would you help me to implement spi communication?
Hello.
I need to implement this spi communication.
Between a PIC 16f877A and the SD CARD.
In the SD CARD I want to save TAGs to compare with the TAGs read by an RFID.
If this TAG exists in the SD CARD access will be released, on the contrary no.
And if it were possible I’d like to implement a way to write that tag to the SD CARD.
if it is possible, how could you help me?
To be able to write data to SD card the microcontroller must have more than 512 byte of RAM space. The PIC16F877A has only 368 byte which means you can not use it. You’ve to use a device with RAM > 512 bytes.