Using the Delay() Function and Auto Format

One of the ways of adjusting the timing flow in a sketch is with the Delay() function.

Usually, if a command has a () after it, it is a function. The delay() function is built into the Arduino IDE.

You can look up the details for the delay() function in the reference page. When the delay() function is encountered in the sketch, the program is halted and sits there, waiting for the specified number of milliseconds inside the ().  For example, delay(500) will cause the microcontroller to sit and wait for 500 milliseconds, or 1/2 a second.

This is one way of controlling the timing flow of a sketch. For example, if we want to turn the LED on and wait 1 second and then turn it off, we can insert a delay(1000); line after we turn on the LED. Then we turn the LED off, wait 1 second and then go back to the top. Here is what the code would look like:

void setup() {
  // put your setup code here, to run once:
pinMode(13,OUPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
digitalWrite(13,HIGH);
delay(500);
digitalWrite(13,LOW);
delay(500);
}


 

As this is written, its not very easy to read. There is a trick we can do to format the code to make it easier to read. Under the menu Tools, we select Auto Format, as in the figure below:

image

Using the command will re-organize the code, as shown below:

void setup() {
  // put your setup code here, to run once:
  pinMode(13, OUTPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
  digitalWrite(13, HIGH);
  delay(500);
  digitalWrite(13, LOW);
  delay(500);
}

When you run this code, the LED on board will flash off and on every second.

You can literally, copy this code from this web page and paste it into a blank sketch and run it. Try it.

Try these experiments:

  1. How short an on time can you see?
  2. How short an off time can you see?
  3. How fast an off-on-off-on cycle can you see as blinking or as apparently always on.