====== Program structure ====== ===== Main loop ===== Arduino programs are called **sketches**. The source code for a sketch is stored in a text file that has a ''ino'' file extension. Arduino sketches all have the same basic structure, consisting of a ''setup'' function and a ''loop'' function. void setup() { // Stuff in here gets run once when the program starts. } void loop() { // Stuff in here gets run over and over and over again // (until you turn the power off). } Whatever you write in the body of the ''setup'' function will happen only once---when the program starts (e.g. after you power up the Arduino, press the reset button, or load a new program). Whatever you write in the body of the ''loop'' function will happen over and over as fast as the Arduino can manage until you halt the program (e.g., by removing the power, pushing the reset button, or loading a new program). ===== Blink an LED ===== Blinking an LED is the microcontroller equivalent to a "[[wp>Hello_world|Hello world]]" program in general programming. Here is how to blink an LED in Arduino: /* BlinkMe Turn an LED on and off once per second. */ void setup() { pinMode(13, OUTPUT); // make pin 13 an output } void loop() { digitalWrite(13, HIGH); // turn the LED on (HIGH is the voltage level) delay(1000); // wait one second (1000 milliseconds) digitalWrite(13, LOW); // turn the LED off by making the voltage LOW delay(1000); // wait one second } Here is the same example but using a **variable** to store the pin number. /* BlinkMe2 Turn an LED on and off once per second (improved version). */ // use variable ledPin to store the pin number that drives the LED int ledPin = 13; void setup() { pinMode(ledPin, OUTPUT); // make ledPin an output } void loop() { digitalWrite(ledPin, HIGH); // turn the LED on delay(1000); // wait one second digitalWrite(ledPin, LOW); // turn the LED off delay(1000); // wait one second } One of the advantages of using a named value for the pin number is that if we want to change the pin number we only need to change it in one place. Here we use variables also to define delay times: /* BlinkMe3 Turn an LED on and off once per second (another improved version). */ // use variable ledPin to store the pin number that drives the LED int ledPin = 13; // define the LED's on and off times in milliseconds int onTime = 1000; int offTime = 1000; void setup() { pinMode(ledPin, OUTPUT); // make ledPin an output } void loop() { digitalWrite(ledPin, HIGH); // turn the LED on delay(onTime); // wait onTime mS digitalWrite(ledPin, LOW); // turn the LED off delay(offTime); // wait offTime mS }