Sei sulla pagina 1di 41

RGB led, active buzzer and

creating a led chaser using


Arduino Uno R4
Variables in C++
A variable is a name given to a memory location. It is the basic unit of storage in

a program.

● The value stored in a variable can be changed during program execution.


● A variable is only a name given to a memory location, all the operations
done on the variable effects that memory location.
● In C++, all the variables must be declared before use.
How to declare variables?
A typical variable declaration is of the form:

// Declaring a single variable

type variable_name;

// Declaring multiple variables:

type variable1_name, variable2_name, variable3_name;

A variable name can consist of alphabets (both upper and lower case), numbers
and the underscore ‘_’ character. However, the name must not start with a number.
In the above diagram,
datatype: Type of data that can be stored in this variable.
variable_name: Name given to the variable.
value: It is the initial value stored in the variable.
Examples:

// Declaring float variable

float simpleInterest;

// Declaring integer variable

int time, speed;

// Declaring character variable

char var;
Difference between variable declaration and definition

The variable declaration refers to the part where a variable is first declared or

introduced before its first use. A variable definition is a part where the variable is

assigned a memory location and a value. Most of the times, variable declaration

and definition are done together.

See the following C++ program for better clarification:


#include <iostream>

using namespace std;

int main()

// declaration and definition

// of variable 'a123'

char a123 = 'a';

// This is also both declaration and definition

// as 'b' is allocated memory and


// assigned some garbage value.

float b;

// multiple declarations and definitions

int _c, _d45, e;

// Let us print a variable

cout << a123 << endl;

return 0;

}
Types of variables
There are three types of variables based on the scope of variables in C++:

● Local Variables
● Instance Variables
● Static Variables
1. Local Variables: A variable defined within a block or method or constructor is called local
variable.
○ These variable are created when the block is entered or the function is called and
destroyed after exiting from the block or when the call returns from the function.
○ The scope of these variables exists only within the block in which the variable is
declared. i.e. we can access these variable only within that block.
○ Initialisation of Local Variable is Mandatory.
// C++ program to demonstrate Local variables

#include <iostream>
using namespace std;

void StudentAge()
{
// local variable age
int age = 0;
age = age + 5;
cout << "Student age is : " << age;
}

// Driver code
int main()
{
StudentAge();
}
Functions in C/C++
A function is a set of statements that take inputs, do some specific computation

and produces output.

The idea is to put some commonly or repeatedly done task together and make a

function so that instead of writing the same code again and again for different

inputs, we can call the function.


#include <iostream>

using namespace std;

int max(int x, int y) {

if (x > y)

return x;

else

return y;

}
int main() {

int a = 10, b = 20;

// Calling above function to find max of 'a' and 'b'

int m = max(a, b);

cout << "m is " << m;

return 0;

Output:

m is 20
Why do we need functions?

● Functions help us in reducing code redundancy. If functionality is


performed at multiple places in software, then rather than writing the
same code, again and again, we create a function and call it everywhere.
This also helps in maintenance as we have to change at one place if we
make future changes to the functionality.
● Functions make code modular. Consider a big file having many lines of
codes. It becomes really simple to read and use the code if the code is
divided into functions.
● Functions provide abstraction. For example, we can use library functions
without worrying about their internal working.
Function Declaration
A function declaration tells the compiler about the number of parameters function
takes, data-types of parameters and return type of function. Putting parameter
names in function declaration is optional in the function declaration, but it is
necessary to put them in the definition. Below are an example of function
declarations. (parameter names are not there in below declarations)
// A function that takes two integers as parameters
// and returns an integer
int max(int, int);

// A function that takes a int pointer and an int variable as parameters


// and returns an pointer of type int
int *swap(int*,int);

// A function that takes a charas parameters


// and returns an reference variable
char *call(char b);

// A function that takes a char and an int as parameters


// and returns an integer
int fun(char, int);
It is always recommended to declare a function before it is used.

In C, we can do both declaration and definition at the same place, like done in the above example

program.

C also allows to declare and define functions separately, this is especially needed in case of library

functions. The library functions are declared in header files and defined in library files. Below is an

example declaration.

Parameter Passing to functions

The parameters passed to function are called actual parameters. For example, in the above program

10 and 20 are actual parameters.

The parameters received by function are called formal parameters. For example, in the above program

x and y are formal parameters.


There are two most popular ways to pass parameters.

Pass by Value: In this parameter passing method, values of actual parameters are copied to

function’s formal parameters and the two types of parameters are stored in different memory

locations. So any changes made inside functions are not reflected in actual parameters of

caller.

Pass by Reference Both actual and formal parameters refer to same locations, so any

changes made inside the function are actually reflected in actual parameters of caller.

In C, parameters are always passed by value. Parameters are always passed by value in C.
Following are some important points about functions in C.

1) Every C program has a function called main() that is called by operating system when a

user runs the program.

2) Every function has a return type. If a function doesn’t return any value, then void is used as

return type. Moreover, if the return type of the function is void, we still can use return

statement in the body of function definition by not specifying any constant, variable, etc. with

it, by only mentioning the ‘return;’ statement which would symbolise the termination of the

function as shown below:

void function name(int a)


{
....... //Function Body
return; //Function execution would get terminated
}
3) In C, functions can return any type except arrays and functions. We can get around this
limitation by returning pointer to array or pointer to function.

4)If in a C program, a function is called before its declaration then the C compiler
automatically assumes the declaration of that function in the following way:

int function name();

And in that case if the return type of that function is different than INT ,compiler would show
an error.
Loops in C and C++
Loops in programming comes into use when we need to repeatedly execute a block of

statements. For example: Suppose we want to print “Hello World” 10 times. This can be done

in two ways as shown below:

// C++ program to illustrate need of loops

#include <iostream>

using namespace std;

int main(){

cout << "Hello World\n";


cout << "Hello World\n";

cout << "Hello World\n";

cout << "Hello World\n";

cout << "Hello World\n";

cout << "Hello World\n";

cout << "Hello World\n";

cout << "Hello World\n";

cout << "Hello World\n";

cout << "Hello World\n";

return 0;

}
Output:
Hello World

Hello World

Hello World

Hello World

Hello World

Hello World

Hello World

Hello World

Hello World

Hello World
Using Loops
In Loop, the statement needs to be written only once and the loop will be executed 10 times
as shown below.
In computer programming, a loop is a sequence of instructions that is repeated until a
certain condition is reached.
● An operation is done, such as getting an item of data and changing it, and then
some condition is checked such as whether a counter has reached a prescribed
number.
● Counter not Reached: If the counter has not reached the desired number, the next
instruction in the sequence returns to the first instruction in the sequence and
repeat it.
● Counter reached: If the condition has been reached, the next instruction “falls
through” to the next sequential instruction or branches outside the loop.
There are mainly two types of loops:

1. Entry Controlled loops: In this type of loops the test condition is tested
before entering the loop body. For Loop and While Loop are entry
controlled loops.
2. Exit Controlled Loops: In this type of loops the test condition is tested or
evaluated at the end of loop body. Therefore, the loop body will execute
atleast once, irrespective of whether the test condition is true or false. do
– while loop is exit controlled loop.
For Loop

A for loop is a repetition control structure which allows us to write a loop that is executed a

specific number of times. The loop enables us to perform n number of steps together in one

line.

Syntax:

for (initialization expr; test expr; update expr)

// body of the loop

// statements we want to execute

}
In for loop, a loop variable is used to control the loop. First initialize this loop variable to

some value, then check whether this variable is less than or greater than counter value. If

statement is true, then loop body is executed and loop variable gets updated . Steps are

repeated till exit condition comes.

● Initialization Expression: In this expression we have to initialize the loop counter to


some value. for example: int i=1;
● Test Expression: In this expression we have to test the condition. If the condition
evaluates to true then we will execute the body of loop and go to update expression
otherwise we will exit from the for loop. For example: i <= 10;
● Update Expression: After executing loop body this expression
increments/decrements the loop variable by some value. for example: i++;
Equivalent flow diagram for loop :
// C program to illustrate for loop

#include <stdio.h>

int main(){

int i=0;

for (i = 1; i <= 10; i++)

printf( "Hello World\n");

return 0;

}
Output:
Hello World

Hello World Important Point:

Hello World ● Use for loop when number of


Hello World iterations is known beforehand, i.e.
Hello World
the number of times the loop body is
Hello World
needed to be executed is known.
Hello World

Hello World

Hello World

Hello World
Arduino Functions
digitalRead()
[Digital I/O]

Description
Reads the value from a specified digital pin, either HIGH or LOW.

Syntax
digitalRead(pin)

Parameters
pin: the Arduino pin number you want to read

Returns
HIGH or LOW

Example Code
Sets pin 13 to the same value as pin 7, declared as an input.
int ledPin = 13; // LED connected to digital pin 13

int inPin = 7; // pushbutton connected to digital pin 7 Notes and Warnings

If the pin isn’t


int val = 0; // variable to store the read value connected to
anything,
void setup() { digitalRead() can
return either HIGH
pinMode(ledPin, OUTPUT); // sets the digital pin 13 as output or LOW (and this can
change randomly).
pinMode(inPin, INPUT); // sets the digital pin 7 as input
The analog input
} pins can be used as
digital pins, referred
to as A0, A1, etc.
void loop() {
The exception is the
Arduino Nano, Pro
val = digitalRead(inPin); // read the input pin Mini, and Mini’s A6
and A7 pins, which
digitalWrite(ledPin, val); // sets the LED to the button's value can only be used as
analog inputs.
}
digitalWrite()
[Digital I/O]

Description

Write a HIGH or a LOW value to a digital pin.

If the pin has been configured as an OUTPUT with pinMode(), its voltage will be set to the
corresponding value: 5V (or 3.3V on 3.3V boards) for HIGH, 0V (ground) for LOW.

If the pin is configured as an INPUT, digitalWrite() will enable (HIGH) or disable (LOW) the
internal pullup on the input pin. It is recommended to set the pinMode() to INPUT_PULLUP to
enable the internal pull-up resistor. See the Digital Pins tutorial for more information.

If you do not set the pinMode() to OUTPUT, and connect an LED to a pin, when calling
digitalWrite(HIGH), the LED may appear dim. Without explicitly setting pinMode(), digitalWrite()
will have enabled the internal pull-up resistor, which acts like a large current-limiting resistor.
Syntax

digitalWrite(pin, value)

Parameters

pin: the Arduino pin number.

value: HIGH or LOW.

Returns

Nothing

Example Code

The code makes the digital pin 13 an OUTPUT and toggles it by alternating between HIGH and
LOW at one second pace.
void setup() {

pinMode(13, OUTPUT); // sets the digital pin 13 as output

Notes and Warnings

void loop() { The analog input pins can


be used as digital pins,
digitalWrite(13, HIGH); // sets the digital pin 13 on
referred to as A0, A1, etc.

delay(1000); // waits for a second The exception is the


Arduino Nano, Pro Mini,
digitalWrite(13, LOW); // sets the digital pin 13 off and Mini’s A6 and A7 pins,
which can only be used as
delay(1000); // waits for a second
analog inputs.
}
pinMode()
[Digital I/O]
Description

Configures the specified pin to behave either as an input or an output. See the Digital Pins page
for details on the functionality of the pins.As of Arduino 1.0.1, it is possible to enable the internal
pullup resistors with the mode INPUT_PULLUP. Additionally, the INPUT mode explicitly disables
the internal pullups.

Syntax

pinMode(pin, mode)

Parameters

pin: the Arduino pin number to set the mode of.

mode: INPUT, OUTPUT, or INPUT_PULLUP. See the Digital Pins page for a more complete
description of the functionality.

Returns

Nothing
Example Code

The code makes the digital pin 13 OUTPUT and Toggles it HIGH and LOW

void setup() {

pinMode(13, OUTPUT); // sets the digital pin 13 as output

} Notes and Warnings

The analog input pins


void loop() { can be used as digital
pins, referred to as
digitalWrite(13, HIGH); // sets the digital pin 13 on
A0, A1, etc.
delay(1000); // waits for a second

digitalWrite(13, LOW); // sets the digital pin 13 off

delay(1000); // waits for a second

}
delay()
[Time]

Description
Pauses the program for the amount of time (in milliseconds) specified as parameter.
(There are 1000 milliseconds in a second.)

Syntax
delay(ms)

Parameters
ms: the number of milliseconds to pause. Allowed data types: unsigned long.

Returns
Nothing
Example Code
The code pauses the program for one second before toggling the output pin.

int ledPin = 13; // LED connected to digital pin 13

void setup() {

pinMode(ledPin, OUTPUT); // sets the digital pin as output

void loop() {

digitalWrite(ledPin, HIGH); // sets the LED on

delay(1000); // waits for a second

digitalWrite(ledPin, LOW); // sets the LED off

delay(1000); // waits for a second

}
Notes and Warnings

While it is easy to create a blinking LED with the delay() function and many sketches use short
delays for such tasks as switch debouncing, the use of delay() in a sketch has significant
drawbacks. No other reading of sensors, mathematical calculations, or pin manipulation can go
on during the delay function, so in effect, it brings most other activity to a halt. For alternative
approaches to controlling timing see the Blink Without Delay sketch, which loops, polling the
millis() function until enough time has elapsed. More knowledgeable programmers usually avoid
the use of delay() for timing of events longer than 10’s of milliseconds unless the Arduino sketch
is very simple.

Certain things do go on while the delay() function is controlling the Atmega chip, however,
because the delay function does not disable interrupts. Serial communication that appears at the
RX pin is recorded, PWM (analogWrite) values and pin states are maintained, and interrupts will
work as they should.

Potrebbero piacerti anche