0% found this document useful (0 votes)
300 views68 pages

Arduino-LED Programming (Switch-Case, If-Else, Loop, Function)

The document discusses various Arduino programming concepts including switch case statements, if-else statements, loops (while, do-while, for), functions, and arrays. It provides examples of using these concepts to control LEDs by turning them on and off based on serial input characters or in sequences. Code examples are given to demonstrate switch cases, loops, and arrays for lighting up LEDs individually, in sequences forwards and backwards, and in patterns. The document is intended to teach these basic Arduino programming structures and how to apply them.

Uploaded by

nitinsomanathan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
300 views68 pages

Arduino-LED Programming (Switch-Case, If-Else, Loop, Function)

The document discusses various Arduino programming concepts including switch case statements, if-else statements, loops (while, do-while, for), functions, and arrays. It provides examples of using these concepts to control LEDs by turning them on and off based on serial input characters or in sequences. Code examples are given to demonstrate switch cases, loops, and arrays for lighting up LEDs individually, in sequences forwards and backwards, and in patterns. The document is intended to teach these basic Arduino programming structures and how to apply them.

Uploaded by

nitinsomanathan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 68

Arduino- LED Programming

(Switch-Case,If-else, loop,Function)
Arduino switch case
❑ The switch case controls the flow of the program by
executing the code in various cases. A switch statement
compares a particular value of a variable with statements
in other cases. When the statements in a case matches
the value of a variable, the code associated with that
case executes.
❑ The break keyword is used at the end of each case. For
example, if there are five cases, the break statements will
also be five. The break statement exits the switch case.
❑ The switch statement without a break will continue to
execute all the cases until the end. Hence, it is essential
to include a break statement at the end of each case.
Let's understand with an example.
switch(variable)
{
case 1:
// statements related to case1
break;
case 2:
// statements related to case2
break;
.
.
case n:
// statements related to case n
break;
default:
break;
}
default:
break;
}
where,
variable: It includes the variables whose value will be
compared with the multiple cases
value: It consists of a value to compare. These values
are constants. The allowed data types
are int and char.
Consider the below flowchart:
EXP 1- Open the Serial monitor and send any
character. The characters a, b, c, d, e and f will
turn on LEDs. Any other character will turn the
LEDs off
Components Required:-
❑Arduino Board
❑6 X 220 ohm resistors
❑6 X LEDs
❑Jumpers
❑breadboard
Circuit
CODING
void setup()
{
Serial.begin(9600);
for (int thisPin = 2; thisPin < 8; thisPin++)
{
pinMode(thisPin, OUTPUT);
}
}
void loop()
{
if (Serial.available() > 0)
{
int inByte = Serial.read();
switch (inByte) {
case 'a':
digitalWrite(2, HIGH);
break;
case 'b':
digitalWrite(3, HIGH);
break;
case 'c':
digitalWrite(4, HIGH);
break;
case 'd':
digitalWrite(5, HIGH);
break;
case 'e':
digitalWrite(6, HIGH);
break;
case ‘f':
digitalWrite(7, HIGH);
break;
default:
for (int thisPin = 2; thisPin < 8; thisPin++)
{
digitalWrite(thisPin, LOW);
}}}}
The Arduino while and do
while Loops
while Loop Structure
The while loop has a structure as follows:
while (loop test expression goes here)
{
Statements that run in the loop go here
Statement 1
Statement 2 ...
}
The while loop starts with the while keyword followed by a test expression
between opening and closing parentheses. Opening and closing braces
denote the body of the loop.
The do while Loop
The do while loop works in the same way as the while loop, except that
it always runs once even if the test expression evaluates to false.
do while Loop Structure
The do while loop consists of two keywords do and while, as shown
below.
do {
Statements that run in the loop go here
Statement 1
Statement 2 ...
}
while (test expression goes here);
The body of the do while loop falls between opening and closing
braces and contains statements that are to be run in the loop.
The while keyword and test expression come after the body of the
loop and are terminated by a semicolon (;).
Arduino While loop example 1
through 10

❑ By moving the iterator (i++) you can change the output as


a sequence from 1 to 10 - this is easier than the for loop
logic as you don't need to think of the conditional i.e.
should it be >=10, <11 etc.
void setup ()
{
int i=0;
Serial.begin(9600);
Serial.println("Arduino while loop");
while(i<10)
{
i++;
Serial.println(i);
}}
void loop()
{}
Arduino example of the Do while
loop
Here the condition is tested at the end so the main body of code is
always executed once.

void setup () {
int i=0;
Serial.begin(9600);
Serial.println("Arduino do while loop");
do
{
i++;
Serial.println(i);
}
while(i<10);
}
void loop()
{}
Arduino - for Loop
❑ The statements inside the curly brackets under for loop
are executed repeatedly according to the specified
condition. An increment counter in the for loop is used to
increment or decrement the loop repetitions.

❑ The for statement is commonly used for repetitive task or


operation or to operate on the group of data/pins in
combination with arrays.
The syntax is:
for (initialization; condition; increment)
{
\\ statements
}
where,
initialization: It is defined as the initialization of the
variable.
condition: The condition is tested on every execution. If
the condition is true, it will execute the given task. The
loop ends only when the condition becomes false.
increment: It includes the increment operator, such as i +
+, i - - , i + =1, i-=1 , etc. It is incremented each time until
the condition remains true.
To print a message 'Arduino' 15
times.
To print a message 15 times or more is quite complicated using Serial.println (
), as the code will become too lengthy.

To overcome this, programmers prefer to use for loop to execute a task multiple
times, while using a single statement.

Let's consider the below code.

int i;

void setup ( )

Serial.begin(9600);

for ( i = 0 ; i < 15 ; i ++ )

Serial.println( "Arduino"); } }
void loop ( ) {
}
❑OUTPUT:-
Exp 1- Light multiple LEDs in
sequence, then in reverse using For
Loop Iteration
Components Required:-
❑Arduino Board
❑6 X 220 ohm resistors
❑6 X LEDs
❑Jumpers
❑breadboard
Circuit
CODING
int t = 100;
void setup()
{
for (int i = 2; i <=7; i++)
{
pinMode(i, OUTPUT);
}
}
void loop() {
for (int i = 2; i <=7; i++)
{
digitalWrite(i, HIGH);
delay(t);
digitalWrite(i, LOW);
}
for (int i = 7; i >= 2; i--)
{
digitalWrite(i, HIGH);
delay(t);
digitalWrite(i, LOW);
}
}
Exp 2- Light multiple LEDs in odd
sequence, then in reverse using For
Loop Iteration
CODING
int t = 100;
void setup()
{
for (int i = 2; i <=7; i++)
{
pinMode(i, OUTPUT);
}
}
void loop() {
for(int i=2; i<=7; i=i+2) {
digitalWrite(i,HIGH);
delay(100);
digitalWrite(i,LOW);
}
for(int i=7; i>=2; i=i-2)
{
digitalWrite(i,HIGH);
delay(100);
digitalWrite(i,LOW);
}
Exp 3- Light multiple LEDs in
patterns using For Loop Iteration
CODING
void setup()
{
pinMode(2, OUTPUT);
pinMode(3, OUTPUT);
pinMode(4, OUTPUT);
pinMode(5, OUTPUT);
pinMode(6, OUTPUT);
pinMode(7, OUTPUT);
}
void loop()
{
for( int i = 0; i < 1; i = i +1 ) {
digitalWrite(2, HIGH);
delay(1000);
digitalWrite(2, LOW);
delay(1000);
}
for( int i = 0; i < 2; i = i +1 )
{
digitalWrite(3, HIGH);
delay(500); // the duration is 0.5 seconds
digitalWrite(3, LOW);
delay(500);
}
for( int i = 0; i < 3; i = i +1 )
{
digitalWrite(4, HIGH);
delay(500);
digitalWrite(4, LOW);
delay(500);
}
for( int i = 0; i < 4; i = i +1 )
{
digitalWrite(5, HIGH);
delay(500);
digitalWrite(5, LOW);
delay(500);
}

for( int i = 0; i < 5; i = i +1 )


{
digitalWrite(6, HIGH);
delay(500);
digitalWrite(6, LOW);
delay(500);
}
for( int i = 0; i <6; i = i +1 )
{
digitalWrite(7, HIGH);
delay(500);
digitalWrite(7, LOW);
delay(500);
}}
HOW TO USE ARRAYS WITH
ARDUINO
What are Arrays?
❑ The arrays are defined as the data structures that allow multiple
values of same type to be grouped together in a contiguous way.
This is an easily access method.

❑ The array is normally built from the data types like integer, real,
characters, and boolean. It refers to a named list of finite number
(n) of similar data elements.

❑ The set of consecutive numbers usually represent the elements in


the array, which are 0, 1, 2, 3, 4, 5, 6,.......n.
❑ For example, if the name of an array of 5 elements is AR, the
elements will be referenced as shown below:
AR[0], AR[1], AR[2], AR[3], and AR[4]
Arrays in Arduino
❑ In the below figure, the array in Arduino is declared with the integer
data type.
❑ It is also defined as the collection of variables, which is acquired with
an index number.
❑ The array is represented as:

We can specify any name according to our choice. The array name is
the individual name of an element.
ARRAY DECLARATION
There are different methods to declare an array in Arduino, which are
listed below:

We can declare the array without specifying the size.

For example,

❑ int myarray[ ] = { 1, 4, 6, 7 } ;

We can declare the array without initializing its elements.

For example,

❑ int myarray[ 5];

We can declare the array by initializing the size and elements.

❑ int myarray[ 8] = { 1, 4, 7, 9, 3, 2 , 4};


FEATURES OF ARRAY
The elements of the array can be characters, negative numbers, etc.

For example,

❑ int myarray[ 4 ] = { 1, -3, 4};

❑ char myarray[ 6] = " Hi " ;

The size of the array should not be less than the number of elements.
For example,

❑ int myarray[5 ] = { 1, 4, 6, 7 } ; can be written as int myarray[8 ] = {


1, 4, 6, 7 } ;

But, it cannot be written as int myarray[ 2] = { 1, 4, 6, 7 } ;


Using Arrays
The sketch below shows the basic use of an array.
void setup() {
int my_array[5];
int i;
Serial.begin(9600);
my_array[0] = 23;
my_array[1] = 1001;
my_array[2] = 9;
my_array[3] = 1234;
my_array[4] = 987;
for (i = 0; i < 5; i++) {
Serial.println(my_array[i]);
}
}
void loop() {
}
EXP 1- Turn the LED’s on and off
for 1 second using Arrays
Components Required:-
❑1x Breadboard

❑1x Arduino Uno

❑4x LEDs

❑4x 220Ω Resistors

❑9x Jumper Wires


Circuit
int ledPins[] = { 2, 7, 10, 11};
int c = 4;
void setup() {
for (int i = 0; i < c; i++) {
pinMode(ledPins[i], OUTPUT);
}
void loop() {
for (int i = 0; i < c; i++) {
digitalWrite(ledPins[i], HIGH);
}
delay(1000);
for (int i = 0; i < c; i++) {
digitalWrite(ledPins[i], LOW);
}
delay(1000);
}
EXP 2- Turn the LED’s on and off
one by one going left to right using
Arrays
int t = 500;
int ledPins[] = {2,7,10,11};
int c = sizeof(ledPins)/sizeof(int);
void setup() {
for (int i = 0; i < c; i++) {
pinMode(ledPins[i], OUTPUT);
}
}
void loop() {
for (int i = 0; i < c; i++)
{
digitalWrite(ledPins[i], HIGH);
delay(t);
}
for (int i = 0; i < c; i++)
{
digitalWrite(ledPins[i], LOW);
delay(t);
}}
EXP 3-Run Patterns on LEDs connect at
Pins 2,7,10,11. Pattern Example:
1000 0100 0010 0001 1100 0110 0011
CODING
int led[4]={2,7,10,11},i,j;
void setup()
{
for(i=0;i<4;i++)
pinMode(led[i],OUTPUT);
}
void loop()
{
for(i=0;i<2;i++)
{
if(i==0)
for(j=0;j<=3;j++)
{
digitalWrite(led[j],HIGH);
delay(500);
digitalWrite(led[j],LOW);
delay(500);
}
else
{
for(j=0;j<=2;j++)
{
digitalWrite(led[j],HIGH);
digitalWrite(led[j+1],HIGH);
delay(500);
digitalWrite(led[j],LOW);
digitalWrite(led[j+1],LOW);
delay(500);
}
delay(500);
}
}
}
Arduino Functions
❑ The functions allow a programmer to divide a specific
code into various sections, and each section performs a
particular task. The functions are created to perform a
task multiple times in a program.
❑ The function is a type of procedure that returns the area
of code from which it is called.
❑ For example, to repeat a task multiple times in code, we
can use the same set of statements every time the task is
performed.
Advantages of using Functions
Let's discuss some advantages of using functions in
programming, which are listed below:
❑ It increases the readability of the code.
❑ It conceives and organizes the program.
❑ It reduces the chances of errors.
❑ It makes the program compact and small.
❑ It avoids the repetition of the set of statements or codes.
❑ It allows us to divide a complex code or program into a
simpler one.
❑ The modification becomes easier with the help of
functions in a program.
❑The Arduino has two common
functions setup() and loop(), which are called
automatically in the background. The code to be
executed is written inside the curly braces within
these functions.
❑void setup() - It includes the initial part of the code,
which is executed only once. It is called as
the preparation block.
❑void loop() - It includes the statements, which are
executed repeatedly. It is called the execution
block.
❑But sometimes, we need to write our own functions.
Function Declaration
.The method to declare a function is listed below:
❑ Function return type
We need a return type for a function. For example, we can store
the return value of a function in a variable.
We can use any data type as a return type, such as float, char,
etc.
❑ Function name
It consists of a name specified to the function. It represents the
real body of the function.
❑ Function parameter
It includes the parameters passed to the function. The
parameters are defined as the special variables, which are
used to pass data to a function.
The function must be followed by parentheses ( ) and
the semicolon ;
The actual data passed to the function is termed as an
argument.
Let's understand with some examples.
Example 1:
Consider the below image:
Example 2: Here, we will add two
numbers.
Consider the below code:
void setup()
{
Serial.begin(9600);
}
void loop() {
int a = 5;
int b = 4;
int c;
c = myAddfunction(a, b);
Serial.println(c);
delay(1000);
}
int myAddfunction(int i, int j)
{
int sum;
sum = i + j;
return sum;
}
❑ Similarly, we can perform arithmetic operations using the above concept.
EXP 1- To blink led one by
one using functions
CIRCUIT
CODING
int ledPins[] = {2,3,4};

void setup()

for(int i = 0; i < 3; i++){

pinMode(ledPins[i],OUTPUT);

}
void loop()
{
control_led();
}
void control_led()
{
int delayTime = 2000;
digitalWrite(ledPins[0], HIGH);
delay(delayTime);
digitalWrite(ledPins[1], HIGH);
delay(delayTime);
digitalWrite(ledPins[2], HIGH);
delay(delayTime);
digitalWrite(ledPins[2], LOW);

delay(delayTime);

digitalWrite(ledPins[1], LOW);

delay(delayTime);

digitalWrite(ledPins[0], LOW);

delay(delayTime);

}
EXP 2- To glow LED’s in
patterns using functions
CIRCUIT
CODING
int ledPins[] = {2,3,4};
int pattern1[] = {HIGH,HIGH,LOW};
int pattern2[] = {LOW,HIGH,HIGH};
int pattern3[] = {HIGH,LOW,HIGH};

void setup()
{

for(int i = 0; i < 3; i++)


{
pinMode(ledPins[i],OUTPUT);
}
}
void loop()
{
makePattern(ledPins, pattern1, 3);
makePattern(ledPins, pattern2, 3);
makePattern(ledPins, pattern3, 3);
}

void makePattern(int leds[], int pattern[], int num)


{
int delayTime = 1000;
for(int i = 0; i < num; i++)
{
digitalWrite(leds[i], pattern[i]);
}
delay(delayTime);
}
Arduino- Strings
❑ Strings are used to store text. They can be used to display text on an
LCD or in the Arduino IDE Serial Monitor window. Strings are also
useful for storing the user input. For example, the characters that a
user types on a keypad connected to the Arduino.

There are two types of strings in Arduino programming −

❑ Arrays of characters, which are the same as the strings used in C


programming.

❑ The Arduino String, which lets us use a string object in a sketch.


String Character Arrays

❑ The first type of string that we will learn is the string that is a series of
characters of the type char.

❑ A string is an array of char variables.

❑ A string is a special array that has one extra element at the end of
the string, which always has the value of 0 (zero). This is known as a
"null terminated string".
String Character Array Example
This example will show how to make a string and print it to the serial
monitor window.
Example
void setup() {
char my_str[6];
Serial.begin(9600);
my_str[0] = 'H';
my_str[1] = 'e';
my_str[2] = 'l';
my_str[3] = 'l';
my_str[4] = 'o';
my_str[5] = ‘\0’;
Serial.println(my_str); }
void loop() { }
❑ The following example shows what a string is made up of; a
character array with printable characters and 0 as the last element of
the array to show that this is where the string ends.

❑ The string can be printed out to the Arduino IDE Serial Monitor
window by using Serial.println() and passing the name of the string.
This same example can be written in a more convenient way as shown below −
Example
void setup()
{
char my_str[] = "Hello";
Serial.begin(9600);
Serial.println(my_str); }
void loop()
{}
❑ In this sketch, the compiler calculates the size of the string array and also
automatically null terminates the string with a zero. An array that is six elements
long and consists of five characters followed by a zero is created exactly the
same way as in the previous sketch.
EXP 1- Serial.readString() function code to
loop-back from PC (serial monitor).
CODING
void setup()
{
Serial.begin(9600); // Set the baud rate to 9600
}
void loop()
{
String s1 = Serial.readString();// s1 is String type variable.
Serial.print("Received Data => ");
Serial.println(s1);//display same received Data back in serial
monitor.
delay(500);
}
EXP 2- Serial.readString() function code on
the LED on pin 13 when you send “on”
and turn off the LED when you send “off”.
CIRCUIT
CODING
void setup()
{
Serial.begin(9600); // Set the baud rate to 9600
pinMode(13,OUTPUT);
}
void loop()
{
String s1 = Serial.readString();// s1 is String type variable.
Serial.print("Received Data => ");
Serial.println(s1);//display same received Data back in serial monitor.
if(s1.indexOf("on")>=0)
{
digitalWrite(13,HIGH);
}
if(s1.indexOf("off")>=0){
digitalWrite(13,LOW);
}
delay(100);
}

You might also like