Basic of programming Programming
• In the case of Arduino, the language is based on the
C/C++
• The IDE enables you to write a computer program, which
is a set of step-by-step instructions that you then upload
to the Arduino.
• Your Arduino will then carry out those instructions and
interact with whatever you have connected to it.
• program line in C/C++ program end with semicolon ;
• The Arduino includes many basic embedded functions,
such as the :
functions for reading and writing to digital and
analog input and output pins,
interrupt functions,
mathematical functions, and
serial communication functions.
1. Arduino - Program Structure
Arduino Program (Sketch) Structure
Software structure consist of two main functions :
• Setup( ) function
• Loop( ) function
setup():
• A function present in every Arduino sketch.
• Run once before the loop() function.
• The setup() function should follow the declaration of
any variables at the very beginning of the program
• used to set pinMode or initialize serial communication.
loop():
• A function present in every single Arduino sketch.
• This code happens over and over again
• reading inputs, triggering outputs, etc.
• The loop() is where (almost) everything happens
1. Declare variables at top
2. Initialize
• setup() – run once at beginning
3. Running
• loop() – run repeatedly, after setup()
Declare variable
void setup()
{
set pins
Example of a bare minimum program:}
void loop()
{
repeatable instruction
}
Declare variables at top
2. Arduino - Data Types
• All variables have to be declared before they are used.
• Declaring a variable means defining its type.
int inputVariable;
char x;
• optionally, setting an initial value (initializing the variable).
int inputVariable = 0;
declares that variable inputVariable is of type int,
and that its initial value is zero.
Variable Types
1. char – a data type that takes up 1 byte of memory that
stores a character value. Character literals are written
in single quotes, like this: 'A’.
2. int – integers are your primary datatype for number
storage, and store a 2 byte value. This yields a range
of −32,768 to 32,767.
3. long – long variables are extended size variables for
number storage, and store 32 bits (4 bytes), from
−2,147,483,648 to 2,147,483,647.
4. double /float – datatype for floating-point numbers, a
number that has a decimal point. Floating-point
numbers can be as large as 3.4028235E+38 and as
low as −3.4028235E+38. They are stored as 32 bits (4
bytes) of information.
Example of variables:
• Char chr_a = ‘a’ ; //declaration of variable with type
char and initialize it with character a
• int counter = 32 ; // declaration of variable with
type int and initialize it with 32
• long velocity = 102346 ; //declaration of variable
with type Long and initialize it with 102346
• float num = 1.352; //declaration of variable with
type float and initialize it with 1.352
3. Arduino - Operators
1. Arithmetic Operators
Arithmetic operators include:
• addition,
• subtraction,
• multiplication, and
• division.
y = y + 3;
x = x - 7;
i = j * 6;
r = r / 5;
Example
/* Math */
Run this program. int a = 5;
int b = 10;
int c = 20;
What do you see on the Serial void setup()
Monitor?
{
Serial.begin(9600); // set up Serial library at 9600 bps
Serial.println("Here is some math: ");
Replace format “int” with Serial.print("a = ");
“float” Serial.println(a);
Serial.print("b = ");
Serial.println(b);
Serial.print("c = ");
Run this program again. Serial.println(c);
Serial.print("a + b = "); // add
What do you see on the Serial Serial.println(a + b);
Monitor?
Serial.print("a * c = "); // multiply
Serial.println(a * c);
Serial.print("c / b = "); // divide
Serial.println(c / b);
Serial.print("b - c = "); // subtract
Serial.println(b - c);
}
void loop() // we need this to be here even though its empty
{
}
2. Compound Operators
( ++ , -- , += , -= , *= , /= )
Increment or decrement a variable
X ++ // same as x = x + 1, or increments x by +1
X -- // same as x = x – 1, or decrements x by -1
X += y // same as x = x + y, or increments x by +y
X -= y // same as x = x - y, or decrements x by -y
X *= y // same as x = x * y, or multiplies x by y
X /= y // same as x = x / y, or divides x by y
Example:
x = 2; // x = 2
x += 4; // x now contains 6
x -= 3; // x now contains 3
x *= 10; // x now contains 30
x /= 2; // x now contains 15
3. Comparison operators
x == y (x is equal to y)
x != y (x is not equal to y)
x < y (x is less than y)
x > y (x is greater than y)
x <= y (x is less than or equal to y)
x >= y (x is greater than or equal to y)
4. Arduino - Control Statements
1. “if” condition
If the expression is true then the statement or block of
statements gets executed otherwise these statements
are skipped.
if (expression){
Block of statements;
}
if (someVariable > 50)
{ Expression ( comparison
operator)
// do something here
The program tests to see if someVariable is greater than
50. If it is, the program takes a particular action. If not,
the program skips over the code.
2. “if…else”
• Decision making structures require that the
programmer specify one or more conditions to be
evaluated by the program.
• It should be along with a statement or statements
to be executed if the condition is true, and, other
statements to be executed if the condition is false.
if (inputPin == HIGH)
{
doThingA;
}
else
{
doThingB;
}
3. “ If… else if …else ”
The if statement can be followed by an optional else if...else
statement, which is very useful to test various conditions using
single if...else if statement.
if (expression_1){
Block of statements;
}
else if(expression_2){
Block of statements;
}
.
.
.
else {
Block of statements;
Arduino - Loops
A loop statement allows us to execute a statement or
group of statements multiple times .
1. “for” statement
• The “for” statement is used to repeat a block of
statements enclosed in curly braces. { }
• An increment counter is usually used to increment and
terminate the loop.
• A for loop executes statements a predetermined
number of times.
• The control expression for the loop is initialized,
tested and manipulated entirely within the for loop
parentheses
• Each for loop has up to three expressions, which
determine its operation. Notice that the three
expressions in the for loop argument parentheses are
separated with semicolons.
for (initialization; condition; increment)
{
//statement(s);
}
for (initialization; condition; increment)
{
//statement(s);
}
1. The “initialization” happens first and exactly once.
2. Each time through the loop, the “condition” is
tested; if it's true:
1. the “statement” block, and
2. the “increment” is executed,
3. then the “condition” is tested again.
4. When the “condition” becomes false, the loop ends.
Example “Dim an LED using a PWM pin”:
int PWMpin = 10; // LED in series with 1k resistor on pin 10
void setup()
{
initialization
// no setup needed
} condition
increment
void loop()
{
for (int i=0; i <= 255; i++)
{
analogWrite(PWMpin, i); statement
delay(10);
}
}
2. “while” loop
• while loops will loop continuously, and infinitely, until
the expression inside the parenthesis, () becomes false.
• Something must change the tested variable, or the
while loop will never exit.
• This could be in your code, such as an incremented
variable, or an external condition, such as testing a
sensor.
while(someVariable ?? value)
{
doSomething;
}
Example:
int button2Pin = 2;
buttonState = LOW;
while(buttonState == LOW)
buttonState = digitalRead(button2Pin);
}
3. “do … while” loop
The “do” loop works in the same manner as the “while”
loop, with the exception that the condition is tested at
the end of the loop, so the “do” loop will always run at
least once
do
{
doSomething;
}
while (someVariable ??
value);
Example:
do
{
x = readSensor();
delay(10);
}
while (x < 100); // loops if x < 100
Arduino - Digital I/O Functions
1. pinMode(pin, mode)
Before we use a port, we need to inform the controller
about how it should operate.
2. digitalWrite(pin, value)
Once a pin is established as an OUTPUT, it is then possible
to turn that pin on or off using the digitalWrite() function.
3. digitalRead(pin)
With a digital pin configured as an INPUT, we can
read the state of that pin using the digitalRead()
function.
Arduino - Analog I/O Functions
1. analogRead(pin)
• This function works with the above analogy only for pins
(A0–A5).
• analogy pins unlike digital ones, do not need to be first
declared as INPUT nor OUTPUT.
• Reads the value from a specified analog pin with a 10-bit
resolution. will return a number including or between 0
and 1023
2. analogWrite(pin,value)
• The Arduino also has the capability to output an Analog
signal, this signal is called pulse width modulation
(PWM).
• Digital Pins # 3, # 5, # 6, # 9, # 10, and # 11 have
PWM capabilities.
• You do not need to call pinMode() to set the pin as an
output before calling analogWrite()
• Can be used to light a LED at varying brightnesses or
drive a motor at various speeds.
Arduino - Timer Functions
1.delay(ms)
Pauses the program for the amount of time (in
milliseconds) specified as the parameter.
• Lots of useful functions
pinMode() – set a pin as input or output
digitalWrite() – set a digital pin high/low
digitalRead() – read a digital pin’s state
analogRead() – read an analog pin
analogWrite() – write an “analog” PWM value
delay() – wait an amount of time (ms)
• And many others. And libraries. And
examples!
Arduino - Communication Functions
1. Serial.begin(speed) initializes serial monitor. the typical
speed is 9600.
2. Serial.read() Reads incoming serial data.
3. Serial.print(val) Prints data to the serial port (monitor)
4. Serial.printIn(val,format) Prints data to the serial port
(monitor) followed by a new line
Arduino - Math Functions
The Arduino language supports many math functions which
make it possible to perform sophisticated data processing
1.min(x,y) Calculates the minimum of two numbers
2.max(x,y) Calculates the maximum of two numbers.
3.abs(x) Computes the absolute value of a number
4.pow(base,exponent) Calculates the value of a number
raised to a power.
5.sqrt(x) Calculates the square root of a number.
6.map(value,fromLow,fromHigh,toLow,toHigh) Remaps a
number from one range to another. That is, a value of
fromLow would be mapped to toLow, a value of fromHigh to
toHigh, values in-between to values in-between, etc.