I bought a new Arduino MKR Zero which is generally promoted for playing sound from SD Card (SD card slot built-in on the board) but since the Microcontroller is SAMD21
, I believe it supports keyboard emulation.
I am trying to simulate opening a file code.txt
from SD card with the following code:
CTRL ESC
delay(100)
STRING r
delay(100)
STRING notepad
ENTER
and on the Arduino MKR Zero, I flashed the following code:
#include <SD.h>
#include <Keyboard.h>
File codeFile;
File logFile;
void setup() {
pinMode(LED_BUILTIN, OUTPUT);
Serial.begin(9600);
delay(2000); // Allow time for the serial monitor to open
Keyboard.begin();
// Initialize the SD card
if (!SD.begin()) { // Change the pin number according to your setup
Serial.println("SD initialization failed!");
return;
}
else {
Serial.println("SD Initialized success!");
}
// Open the code file
codeFile = SD.open("code.txt");
if (!codeFile) {
Serial.println("Failed to open code.txt");
return;
}
else{
Serial.println("code.txt found in SD Card.");
}
// Open the log file
logFile = SD.open("log.txt", FILE_WRITE); // Open for writing (create if it doesn't exist)
if (!logFile) {
Serial.println("Failed to open log.txt");
return;
}
else {
Serial.println("log.txt opened in SD card.");
}
// Wait for the computer to recognize the USB connection
delay(5000);
// Execute the code from the file
while (codeFile.available()) {
char c = codeFile.read();
Keyboard.write(c); // Send each character from the file as a keystroke
logFile.write(c); // Write the character to the log file
Serial.print(c); //print the character in Serial Monitor
delay(20); // Adjust this delay as needed
}
// Close the files
codeFile.close();
logFile.close();
Keyboard.end();
Serial.println("\n\nEnd of code.");
digitalWrite(LED_BUILTIN, HIGH);
}
void loop() {
// Nothing to do here
}
The code uploads successfully on the board. Now, when I reset the board, I am getting the following output in the Serial Monitor.
SD Initialized success!
code.txt found in SD Card.
log.txt opened in SD card.
CTRL ESC
delay(100)
STRING r
delay(100)
STRING notepad
ENTER
End of code.
But this code is not doing anything on the Desktop. What am I doing incorrect here?
I found the solution, seems like it was driver issue.
I went to Device Manager and saw 2 drivers,
Arduino MKR Zero (COM14)
with Code 10
USB Serial Device (COM13)
I uninstalled both the drivers, reboot and now, HID was working fine.
One issue, the HID was simply typing the contents of the code.txt
file rather than executing it (I saw it typing GUI r...
in notepad in Windows).
I just have to figure out how to execute it instead.