ARDUINO Syntax PDF
ARDUINO Syntax PDF
SYNTAX
IF statements In Arduino
• The if statement checks for a condition and executes the following statement or set of statements if the condition is 'true'.
•
Syntax
• if (condition) {
• //statement(s)
• }
•
if (x > 120) digitalWrite(LEDpin, HIGH);
•
if (x > 120)
• digitalWrite(LEDpin, HIGH);
•
if (x > 120) {digitalWrite(LEDpin, HIGH);}
•
if (x > 120) {
• digitalWrite(LEDpin1, HIGH);
• digitalWrite(LEDpin2, HIGH);
• }
IF-ELSE Statement ARDUINO
• The if…else allows the program to take action whether the condition is met or otherwise. An else clause will be executed if the condition in the if
statement results in false.
• Syntax
• if (condition1) {
• // do Thing A
• }
• else {
• // do Thing B
• }
• Example Code
• if (temperature >= 70) {
• // Danger! Shut down the system.
• :
• }
• else { // temperature < 70
• // Safe! Continue usual tasks.
• :
• }
The if…elseif...else allows greater control over the flow of code than the basic if statement, by allowing multiple tests to be grouped.
Example Code
if (temperature >= 70) {
// Danger! Shut down the system.
• :
Syntax }
• if (condition1) { else if (temperature >= 60) { // 60
• // do Thing A <= temperature < 70
• } // Warning! User attention
• else if (condition2) { required.
• // do Thing B :
• }
• else { }
• // do Thing C else { // temperature < 60
• } // Safe! Continue usual tasks.
:
}
• SWITCH-CASE in Arduino
Creating an Array
All of the methods below are valid ways to create (declare) an array.
int myInts[6]; // elements not mentioned
int myPins[] = {2, 4, 8, 3, 6}; // size not mentioned
int mySensVals[5] = {2, 4, -8, 3, 2}; // both elements and size given
char message[6] = "hello"; // an extra character for null
• Accessing an Array
• Arrays are zero indexed, that is, referring to the array initialization above, the first element of the array is at index 0, hence
• It also means that in an array with ten elements, index nine is the last element. Hence
• int myArray[10]={9, 3, 2, 4, 3, 2, 7, 8, 9, 11};
• // myArray[9] contains 11
• // myArray[10] is invalid and contains random information (other memory address)
LED ARRAY CIRCUIT-2
• int LedArray [] = {13, 11, 8, 3};
• void setup(){
• for (int i = 0; i < 4; i++)
• { pinMode(LedArray[i], OUTPUT);
• }
• }
•
void loop() {
• for (int i = 0; i < 4; i++)
• {
• digitalWrite(LedArray[i], HIGH);
• // LEDs turn on one by one
• delay(500);
• }
• for (int i = 3; i >= 0; i--)
• {
• digitalWrite(LedArray[i], LOW);
• // LEDs turn off one by one
• delay(500);
• }
• }
Code to display a message on the LCD