void setup() {
Serial.begin(9600); // Start serial communication at 9600 baud
while (!Serial); // Wait for Serial to be ready (useful for boards like Arduino Leonardo)
Serial.println("Serial Shell Ready. Type 'help' for commands.");
// Set GPIO pins 2-9 as OUTPUT (adjust if necessary for your board)
for (int pin = 2; pin <= 9; pin++) {
pinMode(pin, OUTPUT);
digitalWrite(pin, HIGH); // Ensure pins start HIGH
}
}
void loop() {
static String inputBuffer = ""; // Buffer to store incoming data
// Check if data is available on the serial port
if (Serial.available()) {
char incomingChar = Serial.read(); // Read one character
// Check for end of command
if (incomingChar == '\n' || incomingChar == '\r') {
if (inputBuffer.length() > 0) {
processCommand(inputBuffer); // Process the full command
inputBuffer = ""; // Clear the buffer
}
} else {
inputBuffer += incomingChar; // Append character to buffer
}
}
}
void processCommand(String command) {
command.trim(); // Remove leading/trailing whitespace
if (command == "help") {
Serial.println("Available Commands:");
Serial.println(" - help: Show this help message");
Serial.println(" - led_on: Turn the onboard LED on");
Serial.println(" - led_off: Turn the onboard LED off");
Serial.println(" - status: Get the LED status");
Serial.println(" - reboot <pin> [time]: Set a GPIO LOW for specified time (default 1s)");
} else if (command.startsWith("reboot ")) {
handleRebootCommand(command);
} else if (command == "led_on") {
digitalWrite(LED_BUILTIN, HIGH);
Serial.println("LED is ON.");
} else if (command == "led_off") {
digitalWrite(LED_BUILTIN, LOW);
Serial.println("LED is OFF.");
} else if (command == "status") {
if (digitalRead(LED_BUILTIN) == HIGH) {
Serial.println("LED is currently ON.");
} else {
Serial.println("LED is currently OFF.");
}
} else {
Serial.println("Unknown command. Type 'help' for a list of commands.");
}
}
void handleRebootCommand(String command) {
// Parse arguments (e.g., "reboot 5 2000")
int firstSpace = command.indexOf(' ');
int secondSpace = command.indexOf(' ', firstSpace + 1);
// Extract pin number and optional time
int pin = command.substring(firstSpace + 1, secondSpace).toInt();
int duration = (secondSpace != -1) ? command.substring(secondSpace + 1).toInt() : 1000;
// Validate pin range (2-9 for GPIOs on most Arduino boards)
if (pin < 2 || pin > 9) {
Serial.println("Invalid pin number. Use a number between 2 and 9.");
return;
}
// Validate duration
if (duration <= 0) {
Serial.println("Invalid duration. Must be greater than 0.");
return;
}
// Execute command
Serial.print("Rebooting GPIO ");
Serial.print(pin);
Serial.print(" for ");
Serial.print(duration);
Serial.println(" ms...");
digitalWrite(pin, LOW);
delay(duration);
digitalWrite(pin, HIGH);
Serial.println("Done.");
}