3 * Copyright (c) 2006-2012 by Roland Riegel <feedback@roland-riegel.de>
5 * This file is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License version 2 as
7 * published by the Free Software Foundation.
11 #include <avr/pgmspace.h>
12 #include <avr/sleep.h>
14 #include "fat_config.h"
15 #include "partition.h"
17 #include "sd_raw_config.h"
23 * \mainpage MMC/SD/SDHC card library
25 * This project provides a general purpose library which implements read and write
26 * support for MMC, SD and SDHC memory cards.
29 * - low-level \link sd_raw MMC, SD and SDHC read/write routines \endlink
30 * - \link partition partition table support \endlink
31 * - a simple \link fat FAT16/FAT32 read/write implementation \endlink
33 * \section circuit The circuit
34 * The circuit which was mainly used during development consists of an Atmel AVR
35 * microcontroller with some passive components. It is quite simple and provides
36 * an easy test environment. The circuit which can be downloaded on the
37 * <a href="http://www.roland-riegel.de/sd-reader/">project homepage</a> has been
38 * improved with regard to operation stability.
40 * I used different microcontrollers during development, the ATmega8 with 8kBytes
41 * of flash, and its pin-compatible alternative, the ATmega168 with 16kBytes flash.
42 * The first one is the one I started with, but when I implemented FAT16 write
43 * support, I ran out of flash space and switched to the ATmega168. For FAT32, an
44 * ATmega328 is required.
46 * The circuit board is a self-made and self-soldered board consisting of a single
47 * copper layer and standard DIL components, except of the MMC/SD card connector.
49 * The connector is soldered to the bottom side of the board. It has a simple
50 * eject button which, when a card is inserted, needs some space beyond the connector
51 * itself. As an additional feature the connector has two electrical switches
52 * to detect wether a card is inserted and wether this card is write-protected.
54 * \section pictures Pictures
55 * \image html pic01.jpg "The circuit board used to implement and test this application."
56 * \image html pic02.jpg "The MMC/SD card connector on the soldering side of the circuit board."
58 * \section software The software
59 * The software is written in C (ISO C99). It might not be the smallest or
60 * the fastest one, but I think it is quite flexible. See the project's
61 * <a href="http://www.roland-riegel.de/sd-reader/benchmarks/">benchmark page</a> to get an
62 * idea of the possible data rates.
64 * I implemented an example application providing a simple command prompt which is accessible
65 * via the UART at 9600 Baud. With commands similiar to the Unix shell you can browse different
66 * directories, read and write files, create new ones and delete them again. Not all commands are
67 * available in all software configurations.
68 * - <tt>cat \<file\></tt>\n
69 * Writes a hexdump of \<file\> to the terminal.
70 * - <tt>cd \<directory\></tt>\n
71 * Changes current working directory to \<directory\>.
73 * Shows card manufacturer, status, filesystem capacity and free storage space.
75 * Reinitializes and reopens the memory card.
77 * Shows the content of the current directory.
78 * - <tt>mkdir \<directory\></tt>\n
79 * Creates a directory called \<directory\>.
80 * - <tt>mv \<file\> \<file_new\></tt>\n
81 * Renames \<file\> to \<file_new\>.
82 * - <tt>rm \<file\></tt>\n
85 * Ensures all buffered data is written to the card.
86 * - <tt>touch \<file\></tt>\n
88 * - <tt>write \<file\> \<offset\></tt>\n
89 * Writes text to \<file\>, starting from \<offset\>. The text is read
90 * from the UART, line by line. Finish with an empty line.
94 * The following table shows some typical code sizes in bytes, using the 20090330 release with a
95 * buffered read-write MMC/SD configuration, FAT16 and static memory allocation:
98 * <table border="1" cellpadding="2">
102 * <th>static RAM usage</th>
106 * <td align="right">2410</td>
107 * <td align="right">518</td>
111 * <td align="right">456</td>
112 * <td align="right">17</td>
116 * <td align="right">7928</td>
117 * <td align="right">188</td>
122 * The static RAM is mostly used for buffering memory card access, which
123 * improves performance and reduces implementation complexity.
127 * Please note that the numbers above do not include the C library functions
128 * used, e.g. some string functions. These will raise the numbers somewhat
129 * if they are not already used in other program parts.
133 * When opening a partition, filesystem, file or directory, a little amount
134 * of RAM is used, as listed in the following table. Depending on the library
135 * configuration, the memory is either allocated statically or dynamically.
138 * <table border="1" cellpadding="2">
140 * <th>descriptor</th>
141 * <th>dynamic/static RAM</th>
145 * <td align="right">17</td>
148 * <td>filesystem</td>
149 * <td align="right">26</td>
153 * <td align="right">53</td>
157 * <td align="right">49</td>
163 * \section adaptation Adapting the software to your needs
164 * The only hardware dependent part is the communication layer talking to the
165 * memory card. The other parts like partition table and FAT support are
166 * completely independent, you could use them even for managing Compact Flash
167 * cards or standard ATAPI hard disks.
169 * By changing the MCU* variables in the Makefile, you can use other Atmel
170 * microcontrollers or different clock speeds. You might also want to change
171 * the configuration defines in the files fat_config.h, partition_config.h,
172 * sd_raw_config.h and sd-reader_config.h. For example, you could disable
173 * write support completely if you only need read support.
175 * For further information, visit the project's
176 * <a href="http://www.roland-riegel.de/sd-reader/faq/">FAQ page</a>.
178 * \section bugs Bugs or comments?
179 * If you have comments or found a bug in the software - there might be some
180 * of them - you may contact me per mail at feedback@roland-riegel.de.
182 * \section acknowledgements Acknowledgements
183 * Thanks go to Ulrich Radig, who explained on his homepage how to interface
184 * MMC cards to the Atmel microcontroller (http://www.ulrichradig.de/).
185 * I adapted his work for my circuit.
187 * \section copyright Copyright 2006-2012 by Roland Riegel
188 * This program is free software; you can redistribute it and/or modify it under
189 * the terms of the GNU General Public License version 2 as published by
190 * the Free Software Foundation (http://www.gnu.org/copyleft/gpl.html).
191 * At your option, you can alternatively redistribute and/or modify the following
192 * files under the terms of the GNU Lesser General Public License version 2.1
193 * as published by the Free Software Foundation (http://www.gnu.org/copyleft/lgpl.html):
201 * - partition_config.h
205 * - sd-reader_config.h
208 static uint8_t read_line(char* buffer, uint8_t buffer_length);
209 static uint32_t strtolong(const char* str);
210 static uint8_t find_file_in_dir(struct fat_fs_struct* fs, struct fat_dir_struct* dd, const char* name, struct fat_dir_entry_struct* dir_entry);
211 static struct fat_file_struct* open_file_in_dir(struct fat_fs_struct* fs, struct fat_dir_struct* dd, const char* name);
212 static uint8_t print_disk_info(const struct fat_fs_struct* fs);
216 /* we will just use ordinary idle mode */
217 set_sleep_mode(SLEEP_MODE_IDLE);
224 /* setup sd card slot */
228 uart_puts_p(PSTR("MMC/SD initialization failed\n"));
233 /* open first partition */
234 struct partition_struct* partition = partition_open(sd_raw_read,
235 sd_raw_read_interval,
236 #if SD_RAW_WRITE_SUPPORT
238 sd_raw_write_interval,
248 /* If the partition did not open, assume the storage device
249 * is a "superfloppy", i.e. has no MBR.
251 partition = partition_open(sd_raw_read,
252 sd_raw_read_interval,
253 #if SD_RAW_WRITE_SUPPORT
255 sd_raw_write_interval,
265 uart_puts_p(PSTR("opening partition failed\n"));
271 /* open file system */
272 struct fat_fs_struct* fs = fat_open(partition);
276 uart_puts_p(PSTR("opening filesystem failed\n"));
281 /* open root directory */
282 struct fat_dir_entry_struct directory;
283 fat_get_dir_entry_of_path(fs, "/", &directory);
285 struct fat_dir_struct* dd = fat_open_dir(fs, &directory);
289 uart_puts_p(PSTR("opening root directory failed\n"));
294 /* print some card information as a boot message */
297 /* provide a simple shell */
306 char* command = buffer;
307 if(read_line(command, sizeof(buffer)) < 1)
310 /* execute command */
311 if(strcmp_P(command, PSTR("init")) == 0)
315 else if(strncmp_P(command, PSTR("cd "), 3) == 0)
318 if(command[0] == '\0')
321 /* change directory */
322 struct fat_dir_entry_struct subdir_entry;
323 if(find_file_in_dir(fs, dd, command, &subdir_entry))
325 struct fat_dir_struct* dd_new = fat_open_dir(fs, &subdir_entry);
334 uart_puts_p(PSTR("directory not found: "));
338 else if(strcmp_P(command, PSTR("ls")) == 0)
340 /* print directory listing */
341 struct fat_dir_entry_struct dir_entry;
342 while(fat_read_dir(dd, &dir_entry))
344 uint8_t spaces = sizeof(dir_entry.long_name) - strlen(dir_entry.long_name) + 4;
346 uart_puts(dir_entry.long_name);
347 uart_putc(dir_entry.attributes & FAT_ATTRIB_DIR ? '/' : ' ');
350 uart_putdw_dec(dir_entry.file_size);
354 else if(strncmp_P(command, PSTR("cat "), 4) == 0)
357 if(command[0] == '\0')
360 /* search file in current directory and open it */
361 struct fat_file_struct* fd = open_file_in_dir(fs, dd, command);
364 uart_puts_p(PSTR("error opening "));
370 /* print file contents */
374 while((count = fat_read_file(fd, buffer, sizeof(buffer))) > 0)
376 uart_putdw_hex(offset);
378 for(intptr_t i = 0; i < count; ++i)
381 uart_putc_hex(buffer[i]);
389 else if(strcmp_P(command, PSTR("disk")) == 0)
391 if(!print_disk_info(fs))
392 uart_puts_p(PSTR("error reading disk info\n"));
394 #if FAT_WRITE_SUPPORT
395 else if(strncmp_P(command, PSTR("rm "), 3) == 0)
398 if(command[0] == '\0')
401 struct fat_dir_entry_struct file_entry;
402 if(find_file_in_dir(fs, dd, command, &file_entry))
404 if(fat_delete_file(fs, &file_entry))
408 uart_puts_p(PSTR("error deleting file: "));
412 else if(strncmp_P(command, PSTR("touch "), 6) == 0)
415 if(command[0] == '\0')
418 struct fat_dir_entry_struct file_entry;
419 if(!fat_create_file(dd, command, &file_entry))
421 uart_puts_p(PSTR("error creating file: "));
426 else if(strncmp_P(command, PSTR("mv "), 3) == 0)
429 if(command[0] == '\0')
432 char* target = command;
433 while(*target != ' ' && *target != '\0')
441 struct fat_dir_entry_struct file_entry;
442 if(find_file_in_dir(fs, dd, command, &file_entry))
444 if(fat_move_file(fs, &file_entry, dd, target))
448 uart_puts_p(PSTR("error moving file: "));
452 else if(strncmp_P(command, PSTR("write "), 6) == 0)
455 if(command[0] == '\0')
458 char* offset_value = command;
459 while(*offset_value != ' ' && *offset_value != '\0')
462 if(*offset_value == ' ')
463 *offset_value++ = '\0';
467 /* search file in current directory and open it */
468 struct fat_file_struct* fd = open_file_in_dir(fs, dd, command);
471 uart_puts_p(PSTR("error opening "));
477 int32_t offset = strtolong(offset_value);
478 if(!fat_seek_file(fd, &offset, FAT_SEEK_SET))
480 uart_puts_p(PSTR("error seeking on "));
488 /* read text from the shell and write it to the file */
492 /* give a different prompt */
496 /* read one line of text */
497 data_len = read_line(buffer, sizeof(buffer));
501 /* write text to file */
502 if(fat_write_file(fd, (uint8_t*) buffer, data_len) != data_len)
504 uart_puts_p(PSTR("error writing to file\n"));
511 else if(strncmp_P(command, PSTR("mkdir "), 6) == 0)
514 if(command[0] == '\0')
517 struct fat_dir_entry_struct dir_entry;
518 if(!fat_create_dir(dd, command, &dir_entry))
520 uart_puts_p(PSTR("error creating directory: "));
526 #if SD_RAW_WRITE_BUFFERING
527 else if(strcmp_P(command, PSTR("sync")) == 0)
530 uart_puts_p(PSTR("error syncing disk\n"));
535 uart_puts_p(PSTR("unknown command: "));
541 /* close directory */
544 /* close file system */
547 /* close partition */
548 partition_close(partition);
554 uint8_t read_line(char* buffer, uint8_t buffer_length)
556 memset(buffer, 0, buffer_length);
558 uint8_t read_length = 0;
559 while(read_length < buffer_length - 1)
561 uint8_t c = uart_getc();
563 if(c == 0x08 || c == 0x7f)
569 buffer[read_length] = '\0';
582 buffer[read_length] = '\0';
587 buffer[read_length] = c;
595 uint32_t strtolong(const char* str)
598 while(*str >= '0' && *str <= '9')
599 l = l * 10 + (*str++ - '0');
604 uint8_t find_file_in_dir(struct fat_fs_struct* fs, struct fat_dir_struct* dd, const char* name, struct fat_dir_entry_struct* dir_entry)
606 while(fat_read_dir(dd, dir_entry))
608 if(strcmp(dir_entry->long_name, name) == 0)
618 struct fat_file_struct* open_file_in_dir(struct fat_fs_struct* fs, struct fat_dir_struct* dd, const char* name)
620 struct fat_dir_entry_struct file_entry;
621 if(!find_file_in_dir(fs, dd, name, &file_entry))
624 return fat_open_file(fs, &file_entry);
627 uint8_t print_disk_info(const struct fat_fs_struct* fs)
632 struct sd_raw_info disk_info;
633 if(!sd_raw_get_info(&disk_info))
636 uart_puts_p(PSTR("manuf: 0x")); uart_putc_hex(disk_info.manufacturer); uart_putc('\n');
637 uart_puts_p(PSTR("oem: ")); uart_puts((char*) disk_info.oem); uart_putc('\n');
638 uart_puts_p(PSTR("prod: ")); uart_puts((char*) disk_info.product); uart_putc('\n');
639 uart_puts_p(PSTR("rev: ")); uart_putc_hex(disk_info.revision); uart_putc('\n');
640 uart_puts_p(PSTR("serial: 0x")); uart_putdw_hex(disk_info.serial); uart_putc('\n');
641 uart_puts_p(PSTR("date: ")); uart_putw_dec(disk_info.manufacturing_month); uart_putc('/');
642 uart_putw_dec(disk_info.manufacturing_year); uart_putc('\n');
643 uart_puts_p(PSTR("size: ")); uart_putdw_dec(disk_info.capacity / 1024 / 1024); uart_puts_p(PSTR("MB\n"));
644 uart_puts_p(PSTR("copy: ")); uart_putw_dec(disk_info.flag_copy); uart_putc('\n');
645 uart_puts_p(PSTR("wr.pr.: ")); uart_putw_dec(disk_info.flag_write_protect_temp); uart_putc('/');
646 uart_putw_dec(disk_info.flag_write_protect); uart_putc('\n');
647 uart_puts_p(PSTR("format: ")); uart_putw_dec(disk_info.format); uart_putc('\n');
648 uart_puts_p(PSTR("free: ")); uart_putdw_dec(fat_get_fs_free(fs)); uart_putc('/');
649 uart_putdw_dec(fat_get_fs_size(fs)); uart_putc('\n');
654 #if FAT_DATETIME_SUPPORT
655 void get_datetime(uint16_t* year, uint8_t* month, uint8_t* day, uint8_t* hour, uint8_t* min, uint8_t* sec)