Tarjeta SD#

Introducción#

La clase sdcard se deriva de la clase base brain y proporciona acceso a los archivos almacenados en una tarjeta SD extraíble insertada en el V5 Brain.

Mediante la tarjeta SD, tu robot puede cargar datos como imágenes, leer y escribir archivos, y almacenar información para su uso posterior o para transferirla a un ordenador.

Access#

Brain.SDcard

Notes#

  • El V5 Brain admite tarjetas SD de hasta 32 GB.

  • La tarjeta SD debe estar formateada como FAT32.

    • Las tarjetas SD de más de 32 GB suelen estar formateadas en exFAT, que no es compatible con el V5 Brain.

  • Para poder acceder a los archivos, estos deben estar ubicados en el directorio raíz de la tarjeta SD.

  • La tarjeta SD debe insertarse en el dispositivo antes de poder realizar operaciones con archivos.

  • Los nombres y las rutas de archivo distinguen entre mayúsculas y minúsculas.

Example#

/* This constructor is required when using VS Code.
A Brain is generated automatically at the start of
VEXcode projects. */

// Create the V5 Brain
brain Brain = brain();

// Add more text and display file size
if (Brain.SDcard.exists("Text.txt")) {
  // Get the size of the file
  int fileSize = Brain.SDcard.size("Text.txt");

  // Make a buffer to hold the file data
  uint8_t buffer[fileSize];

  // Load the file from the SD card into the buffer
  Brain.SDcard.loadfile("Text.txt", buffer, sizeof(buffer));

  // Display the file contents on the screen
  Brain.Screen.print("%s", buffer);
}

Funciones de los miembros#

La clase sdcard incluye las siguientes funciones miembro:

  • loadfile — Carga el contenido de un archivo desde la tarjeta SD en un búfer de memoria proporcionado por el usuario.

  • savefile — Guarda datos de un búfer proporcionado por el usuario en un archivo en la tarjeta SD del V5 Brain.

  • appendfile — Agrega datos de un búfer proporcionado por el usuario al final de un archivo existente en la tarjeta SD del V5 Brain.

  • isInserted — Devuelve si hay una tarjeta SD insertada en el Brain.

  • size — Devuelve el tamaño de un archivo almacenado en la tarjeta SD del V5 Brain.

  • exists — Devuelve si existe un archivo con el nombre especificado en la tarjeta SD del V5 Brain.

Los archivos .bmp y .png almacenados en la tarjeta SD se pueden mostrar en la pantalla V5 Brain usando drawImageFromFile, a la que se accede a través de Brain.Screen.

Antes de llamar a cualquier función miembro de sdcard , se debe crear una instancia brain , como se muestra a continuación:

// Create the V5 Brain
brain Brain = brain();

loadfile#

Carga el contenido de un archivo desde la tarjeta SD en un búfer de memoria proporcionado por el usuario.

Available Functions
int32_t loadfile(
  const char* name,
  uint8_t* buffer,
  int32_t len );

Parameters

Parámetro

Tipo

Descripción

name

const char*

El nombre del archivo que se cargará desde la tarjeta SD. El nombre del archivo debe incluir la extensión.

buffer

uint8_t*

Un puntero a un búfer donde se almacenarán los datos del archivo.

len

int32_t

El número máximo de bytes que se leerán del archivo, que normalmente se establece al tamaño del búfer.

Return Values

Devuelve un valor int32_t que representa el número de bytes leídos correctamente del archivo:

  • Un valor positivo indica cuántos bytes se cargaron en el búfer.

  • 0 indica que no se leyó ningún dato.

Notes
  • Si el archivo es mayor que len, solo se leen los primeros len bytes.

  • El búfer debe ser lo suficientemente grande como para contener los datos solicitados.

  • Esta función lee bytes sin procesar y no agrega un terminador nulo.

Examples
// Check for SD card and show a file's text
if (Brain.SDcard.isInserted()) {
  // Create a message to save to the SD card
  uint8_t message[] = "Hello from VEX!";

  // Save the message into "Text.txt"
  Brain.SDcard.savefile("Text.txt", message, sizeof(message));

  // Get the size of the file
  int fileSize = Brain.SDcard.size("Text.txt");

  // Make a buffer to hold the file data
  uint8_t buffer[fileSize];

  // Load the file from the SD card into the buffer
  Brain.SDcard.loadfile("Text.txt", buffer, sizeof(buffer));

  // Display the file contents on the screen
  Brain.Screen.print("%s", buffer);
} else {
  Brain.Screen.print("Insert SD card");
}

savefile#

Guarda los datos de un búfer proporcionado por el usuario en un archivo de la tarjeta SD del V5 Brain.

Available Functions
int32_t savefile(
  const char* name,
  uint8_t* buffer,
  int32_t len );

Parameters

Parámetro

Tipo

Descripción

name

const char*

El nombre del archivo que se guardará como una cadena de texto. El nombre del archivo debe incluir la extensión.

buffer

uint8_t*

Un puntero a un búfer de memoria que contiene los datos que se escribirán en el archivo.

len

int32_t

El número de bytes que se escribirán desde el búfer al archivo.

Return Values

Devuelve un valor int32_t que representa el número de bytes escritos correctamente en el archivo:

  • Un valor positivo indica cuántos bytes se guardaron.

  • 0 indica que no se escribieron datos.

Notes
  • Si el archivo es mayor que len, solo se leen los primeros len bytes.

  • Si ya existe un archivo con el mismo nombre, se sobrescribirá.

  • Esta función no asigna memoria; el búfer debe ser creado y administrado por el usuario.

  • La función escribe bytes sin procesar y no añade un terminador nulo.

Examples
// Check for SD card and show a file's text
if (Brain.SDcard.isInserted()) {
  // Create a message to save to the SD card
  uint8_t message[] = "Hello from VEX!";

  // Save the message into "Text.txt"
  Brain.SDcard.savefile("Text.txt", message, sizeof(message));

  // Get the size of the file
  int fileSize = Brain.SDcard.size("Text.txt");

  // Make a buffer to hold the file data
  uint8_t buffer[fileSize];

  // Load the file from the SD card into the buffer
  Brain.SDcard.loadfile("Text.txt", buffer, sizeof(buffer));

  // Display the file contents on the screen
  Brain.Screen.print("%s", buffer);
} else {
  Brain.Screen.print("Insert SD card");
}

appendfile#

Agrega datos desde un búfer proporcionado por el usuario al final de un archivo existente en la tarjeta SD del V5 Brain.

Available Functions
int32_t appendfile(
  const char* name,
  uint8_t* buffer,
  int32_t len );

Parameters

Parámetro

Tipo

Descripción

name

const char*

El nombre del archivo al que se añadirán datos en la tarjeta SD. El nombre del archivo debe incluir la extensión.

buffer

uint8_t*

Un puntero a un búfer de memoria que contiene los datos que se añadirán al archivo.

len

int32_t

El número de bytes que se añadirán desde el búfer al archivo.

Return Values

Devuelve un int32_t que representa el número de bytes agregados correctamente al archivo:

  • Un valor positivo indica cuántos bytes se añadieron.

  • 0 indica que no se añadieron datos.

Notes
  • Si el archivo es mayor que len, solo se leen los primeros len bytes.

  • El archivo debe existir previamente en la tarjeta SD; esta función no crea un archivo nuevo.

  • Esta función no asigna memoria; el búfer debe ser creado y administrado por el usuario.

  • La función agrega bytes sin procesar y no agrega un terminador nulo.

Examples
// Create a message to save to a new file
uint8_t message[] = "Hello";

// Save only the characters, not the null terminator
Brain.SDcard.savefile("Message.txt", message, sizeof(message) - 1);

// Load the file
int fileSize = Brain.SDcard.size("Message.txt");
uint8_t buffer[fileSize + 1];
Brain.SDcard.loadfile("Message.txt", buffer, fileSize);

// Add null terminator so it can be printed safely
buffer[fileSize] = 0;
Brain.Screen.print("%s\n", buffer);

// Create more text to append to the same file
uint8_t moreText[] = " World!";

// Append only the characters, not the null terminator
Brain.SDcard.appendfile("Message.txt", moreText, sizeof(moreText) - 1);

// Load the updated file
fileSize = Brain.SDcard.size("Message.txt");
uint8_t buffer2[fileSize + 1];
Brain.SDcard.loadfile("Message.txt", buffer2, fileSize);

// Add null terminator
buffer2[fileSize] = 0;
Brain.Screen.newLine();
Brain.Screen.print("%s", buffer2);

isInserted#

Indica si hay una tarjeta SD insertada en el V5 Brain.

Available Functions
bool isInserted();

Parameters

Esta función no acepta ningún parámetro.

Return Values

Devuelve un valor booleano que indica si hay una tarjeta SD insertada:

  • true — Se inserta una tarjeta SD en el V5 Brain.

  • false — No hay ninguna tarjeta SD insertada.

Notes
  • Esta función solo comprueba la presencia de una tarjeta SD; no verifica que la tarjeta esté formateada o sea legible.

Examples
// Check for SD card and show a file's text
if (Brain.SDcard.isInserted()) {
  // Create a message to save to the SD card
  uint8_t message[] = "Hello from VEX!";

  // Save the message into "Text.txt"
  Brain.SDcard.savefile("Text.txt", message, sizeof(message));

  // Get the size of the file
  int fileSize = Brain.SDcard.size("Text.txt");

  // Make a buffer to hold the file data
  uint8_t buffer[fileSize];

  // Load the file from the SD card into the buffer
  Brain.SDcard.loadfile("Text.txt", buffer, sizeof(buffer));

  // Display the file contents on the screen
  Brain.Screen.print("%s", buffer);
} else {
  Brain.Screen.print("Insert SD card");
  }

size#

Devuelve el tamaño de un archivo almacenado en la tarjeta SD del V5 Brain.

Available Functions
int32_t size(
  const char* name );

Parameters

Parámetro

Tipo

Descripción

name

const char*

El nombre del archivo en la tarjeta SD. El nombre del archivo debe incluir la extensión.

Return Values

Devuelve un int32_t que representa el tamaño del archivo en bytes:

  • Un valor positivo indica el tamaño del archivo en bytes.

  • 0 indica que el archivo está vacío o que no se pudo encontrar.

Notes
  • El tamaño devuelto se puede utilizar para asignar un búfer antes de llamar a loadfile.

Examples
// Check for SD card and show a file's text
if (Brain.SDcard.isInserted()) {
  // Create a message to save to the SD card
  uint8_t message[] = "Hello from VEX!";

  // Save the message into "Text.txt"
  Brain.SDcard.savefile("Text.txt", message, sizeof(message));

  // Get the size of the file
  int fileSize = Brain.SDcard.size("Text.txt");

  // Make a buffer to hold the file data
  uint8_t buffer[fileSize];

  // Load the file from the SD card into the buffer
  Brain.SDcard.loadfile("Text.txt", buffer, sizeof(buffer));

  // Display the file contents on the screen
  Brain.Screen.print("%s", buffer);
} else {
  Brain.Screen.print("Insert SD card");
}

exists#

Indica si existe un archivo con el nombre especificado en la tarjeta SD del V5 Brain.

Available Functions
bool exists(
  const char* name );

Parameters

Parámetro

Tipo

Descripción

name

const char*

El nombre del archivo que se va a comprobar en la tarjeta SD. El nombre del archivo debe incluir la extensión.

Return Values

Devuelve un valor booleano que indica si el archivo existe:

  • true — Existe un archivo con el nombre especificado en la tarjeta SD.

  • false — No existe ningún archivo con el nombre especificado.

Examples
// Add more text and display file size
if (Brain.SDcard.exists("Text.txt")) {
  // Get the size of the file
  int fileSize = Brain.SDcard.size("Text.txt");

  // Make a buffer to hold the file data
  uint8_t buffer[fileSize];

  // Load the file from the SD card into the buffer
  Brain.SDcard.loadfile("Text.txt", buffer, sizeof(buffer));

  // Display the file contents on the screen
  Brain.Screen.print("%s", buffer);
}