#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include <esp_log.h>
#include <esp_vfs.h>
#include <esp_vfs_fat.h>
#include <sdmmc_cmd.h>
#include "driver/uart.h"
#define CONFIG_LOG_DEFAULT_LEVEL_VERBOSE 1
//#define CONFIG_LOG_MAXIMUM_LEVEL 5
#define TAG "SD"
/* Indique las conexiones de SPI aquí */
#define PIN_NUM_MISO 19
#define PIN_NUM_MOSI 23
#define PIN_NUM_CLK 18
#define PIN_NUM_CS 5
#define EXAMPLE_MAX_CHAR_SIZE 64
#define MOUNT_POINT "/sdcard"
static esp_err_t s_example_write_file(const char *path, char *data)
{
ESP_LOGI(TAG, "Abriendo archivo %s", path);
FILE *f = fopen(path, "w");
if (f == NULL) {
ESP_LOGE(TAG, "Falló abrir archivo para escritura");
return ESP_FAIL;
}
fprintf(f, data);
fclose(f);
ESP_LOGI(TAG, "Archivo escrito");
return ESP_OK;
}
static esp_err_t s_example_read_file(const char *path)
{
ESP_LOGI(TAG, "Leyendo archivo %s", path);
FILE *f = fopen(path, "r");
if (f == NULL) {
ESP_LOGE(TAG, "Falló abrir archivo para lectura");
return ESP_FAIL;
}
char line[EXAMPLE_MAX_CHAR_SIZE];
fgets(line, sizeof(line), f);
fclose(f);
ESP_LOGI(TAG, "Lectura de archivo: '%s'", line);
return ESP_OK;
}
static void uartClrScr(uart_port_t uart_num) {
const char *clr_scr_seq = "\033[2J";
uart_write_bytes(uart_num, clr_scr_seq, strlen(clr_scr_seq));
}
// Function to move the cursor to a specified position in the terminal
static void uartGotoxy(uart_port_t uart_num, int x, int y) {
char gotoxy_seq[30];
// Construct the ANSI escape sequence for moving the cursor
snprintf(gotoxy_seq, sizeof(gotoxy_seq), "\033[%d;%dH", y + 1, x + 1);
// Write the sequence to the UART
uart_write_bytes(uart_num, gotoxy_seq, strlen(gotoxy_seq));
}
// Escribir cadena por medio del uart especificado
static void uartPuts(uart_port_t uart_num, const char *str) {
uart_write_bytes(uart_num, str, strlen(str));
}
// Tomar un caracter desde la entrada de uart especificado
static char uartGetchar(uart_port_t uart_num) {
char c;
while (uart_read_bytes(uart_num, &c, 1, portMAX_DELAY) == 0) {}
return c;
}
static void uartPutchar(uart_port_t uart_num, char c) {
uart_write_bytes(uart_num, &c, 1);
}
#define CONFIG_EXAMPLE_FORMAT_IF_MOUNT_FAILED
void delayMs(uint16_t ms) {
vTaskDelay(ms / portTICK_PERIOD_MS);
}
typedef enum {
waiting_for_command,
receive_chars_command,
input_name_command,
display_file_command,
edit_text_command,
save_text_command,
} command_type_t;
void initUart() {
const uart_port_t uart_num = UART_NUM_0;
uart_config_t uart_config = {
.baud_rate = 115200,
.data_bits = UART_DATA_8_BITS,
.parity = UART_PARITY_DISABLE,
.stop_bits = UART_STOP_BITS_1
};
// Configure UART parameters
ESP_ERROR_CHECK(uart_param_config(uart_num, &uart_config));
const int uart_buffer_size = (1024 * 2);
// Install UART driver using an event queue here
ESP_ERROR_CHECK(uart_driver_install(UART_NUM_0, uart_buffer_size, uart_buffer_size, 10, NULL, 0));
}
void executeCommand(command_type_t command, char *buffer, uint8_t *buffPos) {
char c = ' ';
char path[20] = {0};
uint8_t pathPos = 0;
char message[60];
switch(command) {
case waiting_for_command:
break;
case receive_chars_command:
uartPuts(UART_NUM_0, "Introduce una cadena: ");
while(c != 'E') { // ASCII for ESC
c = uartGetchar(UART_NUM_0);
if(c != 'E') {
buffer[(*buffPos)++] = c;
uartPutchar(UART_NUM_0, c); // Echo character
}
delayMs(1);
}
buffer[*buffPos] = '\0'; // Null-terminate the string
break;
case display_file_command:
while(c != 'E') {
c = uartGetchar(UART_NUM_0);
if(c != 'E') {
path[pathPos++] = c;
uartPutchar(UART_NUM_0, c); // Echo character
}
delayMs(1);
}
path[pathPos] = '\0'; // Null-terminate the string
s_example_read_file(path);
break;
case save_text_command:
uartPuts(UART_NUM_0, "Introduce nombre de archivo: ");
while(c != 'E') {
c = uartGetchar(UART_NUM_0);
if(c != 'E') {
path[pathPos++] = c;
uartPutchar(UART_NUM_0, c); // Echo character
}
delayMs(1);
}
path[pathPos] = '\0'; // Null-terminate the string
strcpy(path, "file.txt");
strcpy(buffer, "hola");
snprintf(message, sizeof(message), "Nombre del archivo: %s\n", path);
uartPuts(UART_NUM_0, message);
snprintf(message, sizeof(message), "Se guardara: %s\n\n", buffer);
uartPuts(UART_NUM_0, message);
s_example_write_file(path, buffer);
break;
case edit_text_command:
break;
case input_name_command:
break;
default:
break;
}
}
void app_main() {
printf("Hola, Wokwi!!\n");
esp_log_level_set(TAG, ESP_LOG_INFO);
esp_err_t ret;
// Opciones para montar el sistema de archivos.
// Si format_if_mount_failed es true, la SD card va a ser particionada y
// formateada en caso de que el montaje falle.
esp_vfs_fat_sdmmc_mount_config_t mount_config = {
#ifdef CONFIG_EXAMPLE_FORMAT_IF_MOUNT_FAILED
.format_if_mount_failed = true,
#else
.format_if_mount_failed = false,
#endif // EXAMPLE_FORMAT_IF_MOUNT_FAILED
.max_files = 5,
.allocation_unit_size = 16 * 1024
};
sdmmc_card_t *card;
const char mount_point[] = MOUNT_POINT;
ESP_LOGI(TAG, "Inicializando SD card");
ESP_LOGI(TAG, "Usando el periferico SPI");
// Por default, la frecuencia de la SD card es inicializada a SDMMC_FREQ_DEFAULT (20MHz)
// Para configurar una frecuencia específica, use host.max_freq_khz (rango 400kHz - 20MHz para SDSPI)
// Ejemplo: para una frecuencia fija de 10MHz, use host.max_freq_khz = 10000;
sdmmc_host_t host = SDSPI_HOST_DEFAULT();
host.slot = SPI3_HOST;
spi_bus_config_t bus_cfg = {
.mosi_io_num = PIN_NUM_MOSI,
.miso_io_num = PIN_NUM_MISO,
.sclk_io_num = PIN_NUM_CLK,
.quadwp_io_num = -1,
.quadhd_io_num = -1
};
ret = spi_bus_initialize(host.slot, &bus_cfg, SDSPI_DEFAULT_DMA);
if (ret != ESP_OK) {
ESP_LOGE(TAG, "Fallo inicializacion del bus.");
return;
}
sdspi_device_config_t slot_config = SDSPI_DEVICE_CONFIG_DEFAULT();
slot_config.gpio_cs = PIN_NUM_CS;
slot_config.host_id = host.slot;
ESP_LOGI(TAG, "Montaje del sistema de archivos");
ret = esp_vfs_fat_sdspi_mount(mount_point, &host, &slot_config, &mount_config, &card);
if (ret != ESP_OK) {
if (ret == ESP_FAIL) {
ESP_LOGE(TAG, "Falló montaje del sistema de archivos. "
"Si quieres que la tarjeta se formateé, configura la opción CONFIG_EXAMPLE_FORMAT_IF_MOUNT_FAILED.");
} else {
ESP_LOGE(TAG, "Falló inicialización de la tarjeta (%s). "
"Asegúrese de que las líneas de la tarjeta SD tengan resistencias pull-up en su lugar.", esp_err_to_name(ret));
}
return;
}
ESP_LOGI(TAG, "Sistema de archivos montado");
// Imprimir las propiedades de la tarjeta
sdmmc_card_print_info(stdout, card);
// Crear un archivo
const char *file_hello = MOUNT_POINT"/hello.txt";
char data[EXAMPLE_MAX_CHAR_SIZE];
snprintf(data, EXAMPLE_MAX_CHAR_SIZE, "%s %s!\n", "Hello: ", card->cid.name);
ret = s_example_write_file(file_hello, data);
if (ret != ESP_OK) {
return;
}
const char *file_foo = MOUNT_POINT"/foo.txt";
// Borrar archivo si existe (primero revisa si existe)
struct stat st;
if (stat(file_foo, &st) == 0) {
// Borrar
unlink(file_foo);
}
// Renombrar archivo
ESP_LOGI(TAG, "Renombrando %s a %s", file_hello, file_foo);
if (rename(file_hello, file_foo) != 0) {
ESP_LOGE(TAG, "Fallo renombrar");
return;
}
ret = s_example_read_file(file_foo);
if (ret != ESP_OK) {
return;
}
ESP_LOGI(TAG, "Fin del ejemplo");
// Caracter para tomar entrada del usuario
char c = ':';
const uart_port_t uart_num = UART_NUM_0;
uartClrScr(uart_num);
uartGotoxy(uart_num, 0, 0);
command_type_t command = waiting_for_command;
char buffer[256] = {0};
uint8_t buffPos = 0;
initUart();
uartPuts(UART_NUM_0, "Terminal Wokwi: \n");
uartPuts(UART_NUM_0, "Elija comando (t, e, s, v): \n");
while (1) {
char input = uartGetchar(UART_NUM_0);
uartPutchar(UART_NUM_0, input);
switch(input) {
case 't':
command = receive_chars_command;
executeCommand(command, buffer, &buffPos);
break;
case 'v':
command = display_file_command;
executeCommand(command, buffer, &buffPos);
break;
case 'e':
command = edit_text_command;
break;
case 's':
command = save_text_command;
executeCommand(command, buffer, &buffPos);
break;
default:
uartPuts(UART_NUM_0, "Comando desconocido. Intente de nuevo.\n");
break;
}
command = waiting_for_command;
delayMs(1);
}
}