Hi everyone,
I came across an interesting problem. I want to read a file from a USB thumb stick which worked perfectly fine with a previous sketch of mine. However, now I modified the code so that the program checks periodically whether a USB stick is attached and initialised or not. This part works fine, but now I get an error and the file cannot be opened and read anymore. I tried a couple of things (switching from if statements to while loops, existence of file, file path), but nothing helped. Any ideas??
I declared all variables globally and created the function:
void usbConnection() {
unsigned long connectMillis = millis();
if (connectMillis - tUSBCheck >= tUSBCheckInterval) { // Check USB status periodically
tUSBCheck = connectMillis;
if (!msd.connected()) {
lv_label_set_text(label, "No USB drive found.");
static lv_style_t style;
lv_style_init(&style);
lv_style_set_text_color(&style, lv_palette_main(LV_PALETTE_RED));
lv_obj_add_style(label, &style, 0);
Serial.println("MSD not connected");
usbConnected = false; // Update flag to false if not connected
msd.connect(); // Attempt to connect to USB drive
delay(500);
}
else if (msd.connected() && !usbConnected) {
lv_label_set_text(label, "USB drive found.");
static lv_style_t style;
lv_style_init(&style);
lv_style_set_text_color(&style, lv_palette_main(LV_PALETTE_GREEN));
lv_obj_add_style(label, &style, 0);
Serial.println("MSD connected");
usbConnected = true; // Update flag to true if connected
}
}
}
I call this function in
void loop() { usbConnection(); }
and to read the file on the USB stick, I created:
void btnLoadFileClicked(lv_event_t * e) {
Serial.println("Load file button clicked");
if (!msd.connected()) {
Serial.println("USB not connected. Please connect a USB drive.");
return;
}
// Opening .txt file for loading of parameters
delay(2500);
settings = fopen("/usb/settings.txt", "r");
if (settings) {
Serial.println("Opened file");
// logic for file handling
fclose(settings);
Serial.println("Closed file");
} else if (!settings) {
Serial.println("Failed to open file");
}
}
I'm always getting "Failed to open file" in the serial monitor...
Best, Lea