LED blinking only when Serial Monitor is not open

Viewed 67

I have a really simple code that is not behaving how I would expect it to.

Here's the code:

int i;

void setup() {
  Serial.begin(9600);
  pinMode(13, OUTPUT);

}

void loop() {
  //digitalWrite(13, HIGH);
  i = random(1,5);
  Serial.println(i);
  digitalWrite(13, HIGH);
  delay(1000);
  digitalWrite(13, LOW);

}

With this code the LED only blinks when Serial Monitor is on and stays on while Serial Monitor is off. Another problem I have is that if I comment out the current digitalWrite(LED_BUILTIN, HIGH) and replace it with the one I have commented out then the LED wont blink even if Serial Monitor is off.

I have Arduino Micro

1 Answers

If you want to blink a LED, you need to add an extra delay when the LED is going from OFF to ON.

Currently you have:

LED ON -> wait -> LED OFF -> (instantly) LED ON -> wait etc

So what you see is just the LED continuously ON, to make it work add another delay(1000) before digitalWrite(13, HIGH) for example:

int i;
    
void setup() {
  Serial.begin(9600);
  pinMode(13, OUTPUT);
    
}
    
void loop() {
  //digitalWrite(13, HIGH);
  i = random(1,5);
  Serial.println(i);
  delay(1000);
  digitalWrite(13, HIGH);
  delay(1000);
  digitalWrite(13, LOW);
}

I tested it on my Arduino Nano and it worked fine.

Related