The CCS C compiler has a good example of using PIC microcontroller with SD card in FAT file format, this file is located in the examples folder (C:\Program Files\CCS\Examples), its full name is ex_fat.c (fat_ex_shell.c ). This topic shows how this example works, circuit diagram and Proteus ISIS simulation.
As written in the head of the file ex_fat.c:
This is a neat little shell utility that resembles a DOS or UNIX type shell in order to manipulate files on the FAT file system. This is mostly for demonstration purposes on how to use some of the basic functionality of the FAT library.
In this project I’m going to use MMC/SD card and FAT library provided in the page below, without the two files we’ll not be able to compile project source file (C code), the name 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 or CCS C drivers folder:
SD Card driver and FAT Library for CCS C compiler
Related Project:
The following project may have some help!
Read and write files from and to SD card with PIC18F4550 – CCS C
Hardware Required:
- PIC18F4550 microcontroller —> datasheet
- FAT32 formatted SD card (MMC, SD, SDHC, micro SD ….)
- microSD card module
- USB-to-serial UART module (FT232RL, Arduino UNO ….)
- 8MHz crystal oscillator
- 2 x 22pF ceramic capacitors
- Breadboard
- 5V source
- Jumper wires
- PIC MCU programmer (PICkit 3, PICkit 4 …)
The Circuit:
Example circuit schematic is shown below.
All grounded terminals are connected.
In this project the microcontroller runs with an external crystal oscillator of 8MHz and MCLR pin is configured as a digital input pin (in the software).
The microSD card is placed in the module (adapter).
The USB-to-serial UART module such as FT232RL is used to connect the microcontroller with the laptop (PC), in order to send and receive data between the microcontroller and the serial software (CCS IDE serial monitor, Arduino IDE serial monitor, hyper terminal …).
As a hint, instead of the microSD card module we can use AMS1117-3V3 to supply the SD card and three voltage dividers for SS (CS), SCK and MOSI lines; each voltage divider consists of two resistors: 2.2k ohm and 3.3k ohm. MISO line is directly connected between the MCU and the SD card. Related project link above shows a similar circuit diagram.
CCS C code:
The following C code was tested with version 5.051, it gives some warnings which can be ignored.
I made some modifications to the original to work with the PIC18F4550 microcontroller and the circuit diagram shown above.
With the 8MHz crystal oscillator and by enabling PLL2 the microcontroller speed becomes 48MHz which is the highest speed of the PIC18F4550 microcontroller.
As a reminder, to be able to compile the C code below without errors, add the files mmcsd_m.c and fat_m.c to project folder, their download links are in the page below:
SD Card driver and FAT Library for CCS C compiler
Rest of code is described through comments.
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 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 | // CCS C ex_fat.c example with PIC18F4550 microcontroller // C code for CCS C compiler // SD card module connections #define MMCSD_PIN_SELECT PIN_D0 #define MMCSD_PIN_SCK PIN_D1 #define MMCSD_PIN_MOSI PIN_D2 #define MMCSD_PIN_MISO 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 <stdlib.h> // for atoi32 // Include MMC/SD card driver source file #include <mmcsd_m.c> // Include FAT library source file #include <fat_m.c> ////////////////////// /// /// /// Useful Defines /// /// /// ////////////////////// #define COMMAND_SIZE 10 #define NUM_COMMANDS 11 //////////////////////// /// /// /// Global Variables /// /// /// //////////////////////// char g_CWD[200] = "/"; //current working directory char commands[NUM_COMMANDS][COMMAND_SIZE]= { "del", //option1=filename. delete file. "make", //option1=filename. create an empty file, give error if file already exists "append", //option1=filename, option2=string. append string to end of file "cd", //option1=new cwd. change working directory. / is root. "dir", //show files in directory "cat", //option1=filename. display full contents in ascii "tail", //option1=filename. display the last 20 lines of file. "mkdir", //option1=dir. create directory. see 'cd' for rules on dir "rmdir", //option1=dir. remove directory. see 'cd' for rules on dir. "format", // option1=media size in bytes. formats the media. "help" // help! }; //////////////////////////////// /// /// /// Function Implementations /// /// /// //////////////////////////////// /* Summary: Finds a command from the global list of commands. Param: A pointer to the command string. Returns: The command number if the command is found in the command list. 0xFF if the command isn't found */ int FindCommand(char *cmd) { char buf[COMMAND_SIZE]; int i; for (i=0; i<NUM_COMMANDS; i++) { strcpy(buf, &commands[i][0]); if (stricmp(buf, cmd)==0) return(i); } return(0xFF); } /* Summary: Displays the current working directory. Param: None. Returns: None. */ void DisplayPrompt(void) { printf("\r\n\n%s> ", g_CWD); } /* Summary: Deletes a file. Param: The full path of the file to delete. Returns: None. */ void DeleteFile(char *fileName) { printf("\r\nDeleting '%s': ", fileName); if(rm_file(fileName) != GOODEC) { printf("Error deleting file"); return; } printf("OK"); } /* Summary: Creates a file. Param: The full path of the file to create. Returns: None. Example Usage: \> make "Log.txt" */ void MakeFile(char *fileName) { printf("\r\nMaking file '%s': ", fileName); if(mk_file(fileName) != GOODEC) { printf("Error creating file"); return; } printf("OK"); } /* Summary: Append a string to a file. Param: The full path of the file to append to. Param: A pointer to a string to append to the file. Returns: None. Example Usage: \> append "Log.txt" "This will be appended to the end of Log.txt" Note: A "\r\n" will be appended after the appendString. */ void AppendFile(char *fileName, char *appendString) { FILE stream; printf("\r\nAppending '%s' to '%s': ", appendString, fileName); if(fatopen(fileName, "a", &stream) != GOODEC) { printf("Error opening file"); return; } fatputs(appendString, &stream); fatputs("\r\n", &stream); if(fatclose(&stream) != GOODEC) { printf("Error closing file"); return; } printf("OK"); } /* Summary: Change the working directory. Param: The new working directory to switch to. Returns: None. Example Usage: \> cd ftp/ -> /ftp/ \ftp\> cd files/ -> /ftp/files/ \ftp\files> cd.. -> /ftp/ \ftp\> cd .. -> / \> cd /ftp/files/ -> /ftp/files/ Note: Changing the directory to .. will go up a directory. */ void ChangeDirectory(char *newCWD) { FILE stream; //append a / to the end of the filename if it doesn't exist //making an assumption here that newCWD can hold 1 more character if (newCWD[strlen(newCWD)-1] != '/') strcat(newCWD, "/"); if((strstr(newCWD, "../") != 0) && (strcmp(g_CWD, "/") != 0)) { g_CWD[strlen(g_CWD) - 1] = '\0'; g_CWD[strrchr(g_CWD, '/') - g_CWD + 1] = '\0'; } else { if(fatopen(newCWD, "r", &stream) != GOODEC) { printf("\r\nError changing directory"); return; } strcpy(g_CWD, newCWD); } } /* Summary: Display the contents of the working directory. Param: The full path of the directory contents to display. Returns: None. Example Usage: /> dir */ void DisplayDirectory(char *dir) { disp_folder_contents(dir); } /* Summary: Create a directory. Param: The full path of the directory to create. Returns: None. Example Usage: /> mkdir "Backlog" */ void MakeDirectory(char *dir) { //append a / to the end of the filename if it doesn't exist //making an assumption here that newCWD can hold 1 more character if (dir[strlen(dir)-1] != '/') strcat(dir, "/"); printf("\r\nMaking directory '%s': ", dir); if(mk_dir(dir) != GOODEC) { printf("Error creating directory"); return; } printf("OK"); } /* Summary: Remove a directory. Param: The full path of the directory to remove. Returns: None. Example Usage: /> rmdir "Backlog" Note: The directory needs to be empty in order for this command to work. */ void RemoveDirectory(char *dir) { printf("\r\nRemoving directory '%s': ", dir); //append a / to the end of the filename if it doesn't exist //making an assumption here that newCWD can hold 1 more character if (dir[strlen(dir)-1] != '/') strcat(dir, "/"); if(rm_dir(dir) != GOODEC) { printf("Error removing directory"); return; } printf("OK"); } #define CAT_FROM_START FALSE #define CAT_FROM_END TRUE /* Summary: Prints either all of or the last 80 characters in a file. Param: The full path of the file to print off. Param: If true, this function will print off the last 80 characters in the file. If false, this funciton will print off the entire file. Returns: None. Example Usage: /> cat "Logs.txt" (this will display the entire file) Example Usage: /> tail "Logs.txt" (this will display the last 80 characters in the file) */ void PrintFile(char *fileName, int1 startFromEnd) { FILE stream; if(fatopen(fileName, "r", &stream) != GOODEC) { printf("\r\nError opening file"); return; } printf("\r\n"); if(startFromEnd) fatseek(&stream, 80, SEEK_END); fatprintf(&stream); fatclose(&stream); } /* Summary: Formats the media to a specified size. Param: The size of the media, in kB, in string form. Returns: None. Example Usage: /> format 524288 (format a 512MB card) */ void FormatMedia(char *mediaSize) { int32 size; size = atoi32(mediaSize); printf("\r\nFormatting media (size=%LU): ", size); if(format(size) != GOODEC) { printf("Error formatting media"); return; } printf("OK"); } /* Summary: Shows a help prompt. Param: None. Returns: None. Example Usage: /> help */ void ShowHelp() { printf("\r\nFAT Shell Help"); printf("\r\n del filename --- Deletes the file"); printf("\r\n make filename --- Creates an empty file"); printf("\r\n append filename string --- Appends string to the end of the file"); printf("\r\n cd dir --- Change the working directory"); printf("\r\n dir --- Shows the contents of the directory"); printf("\r\n cat filename --- Displays content of file"); printf("\r\n tail filename --- Displays the last 80 characters of file"); printf("\r\n mkdir dir --- Create a directory"); printf("\r\n rmdir dir --- Deletes the directory"); printf("\r\n format size --- Format card. (Example: 'format 5524288' formats a 512MB card)"); printf("\r\n help\tYou are here"); printf("\r\n\n Put a parameter in quotes if it has spaces"); } char * GetCMD(char *in) { char tokens[]=" \r\n"; return(strtok(in,tokens)); } char * GetOption(char *in) { char tokensSpace[]=" \r\n"; char tokensQuote[]="\"\r\n"; //trim leading spaces while (*in==' ') in++; //if first char is a quote, then end token on a quote. ELSE end token on a space if (*in == '\"') return(strtok(in,tokensQuote)); else return(strtok(in,tokensSpace)); } void main(void) { char buffer[255]; char opt_buffer[255]; char *cmd, *option1, *option2; int i; // pointer to the buffer delay_ms(2000); // initialize the FAT // keep in mind that this will automagically initialize the media printf("\r\n\nFAT initialization ... "); i = fat_init(); if (i == 0) { printf("Good\r\n\n"); // Display SD card type ---> MMC, SDSC or SDHC printf("\r\n\r\nCard Type: "); switch(g_card_type) { case MMC: printf("MMC\r\n\n"); break; case SDSC: printf("SDSC\r\n\n"); break; case SDHC: printf("SDHC\r\n\n"); } } else printf("Error\r\n\n"); // main loop while(TRUE) { i = 0; DisplayPrompt(); do { buffer[i] = getch(); // check for a backspace if(buffer[i] != 8) { printf("%c", buffer[i]); i++; } else if(i > 0) { // delete the last character i--; putc(8); putc(' '); putc(8); } buffer[i] = '\0'; } while(buffer[i - 1] != '\r'); // parse the command and options cmd = GetCMD(buffer); option1 = GetOption(cmd + strlen(cmd) + 1); option2 = GetOption(option1 + strlen(option1) + 1); //if option1 starts with a '/', that means the file in the option includes //the full path to the file. if the file doesn't start with a '/', the //current working directory must be added. if (option1 && (option1[0]=='/')) { //option1 is a full path strcpy(opt_buffer, option1); } else if (option1) { // tack on the current working directory to option1 strcpy(opt_buffer, g_CWD); strcat(opt_buffer, option1); } if (cmd) { switch(FindCommand(cmd)) { case 0: //del DeleteFile(opt_buffer); break; case 1: //make MakeFile(opt_buffer); break; case 2: //append AppendFile(opt_buffer, option2); break; case 3: //change directory ChangeDirectory(opt_buffer); break; case 4: //show directory contents DisplayDirectory(g_CWD); break; case 5: //cat, display file PrintFile(opt_buffer, CAT_FROM_START); break; case 6: //tail, display last 80 charachters PrintFile(opt_buffer, CAT_FROM_END); break; case 7: //mkdir, make a directory MakeDirectory(opt_buffer); break; case 8: //rmdir, make a directory RemoveDirectory(opt_buffer); break; case 9: //format, format the card FormatMedia(option1); break; case 10: //help, display help ShowHelp(); break; default: printf("\r\nUnkown Command '%s'", cmd); break; } } } } // End of code |
The video below shows the simulation of the ex_fat example using Proteus ISIS simulation software, the real hardware circuit also gave me the same result. Note that the simulation circuit connections are not the same as the real hardware circuit connection, real hardware circuit schematic diagram is shown above.
To open the SD card image file use an image software such as UltraISO, WinImage ….
Reference:
CCS C compiler example ex_fat.c
SD Card file is FAT32 image file, it can be downloaded from the link below:
SD Card FAT32 image
Proteus simulation file download link:
EX_FAT with PIC18F4550
Discover more from Simple Circuit
Subscribe to get the latest posts sent to your email.
Hi, it is possible do this with pic18F2550, if so what changes do I must do on this pic?
can you make a file explorer whit that library?