Read and write files from and to SD card with PIC18F4550 – CCS C

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).

PIC18F4550 SD card read and write files with micro sd card module

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.

PIC18F4550 SD card read and write files

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:

FTDI FT232RL USB to serial UART module

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:

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 files created by PIC18F4550 microcontroller

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

22 thoughts on “Read and write files from and to SD card with PIC18F4550 – CCS C”

  1. 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.

  2. 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!!

  3. 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

  4. Mariano Turchetti

    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?

  5. 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.

  6. Gustavo Martinez

    Hello!

    I have read your code and asked if it is necessary to work with 48 Mhz. Can I work with another frequency?

  7. What changes should I do in the above code so that it will work for device PIC24FJ128GA006? How is SPI configured in above code?

  8. 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

  9. 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

    1. Simple Projects

      Open fat_m.c file with a text editor like Notepad and read the commented header, you will find all user functions.

  10. 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?

  11. 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?

    1. Simple Projects

      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.

  12. 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.

  13. 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?

    1. Simple Projects

      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.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top