0% found this document useful (0 votes)
11 views

IOT Unit-3

IOT notes

Uploaded by

santodevil2711
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)
11 views

IOT Unit-3

IOT notes

Uploaded by

santodevil2711
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/ 28

Arduino

Arduino is an open-source electronics platform based on easy-to-use hardware


and software. It consists of a microcontroller, which is a small computer on a single
integrated circuit, and a development environment (the Arduino IDE) that allows users
to write and upload code to the microcontroller.

Installing and Setting up the Arduino IDE

Step 1: Download the Arduino IDE

1. Visit the Official Website: Go to the Arduino Software page.


2. Choose Your Version: Select the appropriate version for your operating
system (Windows, macOS, or Linux).
3. Download the Installer: Click on the download link. You may need to agree
to some terms before the download starts.

Step 2: Install the Arduino IDE

For Windows:

1. Run the Installer: Locate the downloaded .exe file and double-click it.
2. Follow the Prompts: Choose your installation options. It’s usually fine to keep
the defaults.
3. Install Drivers: If prompted, allow the installation of drivers that enable
communication with Arduino boards.

For macOS:

1. Open the Disk Image: Locate the downloaded .dmg file and double-click it.
2. Drag to Applications: Drag the Arduino icon into the Applications folder.
3. Launch the IDE: Open the Applications folder and double-click on the
Arduino icon. You might need to allow it through your security settings.

For Linux:

1. Extract the Archive: Open a terminal and navigate to the directory where the
downloaded file is located. Use tar -xvf arduino-* to extract it.
2. Run the Install Script: Navigate into the extracted folder and run sudo
./install.sh.
3. Add User to dialout Group: This is necessary for serial port access. Use
sudo usermod -aG dialout $USER and then log out and back in.

Step 3: Launch the Arduino IDE

 Open the Arduino IDE from your applications or programs menu.


Step 4: Configure the IDE

1. Select Your Board:


o Go to Tools > Board and choose your specific Arduino board model
(e.g., Arduino Uno, Arduino Mega, etc.).
2. Select the Port:
o Connect your Arduino board to your computer via USB.
o Go to Tools > Port and select the port associated with your board (it
usually looks like COM3 on Windows or /dev/ttyUSB0 on Linux).

Step 5: Install Libraries (if needed)

 Some projects require additional libraries. You can install them via:
o Sketch > Include Library > Manage Libraries...
o Search for the library you need and click Install.

Step 6: Write and Upload Your First Sketch

1. Open an Example Sketch:


o Go to File > Examples > Basics > Blink.
2. Upload the Sketch:
o Click the right arrow (Upload) icon in the toolbar. Make sure the code
compiles without errors.
o The onboard LED on your Arduino should start blinking!
1. Comments

Comments are used to annotate your code. They can be single-line or multi-line.

cpp
Copy code
// This is a single-line comment

/*
This is a multi-line comment
that can span multiple lines
*/

2. Variables

Declaring variables involves specifying the type and the name.

cpp
Copy code
int myNumber = 10; // Integer variable
float myFloat = 3.14; // Floating-point variable
char myChar = 'A'; // Character variable
String myString = "Hello"; // String variable

3. Constants

Use const to define constants that shouldn’t change.

cpp
Copy code
const int LED_PIN = 13; // LED pin number

4. Functions

Functions allow you to organize code. They can take parameters and return values.

cpp
Copy code
void myFunction() {
// Code to execute
}

int add(int a, int b) {


return a + b; // Returns the sum of a and b
}

5. Control Structures
If Statements

To execute code based on a condition.

cpp
Copy code
if (myNumber > 5) {
// Code to execute if the condition is true
} else {
// Code to execute if the condition is false
}

For Loops

To repeat code a specific number of times.

cpp
Copy code
for (int i = 0; i < 10; i++) {
// Code to execute 10 times
}

While Loops

To repeat code as long as a condition is true.

cpp
Copy code
while (myNumber < 20) {
myNumber++; // Increment myNumber until it reaches 20
}

6. Input and Output

You can read from and write to digital and analog pins using built-in functions.

cpp
Copy code
pinMode(LED_PIN, OUTPUT); // Set LED_PIN as an
output
digitalWrite(LED_PIN, HIGH); // Turn the LED on
int sensorValue = analogRead(A0); // Read from analog pin
A0

7. Arduino Specific Functions


Setup and Loop

Every Arduino sketch has these two functions.

cpp
Copy code
void setup() {
// Initialization code here
}

void loop() {
// Main code that runs repeatedly
}

8. Basic Syntax Example

Here’s a simple sketch that incorporates many of these concepts:

cpp
Copy code
const int LED_PIN = 13; // LED pin number

void setup() {
pinMode(LED_PIN, OUTPUT); // Initialize the LED pin
as an output
}

void loop() {
digitalWrite(LED_PIN, HIGH); // Turn the LED on
delay(1000); // Wait for a second
digitalWrite(LED_PIN, LOW); // Turn the LED off
delay(1000); // Wait for a second
}
OPERATORS:

When programming with C in the Arduino IDE, operators play an essential role
in performing various operations such as arithmetic, logical comparisons, and bit
manipulation. These operators are standard in C, and here’s a breakdown of the most
commonly used ones in Arduino programming:

1. Arithmetic Operators

Arithmetic operators are used to perform mathematical calculations.

 + : Addition
 - : Subtraction
 * : Multiplication
 / : Division
 % : Modulus (remainder of a division)

Example:

int a = 10;
int b = 3;
int sum = a + b; // sum = 13
int difference = a - b; // difference = 7
int product = a * b; // product = 30
int quotient = a / b; // quotient = 3 (integer division)
int remainder = a % b; // remainder = 1

2. Relational (Comparison) Operators

These operators are used to compare two values.

 == : Equal to
 != : Not equal to
 > : Greater than
 < : Less than
 >= : Greater than or equal to
 <= : Less than or equal to

Example:

int x = 5;
int y = 10;
if (x < y) {
// This will be true
}

3. Logical Operators

Logical operators are used to perform logical operations on Boolean expressions.

 && : Logical AND


 || : Logical OR
 ! : Logical NOT

Example:

bool a = true;
bool b = false;
bool result = a && b; // result = false
result = a || b; // result = true
result = !a; // result = false

4. Bitwise Operators

Bitwise operators are used to manipulate individual bits of variables.

 & : Bitwise AND


 | : Bitwise OR
 ^ : Bitwise XOR
 ~ : Bitwise NOT
 << : Left shift
 >> : Right shift

Example:

int a = 5; // 5 = 00000101 in binary


int b = 9; // 9 = 00001001 in binary

int result = a & b; // result = 1 (00000001)


result = a | b; // result = 13 (00001101)
result = a ^ b; // result = 12 (00001100)
result = ~a; // result = -6 (inverts bits)
result = a << 1; // result = 10 (00001010)
result = b >> 2; // result = 2 (00000010)

5. Assignment Operators

Assignment operators are used to assign values to variables.


 = : Simple assignment
 += : Add and assign
 -= : Subtract and assign
 *= : Multiply and assign
 /= : Divide and assign
 %= : Modulus and assign

Example:

int x = 10;
x += 5; // x = x + 5, so x becomes 15
x -= 3; // x = x - 3, so x becomes 12
x *= 2; // x = x * 2, so x becomes 24
x /= 4; // x = x / 4, so x becomes 6
x %= 5; // x = x % 5, so x becomes 1

6. Increment and Decrement Operators

These operators are used to increase or decrease the value of a variable by 1.

 ++ : Increment
 -- : Decrement

Example:

int count = 10;


count++; // count becomes 11
count--; // count becomes 10

There are two types of increment/decrement operators:

 Prefix (e.g., ++count) increments before using the value.


 Postfix (e.g., count++) increments after using the value.

Example:

int x = 5;
int y = ++x; // y is 6, x is 6
int z = x++; // z is 6, x is 7

7. Ternary Operator

The ternary operator is a shorthand for if-else statements.


 ?: : Conditional

Syntax:

condition ? expression_if_true : expression_if_false;

COMMON CONDITIONAL STATEMENTS IN ARDUINO:

Conditional statements in programming are used to perform different actions based


on different conditions. In Arduino programming, they allow your code to make
decisions and execute certain code blocks only when specific conditions are met.

1. if Statement
2. if-else Statement
3. else if Statement
4. switch-case Statement

1. if Statement

The if statement executes a block of code only if the condition inside the parentheses is
true.

Syntax:

if (condition) {
// Code to execute if the condition is true
}

Example:

int sensorValue = analogRead(A0); // Read sensor data

if (sensorValue > 500) {


digitalWrite(LED_BUILTIN, HIGH); // Turn the LED on if the sensor value is greater
than 500
}

In this example, if the value read from the sensor is greater than 500, the built-in LED
will turn on.

2. if-else Statement
The if-else statement allows you to specify an alternative block of code that runs when
the if condition is false.

Syntax:

if (condition) {
// Code to execute if the condition is true
} else {
// Code to execute if the condition is false
}

Example:

int temperature = 20;

if (temperature > 25) {


digitalWrite(LED_BUILTIN, HIGH); // Turn on the LED if the temperature is greater
than 25
} else {
digitalWrite(LED_BUILTIN, LOW); // Otherwise, turn off the LED
}

In this example, the LED turns on only if the temperature exceeds 25 degrees, otherwise,
it remains off.

3. else if Statement

The else if statement allows you to check multiple conditions sequentially. As soon as
one condition evaluates to true, its block of code is executed and the rest are skipped.

Syntax:

if (condition1) {
// Code if condition1 is true
} else if (condition2) {
// Code if condition2 is true
} else {
// Code if neither condition1 nor condition2 is true
}

Example:

int temperature = 18;


if (temperature > 30) {
// Too hot, take appropriate actions
} else if (temperature > 20) {
// Comfortable, do something
} else {
// Too cold, take actions
}

This allows you to check multiple ranges of temperatures and take different actions for
each range.

4. switch-case Statement

The switch statement is used when you want to compare the value of a variable to several
possible values and execute corresponding blocks of code.

Syntax:

switch (variable) {
case value1:
// Code to execute if variable equals value1
break;
case value2:
// Code to execute if variable equals value2
break;
default:
// Code to execute if variable doesn't match any case
}

Example:

int mode = 2;

switch (mode) {
case 1:
// Execute code for mode 1
digitalWrite(LED_BUILTIN, HIGH);
break;
case 2:
// Execute code for mode 2
digitalWrite(LED_BUILTIN, LOW);
break;
default:
// Code if mode does not match case 1 or case 2
break;
}

In this example, the LED will turn off because the mode variable is equal to 2.

LOOPING STATEMENTS:

Looping statements in Arduino programming allow you to repeat a block of code


multiple times, based on a given condition. This is useful for running tasks continuously,
such as checking sensor values, controlling outputs, or repeating actions a specific
number of times.

Types of Loops in Arduino

1. while Loop
2. do-while Loop
3. for Loop

1. while Loop

The while loop repeats a block of code as long as a given condition is true. The condition
is checked before executing the loop's body.

Syntax:

while (condition) {
// Code to execute while the condition is true
}

Example:

int count = 0;

while (count < 5) {


digitalWrite(LED_BUILTIN, HIGH); // Turn the LED on
delay(500); // Wait for 500 milliseconds
digitalWrite(LED_BUILTIN, LOW); // Turn the LED off
delay(500); // Wait for 500 milliseconds
count++; // Increment count
}

In this example, the LED will blink 5 times. The loop keeps running until the condition
count < 5 becomes false.
2. do-while Loop

The do-while loop is similar to the while loop, but the condition is checked after the code
is executed, so the code inside the loop will run at least once, even if the condition is false
from the start.

Syntax:

do {
// Code to execute
} while (condition);

Example:

int count = 0;

do {
digitalWrite(LED_BUILTIN, HIGH); // Turn the LED on
delay(500); // Wait for 500 milliseconds
digitalWrite(LED_BUILTIN, LOW); // Turn the LED off
delay(500); // Wait for 500 milliseconds
count++;
} while (count < 5);

Here, the LED will blink 5 times, similar to the while loop, but the loop executes at least
once regardless of the condition.

3. for Loop

The for loop is used when you know in advance how many times you want to run a block
of code. It is more compact than the while loop because it combines initialization,
condition checking, and increment/decrement in one line.

Syntax:

for (initialization; condition; increment) {


// Code to execute
}

Example:

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


digitalWrite(LED_BUILTIN, HIGH); // Turn the LED on
delay(500); // Wait for 500 milliseconds
digitalWrite(LED_BUILTIN, LOW); // Turn the LED off
delay(500); // Wait for 500 milliseconds
}

In this example, the loop runs 5 times, incrementing i with each iteration. Once i reaches
5, the loop exits.

Special Keywords for Loops

break

The break statement is used to exit a loop immediately, even if the condition hasn’t been
met yet.

Example:

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


if (i == 5) {
break; // Exit the loop when i equals 5
}
// This code will only run while i is less than 5
}
continue

The continue statement skips the current iteration of the loop and moves to the next
iteration.

Example:

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


if (i % 2 == 0) {
continue; // Skip even numbers
}
// This code will only run for odd values of i
}

ARDUINO C LIBRARY FUNCTION FOR SERIAL, DELAY AND OTHER


INVOKING FUNCTIONS:

In Arduino programming, library functions provide predefined methods that


simplify many common tasks, such as serial communication, timing delays, and
input/output control. Below are some commonly used library functions for serial
communication, timing delays, and other core Arduino functions.
1. Serial Communication Functions

The Serial library allows for communication between the Arduino and your computer via
USB. This is especially useful for debugging and monitoring sensor data.

Serial.begin()

Initializes serial communication at a specified baud rate (the speed at which data is sent
or received).

Syntax:

Serial.begin(baudRate);

Example:

void setup() {
Serial.begin(9600); // Start serial communication at 9600 baud
}
Serial.print()

Sends data to the serial port as human-readable text.

Syntax:

Serial.print(data);
Serial.print(data, format);

 data: The data to be sent (could be a number, character, or string).


 format: Optional format specifier (such as DEC, HEX, or BIN for numbers).

Example:

int sensorValue = analogRead(A0);

void setup() {
Serial.begin(9600); // Initialize serial communication
}

void loop() {
sensorValue = analogRead(A0); // Read sensor value
Serial.print("Sensor Value: "); // Print a label
Serial.println(sensorValue); // Print the sensor value followed by a newline
delay(1000); // Wait for 1 second
}
Serial.println()

Similar to Serial.print(), but it sends a newline (\n) after printing, moving the cursor to the
next line.

Syntax:

Serial.println(data);
Serial.println(data, format);

Example:

Serial.println("Hello, Arduino!"); // Prints the text followed by a newline


Serial.read()

Reads incoming serial data and returns the first byte of incoming data (ASCII code).

Syntax:

int incomingByte = Serial.read();

Example:

void setup() {
Serial.begin(9600); // Start serial communication
}

void loop() {
if (Serial.available() > 0) { // Check if data is available
int incomingByte = Serial.read(); // Read the incoming byte
Serial.print("I received: ");
Serial.println(incomingByte); // Print the received byte
}
}
Serial.available()

Checks how many bytes are available to read from the serial buffer.

Syntax:
int numBytes = Serial.available();

Example:

if (Serial.available() > 0) {
int incomingByte = Serial.read();
Serial.println(incomingByte);
}

2. Delay and Timing Functions

The delay and millis functions are useful for managing timing in your Arduino code.

delay()

Pauses the program for a specified number of milliseconds.

Syntax:

delay(milliseconds);

Example:

digitalWrite(LED_BUILTIN, HIGH); // Turn the LED on


delay(1000); // Wait for 1 second (1000 milliseconds)
digitalWrite(LED_BUILTIN, LOW); // Turn the LED off

In this example, the LED turns on, stays on for 1 second, and then turns off.

delayMicroseconds()

Pauses the program for a specified number of microseconds (1 microsecond = 0.000001


second).

Syntax:

delayMicroseconds(microseconds);

Example:

delayMicroseconds(10); // Pause for 10 microseconds


millis()

Returns the number of milliseconds since the Arduino started running the current
program.

Syntax:

unsigned long timePassed = millis();

Example:

unsigned long startTime = 0;

void setup() {
Serial.begin(9600);
startTime = millis(); // Record the start time
}

void loop() {
if (millis() - startTime > 5000) { // 5 seconds have passed
Serial.println("5 seconds passed");
startTime = millis(); // Reset the start time
}
}

This example prints a message every 5 seconds by using millis() to measure the time
passed.

3. Pin Manipulation Functions

These functions allow you to control and read from the digital and analog pins on the
Arduino board.

pinMode()

Sets the mode of a digital pin to either INPUT, OUTPUT, or INPUT_PULLUP.

Syntax:

pinMode(pin, mode);

 pin: The number of the pin.


 mode: Can be INPUT, OUTPUT, or INPUT_PULLUP.
Example:

void setup() {
pinMode(LED_BUILTIN, OUTPUT); // Set the LED pin as output
}
digitalWrite()

Writes a HIGH or LOW value to a digital pin, turning it on or off.

Syntax:

digitalWrite(pin, value);

 pin: The digital pin to control.


 value: Either HIGH (turn on) or LOW (turn off).

Example:

digitalWrite(LED_BUILTIN, HIGH); // Turn the LED on


digitalRead()

Reads the value from a specified digital pin (either HIGH or LOW).

Syntax:

int state = digitalRead(pin);

Example:

int buttonState = digitalRead(2); // Read the value from pin 2


if (buttonState == HIGH) {
digitalWrite(LED_BUILTIN, HIGH); // Turn the LED on if the button is pressed
}
analogRead()

Reads the value from an analog input pin and returns a value between 0 and 1023
(corresponding to a voltage range of 0 to 5V).

Syntax:

int sensorValue = analogRead(pin);


Example:

int sensorValue = analogRead(A0); // Read the analog input from pin A0


Serial.println(sensorValue); // Print the sensor value
analogWrite()

Writes an analog value (PWM) to a pin, simulating an analog output using Pulse Width
Modulation (PWM). The value can range from 0 (off) to 255 (fully on).

Syntax:

analogWrite(pin, value);

Example:

analogWrite(9, 128); // Set a PWM value of 128 (50% duty cycle) on pin 9

4. Miscellaneous Core Functions

random()

Generates a pseudo-random number.

Syntax:

long randNumber = random(minValue, maxValue);

Example:

int randNum = random(0, 100); // Generate a random number between 0 and 100
randomSeed()

Sets the seed value for the random number generator, allowing you to get different
random sequences each time.

Syntax:

randomSeed(seed);

Example:

randomSeed(analogRead(A0)); // Use a noisy analog pin to generate a random seed


String Library Functions

Strings in Arduino can either be C-style null-terminated character arrays or objects of the
String class. The String class provides various methods to manipulate strings in Arduino.

1. String Concatenation and Modification Functions

String()

The String() constructor can convert a variety of data types (like integers, floats, etc.) into
strings.

Syntax:

String str = String(123); // Creates a string "123"


concat()

Concatenates a string or a number to the current string.

Syntax:

string.concat(value);

Example:

String greeting = "Hello ";


greeting.concat("World!"); // Result: "Hello World!"
+ Operator

The + operator can be used to concatenate strings.

Example:

String greeting = "Hello " + String("World!"); // Result: "Hello World!"


toUpperCase() / toLowerCase()

Converts all characters in a string to uppercase or lowercase.


Syntax:

string.toUpperCase();
string.toLowerCase();

Example:

String text = "Hello";


text.toUpperCase(); // Result: "HELLO"
text.toLowerCase(); // Result: "hello"
2. String Inspection Functions

length()

Returns the number of characters in a string.

Syntax:

int len = string.length();

Example:

String text = "Arduino";


int length = text.length(); // Result: 7
charAt()

Returns the character at a specific index in the string.

Syntax:

char character = string.charAt(index);

Example:

String text = "Arduino";


char firstChar = text.charAt(0); // Result: 'A'
indexOf()

Finds the index of a character or substring in the string. Returns -1 if not found.

Syntax:
cpp
Copy code
int index = string.indexOf(charOrString);

Example:

String text = "Hello Arduino";


int index = text.indexOf("Arduino"); // Result: 6
3. String Conversion Functions

toInt()

Converts a string to an integer.

Syntax:

int num = string.toInt();

Example:

String numStr = "123";


int num = numStr.toInt(); // Result: 123
toFloat()

Converts a string to a float.

Syntax:

float num = string.toFloat();

Example:

String numStr = "3.14";


float pi = numStr.toFloat(); // Result: 3.14
4. String Comparison Functions

equals() / equalsIgnoreCase()

Compares two strings for equality. equalsIgnoreCase() ignores case during comparison.

Syntax:
bool result = string.equals(otherString);
bool result = string.equalsIgnoreCase(otherString);

Example:

String a = "Hello";
String b = "hello";
bool isEqual = a.equals(b); // Result: false
bool isEqualIgnoreCase = a.equalsIgnoreCase(b); // Result: true
compareTo()

Compares two strings lexicographically. Returns 0 if the strings are equal, a positive
number if the first string is greater, or a negative number if the second string is greater.

Syntax:

int result = string.compareTo(otherString);

Example:

String a = "Arduino";
String b = "arduino";
int comparison = a.compareTo(b); // Result: -32 (due to case sensitivity)

MATHEMATICS LIBRARY FUNCTIONS:

The Arduino Math library includes basic math functions that operate on numbers.

1. Basic Math Functions

min()

Returns the smaller of two numbers.

Syntax:

int result = min(x, y);

Example:

int smaller = min(5, 10); // Result: 5


max()

Returns the larger of two numbers.

Syntax:

int result = max(x, y);

Example:

int larger = max(5, 10); // Result: 10


abs()

Returns the absolute value of a number.

Syntax:

int result = abs(x);

Example:

int positive = abs(-10); // Result: 10


sq()

Returns the square of a number.

Syntax:

int result = sq(x);

Example:

int square = sq(3); // Result: 9


2. Trigonometric Functions

sin()

Calculates the sine of an angle (in radians).

Syntax:

float result = sin(angle);


Example:

float sineVal = sin(PI / 2); // Result: 1


cos()

Calculates the cosine of an angle (in radians).

Syntax:

float result = cos(angle);

Example:

float cosineVal = cos(PI); // Result: -1


tan()

Calculates the tangent of an angle (in radians).

Syntax:

float result = tan(angle);

Example:

float tangentVal = tan(PI / 4); // Result: 1


3. Exponential and Logarithmic Functions

pow()

Raises a number to the power of another number.

Syntax:

float result = pow(base, exponent);

Example:

float power = pow(2, 3); // Result: 8 (2 raised to the power of 3)


sqrt()

Returns the square root of a number.


Syntax:

float result = sqrt(x);

Example:

float squareRoot = sqrt(16); // Result: 4


log()

Returns the natural logarithm (base e) of a number.

Syntax:

float result = log(x);

Example:

float naturalLog = log(2.71828); // Result: 1 (approx)


log10()

Returns the base-10 logarithm of a number.

Syntax:

float result = log10(x);

Example:

float base10Log = log10(100); // Result: 2


4. Rounding Functions

round()

Rounds a floating-point number to the nearest integer.

Syntax:

long result = round(x);

Example:

long roundedValue = round(3.6); // Result: 4


floor()

Returns the largest integer less than or equal to the given number.

Syntax:

float result = floor(x);

Example:

float floorValue = floor(3.7); // Result: 3


ceil()

Returns the smallest integer greater than or equal to the given number.

Syntax:

float result = ceil(x);

Example:

float ceilValue = ceil(3.1); // Result: 4

You might also like