Arduino Sketches
Get to know how sketches work, and how they are uploaded to an Arduino.
In the getting started guide (Windows, MacOS, Linux), you uploaded a sketch that blinks an LED. In this tutorial, you'll learn how each part of that sketch works.
A sketch is the name that Arduino uses for a program. It's the unit of code that is uploaded to and run on an Arduino board.
Comments
The first few lines of the Blink sketch are a comment:
1/*2
3 * Blink4
5 *6
7 * The basic Arduino example.  Turns on an LED on for one second,8
9 * then off for one second, and so on...  We use pin 13 because,10
11 * depending on your Arduino board, it has either a built-in LED12
13 * or a built-in resistor so that you need only an LED.14
15 *16
17 * http://www.arduino.cc/en/Tutorial/Blink18
19 */Everything between the
/**/*There's another style for short, single-line comments. These start with
//1int ledPin = 13;                // LED connected to digital pin 13the message "LED connected to digital pin 13" is a comment.
Variables
A variable is a place for storing a piece of data. It has a name, a type, and a value. For example, the line from the Blink sketch above declares a variable with the name
ledPinintledPinledPinOften, however, the value of a variable will change while the sketch runs. For example, you could store the value read from an input into a variable. There's more information in the Variables tutorial.
Functions
A function (otherwise known as a procedure or sub-routine) is a named piece of code that can be used from elsewhere in a sketch. For example, here's the definition of the
setup()1void setup()2{3
4  pinMode(ledPin, OUTPUT);      // sets the digital pin as output5}The first line provides information about the function, like its name, "setup". The text before and after the name specify its return type and parameters: these will be explained later. The code between the
{}You can call a function that's already been defined (either in your sketch or as part of the Arduino language). For example, the line
pinMode(ledPin, OUTPUT);pinMode()ledPinOUTPUTpinMode()pinMode(), digitalWrite(), and delay()
The
pinMode()The
digitalWrite()1digitalWrite(ledPin, HIGH);set the
ledPinThe
delay()1delay(1000);creates a delay of one second.
setup() and loop()
There are two special functions that are a part of every Arduino sketch:
setup()loop()setup()loop()Exercises
1. Change the code so that the LED is on for 100 milliseconds and off for 1000.
2. Change the code so that the LED turns on when the sketch starts and stays on.
See Also
Suggest changes
The content on docs.arduino.cc is facilitated through a public GitHub repository. If you see anything wrong, you can edit this page here.
License
The Arduino documentation is licensed under the Creative Commons Attribution-Share Alike 4.0 license.