#define LED_PIN 14 // define the LED pin 13 for Arduino
int LEDState = LOW; // could use less memory with a byte data type
int blinkInterval = 2000; // global variable to store blink delay interval
unsigned long previousTimeToggled; // time of previous digitalWrite to LED_PIN
unsigned long timeNow = millis(); // current time
void setup() {
Serial.begin(115200); // initialise serial communication
Serial.setTimeout(10); // reduce from the defaul 1000 to 10ms
while (!Serial) {
continue; // wait for serial port to connect
}
pinMode(LED_PIN, OUTPUT); // set pin connected to LED as output
digitalWrite(LED_PIN, LOW); // match LEDState initialisation
previousTimeToggled = millis(); // update with current time
Serial.println("Please enter a blink delay between 100 and 4000 milliseconds.");
}
void loop() {
// check for data on the serial buffer
if (Serial.available() > 0) {
int input = Serial.parseInt();
// validate input
if ( (input >= 10) && (input <= 4000) ) {
// change the blinkInterval used in the blink loop
blinkInterval = input;
Serial.print("Received valid delay time: ");
Serial.println(input);
} else {
Serial.print("Received invalid delay time: ");
Serial.println(input);
}
Serial.println();
Serial.println("Please enter a new blink delay between 100 and 4000 milliseconds.");
}
unsigned long timeNow = millis();
// check if sufficient time has past, if true then toggle LEDState
if ((timeNow - previousTimeToggled) > blinkInterval) {
// Toggle the LED
if (LEDState == LOW) {
LEDState = HIGH;
} else {
LEDState = LOW;
}
digitalWrite(LED_PIN, LEDState);
previousTimeToggled = timeNow; // update with current time
}
}