SunFounder 3in1 Kit
2.3.7 Variable
The variable is one of the most powerful and critical tools in a program. It helps us to store and call data in our programs.
The following sketch file uses variables. It stores the pin numbers of the on-board LED in the variable ledPin and a
number “500” in the variable delayTime.
int ledPin = 13;
int delayTime = 500;
void setup() {
pinMode(ledPin,OUTPUT);
}
void loop() {
digitalWrite(ledPin,HIGH);
delay(delayTime);
digitalWrite(ledPin,LOW);
delay(delayTime);
}
Wait, is this a duplicate of what #define does? The answer is NO.
• The role of #define is to simply and directly replace text, it is not considered by the compiler as part of the
program.
• A variable, on the other hand, exists within the program and is used to store and call value. A variable can
also modify its value within the program, something that a define cannot do.
The sketch file below self-adds to the variable and it will cause the on-board LED to blink longer after each blink.
int ledPin = 13;
int delayTime = 500;
void setup() {
pinMode(ledPin,OUTPUT);
}
void loop() {
digitalWrite(ledPin,HIGH);
delay(delayTime);
digitalWrite(ledPin,LOW);
delay(delayTime);
delayTime = delayTime+200; //Each execution increments the value by 200
}
74 Chapter 2. Get Started with Arduino