Description
I wrote a simple sketch for the Opta that creates a new file in the root folder of a connected USB device and then writes inside it.
I planned to use the connection callback to immediately initialize the USB storage, but unfortunately it did not work. In fact the following sketch cannot create a new file:
Click to expand
#include <Arduino_UnifiedStorage.h>
USBStorage usbStorage;
volatile bool usbAvailable = false;
void setup()
{
// Disable debugging of storage operations.
Arduino_UnifiedStorage::debuggingModeEnabled = false;
// Init USBStorage object.
usbStorage = USBStorage();
// Register connect callback.
usbStorage.onConnect(connectionCallback);
usbStorage.onDisconnect(disconnectionCallback);
}
void loop()
{
while (!usbAvailable)
{
digitalWrite(LED_USER, HIGH);
delay(200);
digitalWrite(LED_USER, LOW);
delay(200);
}
digitalWrite(LED_USER, LOW);
Folder root = usbStorage.getRootFolder();
UFile outFile = root.createFile("test.txt", FileMode::APPEND);
outFile.write("Hello, World!");
outFile.close();
usbStorage.unmount();
digitalWrite(LED_USER, HIGH);
while (1)
{
}
}
void connectionCallback()
{
usbAvailable = true;
usbStorage.removeOnConnectCallback();
// This does not work!
if (!usbStorage.isMounted())
{
usbStorage.begin();
}
}
void disconnectionCallback()
{
usbAvailable = false;
usbStorage.onConnect(connectionCallback);
}
Furthemore, I suspect the storage might not be initialized at all when using the above code, as a simple call to root.exists()
in the loop would halt the execution causing a board reset.
If I instead move the storage initialization code in the loop()
function, the sketch works as expected. I will attach the functioning sketch below for completeness:
Click to expand
#include <Arduino_UnifiedStorage.h>
USBStorage usbStorage;
volatile bool usbAvailable = false;
void setup()
{
// Disable debugging of storage operations.
Arduino_UnifiedStorage::debuggingModeEnabled = false;
// Init USBStorage object.
usbStorage = USBStorage();
// Register connect callback.
usbStorage.onConnect(connectionCallback);
usbStorage.onDisconnect(disconnectionCallback);
}
void loop()
{
while (!usbAvailable)
{
digitalWrite(LED_USER, HIGH);
delay(200);
digitalWrite(LED_USER, LOW);
delay(200);
}
digitalWrite(LED_USER, LOW);
// This works!
if (!usbStorage.isMounted())
{
usbStorage.begin();
}
Folder root = usbStorage.getRootFolder();
UFile outFile = root.createFile("test.txt", FileMode::APPEND);
outFile.write("Hello, World!");
outFile.close();
usbStorage.unmount();
digitalWrite(LED_USER, HIGH);
while (1)
{
}
}
void connectionCallback()
{
usbAvailable = true;
usbStorage.removeOnConnectCallback();
}
void disconnectionCallback()
{
usbAvailable = false;
usbStorage.onConnect(connectionCallback);
}
I did not find any mention of this behavior in the docs. If I can provide further details or assistance ping me!