sending a serial command and keeping it active after closing the monitor

So I have a problem which must be quite simple to fix I just can't find the right wording to describe it. If I write 'on' into the serial monitor the light turns on and if I write 'off' the light turns off. Simple stuff! :sunglasses:

But... when I turn the light on and close the serial monitor the light turns off. I understand this is because it's no longer receiving serial commands but how can I make the output remember its last known state?

This would mean if I turned the led on and closed the monitor it would stay on.

Any ideas would be great. :grin:

Here's what I have so far....

(Also I can't just set the pin HIGH in void setup, forcing it to default to on. It needs to be controllable as I am using python scripts to send the commands.)

/*
 Simple LED sketch
 */
     
int led = 13; // Pin 13
     
void setup()
{
    pinMode(led, OUTPUT); // Set pin 13 as digital out
     
    // Start up serial connection
    Serial.begin(9600); // baud rate
    Serial.flush();
}
     
void loop()
{
    String input = "";
     
    // Read any serial input
    while (Serial.available() > 0)
    {
        input += (char) Serial.read(); // Read in one char at a time
        delay(5); // Delay for 5 ms so the next char has time to be received
    }
     
    if (input == "on")
    {
        digitalWrite(led, HIGH); // on
    }
    else if (input == "off")
    {
        digitalWrite(led, LOW); // off
    }
}

The problem is that the arduino gets rebooted when you open or close the com port. If you want to over ride this behaviour the simplest fix is to place a 10uF electrolytic capacitor from GND to the reset pin. You'll have to remove this prior to uploading any sketch as the upload process relies on this reboot.

Thank you Ken that is exactly what I needed!