#include <SPI.h>
void setup() {
// put your setup code here, to run once:
SPI_initialization(9600);
// Using STRCAT() ---------------------------------
// int32_t session = 45;
// int32_t fileIndex = 10;
// char formatted_NUM[5];
// char fileName[13];
// strcat(fileName,fourDigits(session,formatted_NUM));
// strcat(fileName,fourDigits(fileIndex,formatted_NUM));
// strcat(fileName, ".txt");
// Serial.println(fileName);
//---------------------------------
int32_t session = 5555;
int32_t fileIndex = 1;
char fileName[13]; // Increased size to accommodate null terminator
// Use the same buffer for formatting to avoid unnecessary memory allocation
// and improve performance
fourDigits(session, fileName);
fourDigits(fileIndex, fileName + 4); // Move the pointer to the next available position
// Use snprintf for better readability and to avoid potential buffer overflows
snprintf(fileName + 8, 5, ".txt");
Serial.println(fileName);
}
void loop() {
}
/* Format function; adds leading zeros;
retruns 4 digits*/
char* fourDigits(int32_t digits, char* result)
{
if (digits < 10)
{
sprintf(result, "000%d", digits);
}
else if (digits < 100)
{
sprintf(result, "00%d", digits);
}
else if (digits < 1000)
{
sprintf(result, "0%d", digits);
}
else
{
sprintf(result, "%d", digits);
}
return result;
}
/* Format function: adds leading zeros
** Required input:
*** char formattedNumber[3]; ensures space for format & null
** retruns formattedNumber*/
char* twoDigits(int32_t digits, char* result) // used to format file name
{
if (digits < 10)
{
sprintf(result, "0%d", digits);
}
else
{
sprintf(result, "%d", digits);
}
return result;
}
/* Open serial communications by initializing serial obj @ baudRate
- Standard baudRate = 9600
- Speed of printing to serial monitor
*/
void SPI_initialization(const int baudRate)
{
Serial.begin(baudRate);
// Will wait up to 15 seconds for Arduino Serial Monitor / serial port to connect
// - Needed for native USB port only
// - Ensure only one monitor is open
while (!Serial && millis() < 15000)
{
;
}
Serial.println("\n\n-----New Serial Communication Secured-----");
}