# BeShell-SD Card Example App
This is an example project demonstrating the usage of BeShell-SD Card (SD card driver).
## Features
This example project demonstrates the following features:
### SD Card Features
| Example File | Description |
|---------|------|
| `basic-setup.js` | SD card basic initialization and mounting |
| `file-operations.js` | File read, write, copy, delete operations |
| `directory-ops.js` | Directory create, traverse, recursive delete |
| `file-browser.js` | Interactive file browser |
| `data-logger.js` | Sensor data logging to SD card |
| `image-viewer.js` | Image file scanning and info display |
## Project Structure
```
beshell-sdcard-app/
├── CMakeLists.txt # Project CMake configuration
├── sdkconfig.defaults # Default SDK configuration
├── README.md # This file
├── main/
│ ├── main.cpp # C++ entry file
│ ├── CMakeLists.txt # main component CMake config
│ └── idf_component.yml # Component dependencies
├── img/
│ ├── partitions-4MB.csv # 4MB Flash partition table
│ ├── partitions-8MB.csv # 8MB Flash partition table
│ └── partitions-16MB.csv # 16MB Flash partition table
└── js/
├── main.js # JS entry file
└── example/ # Example scripts directory
├── basic-setup.js
├── file-operations.js
├── directory-ops.js
├── file-browser.js
├── data-logger.js
└── image-viewer.js
```
## Hardware Requirements
- ESP32 / ESP32-S3 / ESP32-C3 or other chips
- SD card module or SD card slot
- SD card (FAT32 format)
- At least 4MB Flash
- USB-to-Serial for flashing and debugging
### Hardware Connection (SPI Mode)
```
ESP32 SD Card
----- -------
GPIO 5 --> CS
GPIO 18 --> SCK
GPIO 19 --> MISO
GPIO 23 --> MOSI
3.3V --> VCC
GND --> GND
```
**Note**:
- Some SD card modules require 5V power, ESP32 GPIO is 3.3V
- Recommend using SD card module with level shifter
- SPI pins may vary depending on ESP32 model
## SD Card Preparation
1. Format SD card to FAT32 file system
2. Can create some test files and directories in advance
3. Insert SD card into module
## Quick Start
### 1. Modify SPI Configuration
Modify the configuration in examples according to your hardware:
```javascript
const SPI_HOST = 2 // SPI2 (HSPI)
const PIN_CS = 5 // CS pin
```
### 2. Build the Project
```bash
idf.py build
```
### 3. Flash the Firmware
```bash
idf.py flash
```
### 4. View Serial Output
```bash
idf.py monitor
```
### 5. Run Examples
In the serial terminal, enter the following command to run an example:
```
run /example/basic-setup.js
```
## Example Details
### Basic Setup
```javascript
import { SDCard } from "sdcard"
let sd = new SDCard()
sd.setup({
spi: 2, // SPI host
cs: 5, // CS pin
mount: "/sdcard", // Mount path
khz: 20000 // SPI clock frequency (kHz)
})
```
### File Operations
```javascript
// Write file
let fhandle = fs.open("/sdcard/test.txt", "w")
fs.write(fhandle, new TextEncoder().encode("Hello SD Card!"))
fs.close(fhandle)
// Read file
fhandle = fs.open("/sdcard/test.txt", "r")
let buffer = new Uint8Array(100)
fs.read(fhandle, buffer)
fs.close(fhandle)
console.log(new TextDecoder().decode(buffer))
```
### Directory Operations
```javascript
// Create directory
fs.mkdir("/sdcard/mydir")
// List directory
let files = fs.listDirSync("/sdcard")
files.forEach(f => console.log(f))
// Remove directory
fs.rmdir("/sdcard/mydir")
```
### Data Logging
```javascript
// Append to log file
let fhandle = fs.open("/sdcard/logs/data.csv", "a")
let line = `${Date.now()},${sensorValue}\n`
fs.write(fhandle, new TextEncoder().encode(line))
fs.close(fhandle)
```
## API Reference
### SDCard Class
#### constructor()
Create SDCard object.
#### setup(config)
Initialize SD card.
- `config.spi`: SPI host number (0-2)
- `config.cs`: CS pin number
- `config.mount`: Mount path
- `config.khz`: SPI clock frequency (kHz)
### File System API (fs module)
#### fs.open(path, mode)
Open file.
- `mode`: "r" (read), "w" (write), "a" (append)
#### fs.read(handle, buffer)
Read file content to buffer.
#### fs.write(handle, data)
Write data to file.
#### fs.close(handle)
Close file.
#### fs.stat(path)
Get file/directory info.
#### fs.mkdir(path)
Create directory.
#### fs.rmdir(path)
Remove empty directory.
#### fs.unlink(path)
Delete file.
#### fs.listDirSync(path)
Synchronously list directory contents.
## Performance Tips
1. **Buffer Size**: Use larger buffers (e.g., 4KB) for read/write to improve performance
2. **File Open Time**: Keep file open for multiple writes instead of frequent open/close
3. **SPI Frequency**: Adjust SPI frequency according to SD card quality (default 20MHz)
4. **Long Filename**: Enable `CONFIG_FATFS_LFN_STACK` for long filename support
## Troubleshooting
### SD Card Initialization Failed
1. Check SPI connections (CS, SCK, MISO, MOSI)
2. Confirm SD card is properly inserted
3. Check if SD card is formatted as FAT32
4. Try lowering SPI frequency
5. Test with another SD card
### File Read/Write Error
1. Check if mount path is correct
2. Confirm file path exists
3. Check if SD card has enough space
4. Confirm file is not being used by other programs
## Dependencies
- [beshell](https://github.com/become-cool/beshell) - BeShell core framework
- [beshell-drv-sdcard](https://github.com/become-cool/beshell-drv-sdcard) - SD card driver component
## License
LGPL
## Links
- [BeShell Documentation](https://beshell.become.cool)
- [ESP-IDF SD Card Documentation](https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/storage/sdmmc.html)
- [FATFS Documentation](http://elm-chan.org/fsw/ff/00index_e.html)
To create a project from this example, run:
idf.py create-project-from-example "become-cool/beshell-drv-sdcard=1.0.1:beshell-sdcard-app"