IOT Unit-3
IOT Unit-3
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.
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.
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
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
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
}
5. Control Structures
If Statements
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
cpp
Copy code
for (int i = 0; i < 10; i++) {
// Code to execute 10 times
}
While Loops
cpp
Copy code
while (myNumber < 20) {
myNumber++; // Increment myNumber until it reaches 20
}
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
cpp
Copy code
void setup() {
// Initialization code here
}
void loop() {
// Main code that runs repeatedly
}
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
+ : 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
== : 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
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
Example:
5. Assignment Operators
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
++ : Increment
-- : Decrement
Example:
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
Syntax:
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:
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:
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:
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:
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;
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:
Example:
In this example, the loop runs 5 times, incrementing i with each iteration. Once i reaches
5, the loop exits.
break
The break statement is used to exit a loop immediately, even if the condition hasn’t been
met yet.
Example:
The continue statement skips the current iteration of the loop and moves to the next
iteration.
Example:
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()
Syntax:
Serial.print(data);
Serial.print(data, format);
Example:
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:
Reads incoming serial data and returns the first byte of incoming data (ASCII code).
Syntax:
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);
}
The delay and millis functions are useful for managing timing in your Arduino code.
delay()
Syntax:
delay(milliseconds);
Example:
In this example, the LED turns on, stays on for 1 second, and then turns off.
delayMicroseconds()
Syntax:
delayMicroseconds(microseconds);
Example:
Returns the number of milliseconds since the Arduino started running the current
program.
Syntax:
Example:
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.
These functions allow you to control and read from the digital and analog pins on the
Arduino board.
pinMode()
Syntax:
pinMode(pin, mode);
void setup() {
pinMode(LED_BUILTIN, OUTPUT); // Set the LED pin as output
}
digitalWrite()
Syntax:
digitalWrite(pin, value);
Example:
Reads the value from a specified digital pin (either HIGH or LOW).
Syntax:
Example:
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:
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
random()
Syntax:
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:
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.
String()
The String() constructor can convert a variety of data types (like integers, floats, etc.) into
strings.
Syntax:
Syntax:
string.concat(value);
Example:
Example:
string.toUpperCase();
string.toLowerCase();
Example:
length()
Syntax:
Example:
Syntax:
Example:
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:
toInt()
Syntax:
Example:
Syntax:
Example:
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:
Example:
String a = "Arduino";
String b = "arduino";
int comparison = a.compareTo(b); // Result: -32 (due to case sensitivity)
The Arduino Math library includes basic math functions that operate on numbers.
min()
Syntax:
Example:
Syntax:
Example:
Syntax:
Example:
Syntax:
Example:
sin()
Syntax:
Syntax:
Example:
Syntax:
Example:
pow()
Syntax:
Example:
Example:
Syntax:
Example:
Syntax:
Example:
round()
Syntax:
Example:
Returns the largest integer less than or equal to the given number.
Syntax:
Example:
Returns the smallest integer greater than or equal to the given number.
Syntax:
Example: