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 cerebro IQ (2ª generación).
Con la tarjeta SD, su robot puede cargar datos como imágenes, leer y escribir archivos y almacenar información para su uso posterior o transferirla a una computadora.
Access#
Brain.SDcard
Notes#
El IQ (2ª generación) Brain admite tarjetas SD de hasta 32 GB de tamaño.
La tarjeta SD debe formatearse como FAT32.
Las tarjetas SD de más de 32 GB suelen formatearse como exFAT, lo que no es compatible con el cerebro IQ (2ª generación).
Todos los archivos deben colocarse en el directorio raíz de la tarjeta SD para ser accesibles.
La tarjeta SD debe insertarse en el cerebro antes de que se puedan realizar las operaciones del archivo.
Los nombres de archivo y las rutas distinguen entre mayúsculas y minús
Example#
/* This constructor is required when using VS Code.
A Brain is generated automatically at the start of
VEXcode projects. */
// Create the 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 de miembro:
loadfile: carga el contenido de un archivo de la tarjeta SD en un búfer de memoria proporcionado por el usuario.savefile: guarda los datos de un búfer proporcionado por el usuario en un archivo de la tarjeta SD de IQ (2 .ª generación) Brain.appendfile: adjunta datos de un búfer proporcionado por el usuario al final de un archivo existente en la tarjeta SD de IQ (2 .ª generación) Brain.isInserted— Devuelve si se ha insertado una tarjeta SD en el cerebro.size— Devuelve el tamaño de un archivo almacenado en la tarjeta SD de IQ (2nd gen) Brain.exists— Devuelve si existe un archivo con el nombre especificado en la tarjeta SD de IQ (2nd gen) Brain.
Los archivos .bmp y .png almacenados en la tarjeta SD se pueden mostrar en la pantalla Brain de IQ (segunda generación) utilizando drawImageFromFile, a la que se accede a través deBrain.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 Brain
brain Brain = brain();
loadfile#
Carga el contenido de un archivo de la tarjeta SD en un búfer de memoria proporcionado por el usuario.
Available Functionsint32_t loadfile(
const char* name,
uint8_t* buffer,
int32_t len );
Parámetro |
Tipo |
Descripción |
|---|---|---|
|
|
El nombre del archivo a cargar desde la tarjeta SD. El nombre del archivo debe incluir la extensión del archivo. |
|
|
Un puntero a un búfer donde se almacenarán los datos del archivo. |
|
|
El número máximo de bytes para leer del archivo, generalmente establecido en el tamaño del búfer. |
Devuelve un 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.
0indica que no se leyeron datos.
Si el archivo es más grande que
len, solo se leen los primeros bytes delen.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.
// 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 en la tarjeta SD de IQ (2ª generación) Brain.
Available Functionsint32_t savefile(
const char* name,
uint8_t* buffer,
int32_t len );
Parámetro |
Tipo |
Descripción |
|---|---|---|
|
|
El nombre del archivo a guardar como una cadena. El nombre del archivo debe incluir la extensión del archivo. |
|
|
Un puntero a un búfer de memoria que contiene los datos que se van a escribir en el archivo. |
|
|
El número de bytes a escribir desde el búfer al archivo. |
Devuelve un int32_t que representa el número de bytes escritos correctamente en el archivo:
Un valor positivo indica cuántos bytes se guardaron.
0indica que no se escribió ningún dato.
Si el archivo es más grande que
len, solo se leen los primeros bytes delen.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.
// 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#
Adjunta datos de un búfer proporcionado por el usuario al final de un archivo existente en la tarjeta SD de IQ (2ª generación) Brain.
Available Functionsint32_t appendfile(
const char* name,
uint8_t* buffer,
int32_t len );
Parámetro |
Tipo |
Descripción |
|---|---|---|
|
|
El nombre del archivo al que adjuntar datos en la tarjeta SD. El nombre del archivo debe incluir la extensión del archivo. |
|
|
Un puntero a un búfer de memoria que contiene los datos que se adjuntarán al archivo. |
|
|
El número de bytes a adjuntar desde el búfer al archivo. |
Devuelve un int32_t que representa el número de bytes añadidos correctamente al archivo:
Un valor positivo indica cuántos bytes se agregaron.
0indica que no se agregaron datos.
Si el archivo es más grande que
len, solo se leen los primeros bytes delen.El archivo ya debe existir en la tarjeta SD; esta función no crea un nuevo archivo.
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.
// 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#
Devuelve si una tarjeta SD está insertada actualmente en el cerebro IQ (2ª generación).
Available Functionsbool isInserted();
Esta función no acepta ningún parámetro.
Return ValuesDevuelve un booleano que indica si se ha insertado una tarjeta SD:
true— Se inserta una tarjeta SD en el cerebro IQ (2ª generación).false— No se inserta ninguna tarjeta SD.
Esta función solo verifica la presencia de una tarjeta SD; no verifica que la tarjeta esté formateada o sea legible.
// 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 de IQ (2ª generación) Brain.
Available Functionsint32_t size(
const char* name );
Parámetro |
Tipo |
Descripción |
|---|---|---|
|
|
El nombre del archivo en la tarjeta SD. El nombre del archivo debe incluir la extensión del archivo. |
Devuelve un int32_t que representa el tamaño del archivo en bytes:
Un valor positivo indica el tamaño del archivo en bytes.
0indica un archivo vacío o que no se pudo encontrar el archivo.
El tamaño devuelto se puede utilizar para asignar un búfer antes de llamar a
loadfile.
// 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#
Devuelve si existe un archivo con el nombre especificado en la tarjeta SD de IQ (2nd gen) Brain.
Available Functionsbool exists(
const char* name );
Parámetro |
Tipo |
Descripción |
|---|---|---|
|
|
El nombre del archivo a comprobar en la tarjeta SD. El nombre del archivo debe incluir la extensión del archivo. |
Devuelve un 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.
// 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);
}