You are on page 1of 38

Unit 3

Arduino Programming
Structuring an Arduino Program
• Program for Arduino are usually refereed to as
sketches.
• 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

}
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
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.
String represents an array of characters
char str[] = "Hello World!";
String str="Hello World!";
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");

}
Array in arduino
Int inputPins [] = {2,3,4,5};
• You want to create and use a int ledPins[] = {10,11,12,13};

group of values called arrays. void setup()


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

• The arrays may be a simple list pinMode(ledPins[i], OUTPUT);


pinMode(inputPins[i], INPUT);
digitalWrite(inputPins[i],LOW); // enable pull-down resistors
OR two or more dimensions.
}
}

• Another use of array is to hold void loop()


{
string of text characters. for(int i = 0; i < 4; i++)
{
Int val = digitalRead(inputPins[i]);

• A character string consists of if (val == HIGH)


{
one or more characters, digitalWrite(ledPins[i], HIGH);
}
followed by null character to else
{
indicate end of the string. 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
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. )

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);
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 temperature sensor never
exceeds 100 degrees. You could use the min() function like this:
sens_val = min(temp, 100);
The Arduino has another operator that deals with division called modulus.
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 radian(float deg)
float rad = radian(deg);
Serial.print(rad);
{
Serial.println(“radians”); return(deg/360*2*pi);
float a = sin(rad); }
Serial.print(a);
Serial.println(“sine value”);
float b = cos(rad);
Serial.print(b);
Serial.print(“cosine value”);
float degree(float rad)
float c = tan(rad); {
Serial.print( c ); return(rad/2/pi*360);
Serial.print(“tangent value”);
}
float deg = degree(rad);
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" ;
char val2[10];
• Using C Character Strings char val3[] = "Welcome to " ;

• Arrays of characters are sometimes


void setup() {
called character strings.
Serial.begin(9600);
• strlen: determine the number of
characters before null length = strlen(val1);
• strcpy: copy one string to another Serial.println(length);

• strcat: it append one string to the


strcpy(val2 ,val1);
end of another.
Serial.println(val2);
• strcmp: it compare two strings
strcat(val3 ,val2);
Serial.println(val3);

if(strcmp(val1, "Arduino“ ) == 0)
{
Serial.println("both the string are equal");
}
else
{
Serial.println("strings are unequal");
}}
void loop()
Array of strings
• It is convenient when working with large
amount of text to setup an array of strings.
• String themselves are arrays, this is an
example of a two dimensional array.
• char* indicates that this is an array of
pointers.
• All array names are actually pointers to make
an array of arrays.
Array of strings
char *strings*+ = ,“string1”, ”string2”, ”string3”-;
void setup()
{ Serial.begin(9600);
}
void loop()
{
for(int i=0;i<3;i++)
{
Serial.println(strings[i]);
delay(500);
}}
Repeating a Sequence of Statements
For loop
int i;
void setup ( )
{
Serial.begin(9600);
for ( i = 0 ; i < 15 ; i ++ )
{
Serial.println( "Arduino");
}
}
void loop ( ) {
}
Repeating a Sequence of Statements
while loop do-while loop
A while loop repeats one or more In do while condition is tested at the
instructions while an expression end of the loop, so the do loop
is true. will always run at least once.

int x = 0;
int var =0; do
while(var < 100) {
{ delay(50);
var++; x = readSensors();
} }
while (x < 100);
Repeating a Sequence of Statements
while loop
int a = 0;
void setup()
{
Serial.begin(9600);
while( a < 5)
{
Serial.println("Welcome to Arduino");
a = a + 1;
}
}
void loop()
{
}
Repeating a Sequence of Statements
Break statement
Break statement void setup()
{
Serial.begin(9600);
Break is used to exit from for, while , do Serial.println(“start");
while loop, by passing the normal for (int i = 1; i < 10; i++)
loop condition. {
Serial.print(“inside loop ");
Serial.println(i);
if(i > 3)
break;
}
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. int percent;
• You create a function by declaring its
val = analogRead(pin);
return type, its name and any
optional parameters that the percent = map(val,0,1023,0,100);
function will receive when it is called. return percent;
Int sensorpin = A0; }
void setup()
{ Serial.begin(9600); In above function, function name is
} sensorPercent.
void loop() It is given an analog pin number to
{
read and return the value as
percent.
Int val = sensorPercent(sensorpin);
Serial.println(val);
}
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 &value2)
{ Serial.begin(9600);} { int temp;
void loop() temp = value1;
{ value1 = value2;
int x =random(10); value2 = temp;
Int y =random(10); }
Serial.print(x);
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
PWM(Pulse Width Modulation)
PWM(Pulse Width Modulation)
Example02: DC motor control
PWM(Pulse Width Modulation)
Example03: Temp based fan speed control
PWM(Pulse Width Modulation)
Example03: Temp based fan speed control
Unit 3 Completed

You might also like