The code in arduino programming language submit to some simple modifications, before it pass to C/C++ compiler.
Structure of arduino language
All structures and expressions of C/C++ which is supported by compiler can be used in arduino, except the main() you can not find it. But you can find instead of it these two main fonctions : setup() and loop() , the compiler consider them as the main fonction ( main() ).
Look to the following code which represent structure of arduino language :
// define PIN name and number #define LED 11 // put your setup code here, to run once: void setup() { // adjust PIN to become output pin. pinMode(LED, OUTPUT); } // put your main code here, to run repeatedly: void loop() { // turn on the LED lamp. digitalWrite(LED, HIGH); // turning on period by milliseconds. delay(100); // turn off the LED lamp digitalWrite(LED, LOW); // turning off period delay(100); }
The setup() function is invited whenever the Arduino board is turned on, or reset by pressing the (reset) button. And it used to define variables, and adjust output/input pins, and Initializing libraries that using in code, and other things.
Pay attention!, the function setup() execute only once after powering on or resetting the arduino board (reset).
The function loop() is invited after the execution of the function setup().
The function loop() execute frequently in main program (main()). This function control the arduino board, untill turn it off or reset it by pressing the (reset button).
Code structure:
Every Arduino code must contain the following two functions:
1- setup() function :
Example : setting the serial interface, and configuring PIN 11 to be in input mode.
// define PIN. int btnPin = 11; // setup() function. void setup() { Serial.begin(9600); pinMode(btnPin, INPUT); } // loop() function. void loop() { //......... }
2- loop() function :
Example : linking the btnPin button to Pin 11, sending the “X” symbol when the button is pressed or the “Y” symbol if on a break, for 1000 milliseconds, via the serial interface.
int btnPin = 11; void setup() { Serial.begin(9600); pinMode(btnPin, INPUT); } // loop() function. void loop() { if (digitalRead(btnPin) == HIGH) Serial.write('X'); else Serial.write('Y'); delay(1000); }
Basics of Arduino Programming
The Arduino programming language is a very easy language that is free from complications and is easy to learn and enables comprehensive control of the Arduino board in a smooth manner that requires only identifying data type and its role, for example: String, Array, Char, int, void, const, define, Boolean, …etc
And identifying Operators and its role, for example:
- Arithmetic Operators
- Comparison Operators
- Boolean Operators
- Bitwise Operators
- Compound Operators
In addition, to make any device or robot by using arduino, we need some essential functions:
- pinMode()
- digitalRead()
- digitalWrite()
- analogRead()
- analogWrite()
- delay()