For this exercise, you will need
- Arduino IDE on your computer
Let’s begin!
Open the Arduino IDE. Click on New to open a new blank code. When you click on New to open a new blank code, you will get a new window with two functions: void setup() and void loop()
void setup()
- Any command you type in the void setup() function will only run once.
- Syntax:
void setup()
{
Type your command here;
}
void loop()
- Any command you type in the void loop() starts executing after void setup() is finished. The commands here will run an infinite number of times unless you specify an exit condition to it.
- Syntax:
void loop()
{
Type your command here;
}
Arduino IDE
Arduino IDE supports user-defined functions as well, apart from void setup() and void loop(), similar to other programming languages.
Example:
void switchLed(){
// led on for 1 second, led off for 1 second
digitalWrite(led, HIGH);
delay(1000)
digitalWrite(led, LOW);
delay(1000);
It looks something like this
Local and Global variables
The global variables are those variables that can be seen by every function in a program whereas local variables are only visible to the function they are declared in. Global variables are declared outside a function. This is done when a variable has to be used in multiple functions throughout the program.
int red = 10;
int yellow = 9;
int green = 8;
void setup(){
pinMode(red, OUTPUT);
pinMode(blue, OUTPUT);
pinMode(green, OUTPUT);
}
void loop(){
changeLights();
delay(1500);
}
void changeLights(){
// green off, blue on for 3 seconds
digitalWrite(green, LOW);
digitalWrite(yellow, HIGH);
delay(3000);
The output looks something like this
In the above example, the variables red, blue, and green are declared outside the function, so they are global variables.
No comments:
Post a Comment