You are on page 1of 35

Unit 3

Arduino Programming
Structuring an Arduino Program
• Program for Arduino are usually refereed to as
sketches.
• Sketches contain code.
• Code that needs to run only once should be
placed in the setup function
• Code to be run continuously into the loop
function.
Structuring an Arduino Program
const int ledPin = 13;
void setup()
{
pinMode(ledPin, OUTPUT); // initialize the digital pin as an output

}
void loop()
{
digitalWrite(ledPin, HIGH); // turn the LED on

delay(1000); // wait a second

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

delay(1000); // wait a second

}
Structuring an Arduino Program
• When the board finishes uploading the code , it
starts at top of the sketch and carries out the
instructions sequentially.
• It runs the code in setup once and goes through
the code in loop.
• When it gets to the end of loop , it goes back to
the beginning of the loop.
Variables in Arduino
• Arduino has different types of variables to represent values.

int 2 bytes represents positive and


negative integer values.
unsigned int 2 bytes represents only positive integer
values.
long 4 bytes represents very large range of
positive and negative values.
unsigned long 4 bytes represents very large range of
positive values
Arduino data types
float 4 bytes represents number with fractions
boolean 1 byte represents true and false values.
boolean value = true;
char 1 byte represents a single character. Can also
represent signed value between - 128 to +127
byte 1 byte represents a single character, but represents
unsigned values. Range 0 to 255.
Other types
String represents an array of characters
char str[] = "Hello World!";
String str="Hello World!";
void used only in function declarations where no value is returned.
int and float data types in Arduino
Example 02 : Temperature sensor
int sensorpin = A0;
void setup()
{
Serial.begin(9600);

void loop()
{
float reading = analogRead(sensorpin);
float tempC = reading/1024;
tempC = tempC*5.0;
tempC = tempC-0.5;
tempC = tempC*100;

Serial.print(tempC);
Serial.println(" degree cel");

}
Working with group of values
• You can create and use a group of values called
arrays.
• The arrays is a simple list or two or more
dimensions.
• Another use of array is to hold string of text
characters.
• A character string consists of one or more
characters, followed by null character to
indicate end of the string.
• You want to how to determine size of the array
Array in Arduino
This array creates two arrays: an array of integers for pins connected to switches and array of
pins connected to LED’s

void loop()
{
for(int i = 0; i < 4; i++)
Int inputPins [] = {2,3,4,5};
{
int ledPins[] = {10,11,12,13}; Int val = digitalRead(inputPins[i]);

void setup() if (val == HIGH)


{ {
for(int i = 0; i < 4; i++)
digitalWrite(ledPins[i], HIGH);
{
}
pinMode(ledPins[i], OUTPUT);
else
pinMode(inputPins[i], INPUT); {
digitalWrite(inputPins[i],LOW); digitalWrite(ledPins[i], LOW);
} }
}
}
}
Array
Monday, 07,Mar22

Boolean data type


• A boolean holds one of two values, true or
false.
• Each boolean variable occupies one byte of
memory.
Example:
boolean run = true;
Boolean data type
int LEDpin = 5;
int switchPin = 13;
boolean running = false;
void setup()
{
pinMode(LEDpin, OUTPUT);
pinMode(switchPin, INPUT);
digitalWrite(switchPin, LOW);
}
void loop()
{
if(digitalRead(switchPin) == HIGH)
{
delay(100);
running = !running;
digitalWrite(LEDpin, running);
}
}
Using Mathematical operators
You perform simple math on values in your sketch.
addition operator (+): int x = x + 1; OR int x += 1;
subtraction operator (-): int x = x -1; OR int x -= 1;
multiplication operator (*): int x = x*1; OR int x*=1;
division operator (/): int x = x/1; OR int x/=1;
(order of every operator is well defined- PEMDAS. Operation inside parentheses are
executed first then exponents then multiplication and division then addition and
subtraction. )

you want to increase or decrease the value of a variable.

myValue += 1;
myValue -= 1;
myValue += 5;
Using Mathematical operators
The Arduino has built in functions for calculating the cosine, sine, and tangent of an angle(in radian)

float a = cos(b);
float a = sin(b);
float a = tan(b);

The Arduino also has a function for calculating the square of a number.
float x = sq(y);

To calculate the square root of a number, use the square root function. This calculates the square root
of y
float x = sqrt(y);

you get a random number. calling random with two parameters set the lower and
upper bounds. the values returned will range from the lower bound to one less than upper bound

Random(0.10);
Using Mathematical operators
The power function calculates the value of a base raised to the power of an
exponent (yx)
int x = pow(base, exponent);

The min() function calculates the minimum value of any two numbers:
int x = min(a, b);

The max() function calculates the maximum value of any two numbers:
int x = max(a, b);

Min and max are useful for keeping values above or below a certain
threshold.For example, say you want to make sure the reading from a
myvalue never exceeds 200 . You could use the min() function like this:
sens_val = min(myvalue,200);

The Arduino has another operator that deals with division called modulus.
you want to find remainder after you divide two values.
int x = a % b;

Another useful Arduino function is the absolute value function. The absolute value
function returns the positive value of a negative number.
int x = abs(-10);
Arduino trigonometric functions
float deg = 45;
float rad = 0;
const float pi = 3.1415;
float a = 0; void loop()
float b = 0; {
float c = 0;
}
void setup()
{
Serial.begin(9600);
float rad = radian(deg);
Serial.print(rad);
float radian(float deg)
Serial.println(“radians”); {
float a = sin(rad);
Serial.print(a); return(deg/360*2*pi);
Serial.println(“sine value”);
}
float b = cos(rad);
Serial.print(b);
Serial.print(“cosine value”);
float c = tan(rad);
Serial.print( c ); float degree(float rad)
Serial.print(“tangent value”);
{
float deg = degree(rad); return(rad/2/pi*360);
Serial.print(deg);
Serial.println(“degrees”); }
}
Arduino String Functionality
• Text is stored in arrays of characters called strings.
• Arduino has capability for using String that can store and manipulate text strings.

void setup() {
String text1 = "SYBTECH";
String text2 = "DIV A";
String text3;
Serial.begin(9600);

text3 = text1 + " CSE " + text2;


Serial.println(text3);

void loop(){
}
int length = 0;
Arduino String Functionality char val1 [] = "Arduino" ;
Using C Character Strings char val2[10];
C language does not support Arduino style String capability, so you char val3[] = "Welcome to " ;
want to understand code written to operate with character arrays.
Arrays of characters are sometimes called character strings. void setup() {
You declare string like Serial.begin(9600);
char name[8];
Declare a string up to 7 characters plus terminating null. length = strlen(val1);
char name[8]=“Arduino”; Serial.println(length);
Initialize the string to Arduino
char name[18]=“Arduino”;
if(strcmp(val1, "Arduino“ ) == 0)
Initialize the string to Arduino but string has room to grow.
{
char name[]=“Arduino”;
Serial.println("both the string are
Compiler initialize the string and calculate size. equal");
}
strlen: determine the number of characters before null else
int length = strlen(string); {
strcpy to copy one string to another Serial.println("strings are unequal");
strcpy(destination, source); }}
strcat to append one string to the end of another. void loop()
strcat(destination, source); {}
// append source string to the end of the
destination string
strcmp: it compare two strings
if(strcmp(str, "Arduino") == 0)
Repeating a Sequence of Statements
while loop
do –while loop
for loop
break
Repeating a Sequence of Statements
while loop while loop
A while loop repeats one or more int a = 0;
instructions while an expression is true. void setup()
{
Serial.begin(9600);
int var =0; while( a < 5)
while(var < 100) {
Serial.println("Welcome to Arduino");
{
var++;
a = a + 1;
} }
}
This code will execute statements in the void loop()
block within the brackets, while the {
value of var is less than 100. }
The value of var skip incrementing when
the var value is grater than or equal to
100.
Repeating a Sequence of Statements
do-while loop
In do while condition is tested at the end of the loop, so the do loop will
always run at least once.

do
{
flashLED();
// call a function to turn an LED on and off
}
while (analogRead(sensorPin) > 100);

the preceding code will flash the LED at least once and will keep flashing
as long as the value read from a sensor is greater than 100. if the value
is not greater than 100, the led will only flash once. This code could be
used in a battery-charging circuit, if it were called once every 10
seconds, whereas continuous flashing indicates the battery is charged.
Repeating a Sequence of Statements
for loop is similar to while loop, but you have more control over the starting
and ending conditions.
a for loop consists of three parts: initialization, conditional test and iteration.

int i;
void setup ( )
{
Serial.begin(9600);
for ( i = 0 ; i < 15 ; i ++ )
{
Serial.println( "Arduino");
}
}
void loop ( ) {
}
Repeating a Sequence of Statements
Break statement

Break statement void setup()


{
You want to terminate a
Serial.begin(9600);
loop early based on Serial.println(“start");
some condition you are for (int i = 1; i < 10; i++)
testing {
Serial.print(“inside loop ");
Break is used to exit from Serial.println(i);
for, while , do while if(i > 3)
loop, by passing the break;
}
normal loop condition.
Serial.println(“end");
}
void loop()
11March 2022.(Friday)

Arduino Function
• Functions are used to organize the int sensorPercent(int pin)
action performed by your sketch into
{
functional blocks.
• You create a function by declaring its int percent;
return type, its name and any val = analogRead(pin);
optional parameters that the function percent = map(val,0,1023,0,100);
will receive when it is called.
Int sensorpin = A0;
return percent;
void setup() }
{ Serial.begin(9600);
} In above function, function name is
void loop() sensorPercent.
{ It is given an analog pin number to
Int val = sensorPercent(sensorpin); read and return the value as
Serial.println(val); percent.
}
Arduino Function
example 01: square of number using function
void setup()
{
Serial.begin(9600); int squarenum(int m)
{
}

void loop() return m*m;


{ }
int i =2;
int k = squarenum(i);

Serial.println(k);

}
Example 02 : Temperature sensor
Arduino code using Function
int sensorpin = A0;
void setup()
{
Serial.begin(9600);

void loop()
{

float tempC = tempsense(sensorpin);

Serial.print(tempC);
Serial.println(" degree cel");

float tempsense(int pin)


{

float reading = analogRead(pin);


float tempC = reading/1024;
tempC = tempC*5.0;
tempC = tempC-0.5;
tempC = tempC*100;
return tempC;
}
Arduino Function
Returning more than one value from function
void setup() void swap(int &value1, int
{ Serial.begin(9600);} &value2)
void loop()
{ int temp;
{
int x =random(10); temp = value1;
Int y =random(10); value1 = value2;
Serial.print(x); value2 = temp;
Serial.print(y);
swap(x,y);
}
Serial.print(x);
Serial.print(y);
}
PWM(Pulse Width Modulation)
• It is a technique for getting analog results with
digital means.
• Digital control is a square wave.(ON-5v & OFF-
0v)
• The duration of ON time is called Pulse width.
• To get varying analog values, you
modulate/change the pulse width.
• Default PWM frequency is 490Hz (Pin5 &6) and
980Hz (Pin3,9,10,11)
PWM(Pulse Width Modulation)
• Use of PWM
– Dimming an LED.
– Providing an analog output.
– Provide variable speed control for Motors
– Generating a Modulated signal to drive infrared LED for a remote
control.
PWM(Pulse Width Modulation)
Example01: Dimming an LED
Unit 3 Completed

You might also like