Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
44 views

Learn Arduino HNK

Explore the world of embedded systems with Learn Arduino Hnk! This comprehensive guide covers the essentials of Arduino programming, from basic electronics to advanced projects using sensors, motors, and wireless communication. Perfect for students, hobbyists, and tech enthusiasts, this book provides hands-on examples that bring your ideas to life.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
44 views

Learn Arduino HNK

Explore the world of embedded systems with Learn Arduino Hnk! This comprehensive guide covers the essentials of Arduino programming, from basic electronics to advanced projects using sensors, motors, and wireless communication. Perfect for students, hobbyists, and tech enthusiasts, this book provides hands-on examples that bring your ideas to life.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 58

MASTERING

EMEDDED SYSTEMS
B E C O M E R E A D Y

HNK

LEARN Arduino
Arduino is an open-source electronics platform based on easy-to-use
hardware and software. It's a powerful and versatile technology that can
be used for various purposes such as interactive projects, automation,
and education. In the following section, we will provide an overview of this
textbook's content.

OVERVIEW
This textbook provides a comprehensive guide to Arduino, focusing on
how to use its components and capabilities effectively. You will learn the
theory and practice of Arduino, such as how to use digital and analog I/O
functions, timers, communication functions, and sensors.

You will learn the essentials of Arduino, such as how to control LEDs,
read sensors, use serial communication, and handle interrupts. You will also
learn how to use C++ and Arduino IDE to write and upload sketches to the
Arduino board. You will apply your skills to create various projects such as a
light-sensitive lamp, a temperature monitor, and an ultrasonic distance
meter. This textbook is suitable for anyone who wants to learn how to use
Arduino in a practical and innovative way.

In the second part of this textbook, you will learn how to use advanced
libraries and shields that extend Arduino’s capabilities, such as motor
control, wireless communication, and environmental sensing.
Table of Contents

Description of the Simulation: ............................................................................................... 6


Description of the Code: ........................................................................................................ 6
1. Basic Arithmetic Operations .............................................................................................. 9
Code ................................................................................................................................... 9
Results .............................................................................................................................. 10
Setup Function ................................................................................................................. 10
2. Mathematical Functions in Arduino ................................................................................ 11
Example Code: ..................................................................................................................... 12
Explanation: ......................................................................................................................... 13
Summary ......................................................................................................................... 13
3. Loops in Arduino ............................................................................................................. 14
For Loop............................................................................................................................... 14
While Loop .......................................................................................................................... 15
Do-While Loop .................................................................................................................... 16
Nested Loops ....................................................................................................................... 17
Summary .......................................................................................................................... 18
4. Declaring and Initializing Arrays..................................................................................... 18
Integer Array .................................................................................................................... 18
Demonstrating Various Array Types in Arduino................................................................. 19
Example Code with Various Array Types ....................................................................... 20
Summary .......................................................................................................................... 21
5. Basic Switch Case Example............................................................................................. 22
Code ................................................................................................................................. 22
6. Basic if, else if, else Example .......................................................................................... 23
Logic Table .......................................................................................................................... 23
Explanation and Example Code ........................................................................................... 23
Explanation of the Example Code ................................................................................... 25
7. Various Serial Methods.................................................................................................... 26
Example 1: Reading and Printing a String........................................................................... 26
Code ................................................................................................................................. 26
Example 2: Reading and Printing a Float ............................................................................ 27
Code ................................................................................................................................. 27
void setup() ............................................................................................................... 27
Example 3: Reading and Printing a Double ......................................................................... 28
Code ................................................................................................................................. 28
void setup() ............................................................................................................... 28
Example 4: Reading and Printing an Integer ....................................................................... 29
Code ................................................................................................................................. 29
Example 5: Reading and Printing a Character ..................................................................... 29
Code ................................................................................................................................. 30
Summary .......................................................................................................................... 30
7. Servo Motors ........................................................................................................................ 31
1. Basics of Servo Motors ................................................................................................ 31
2. Servo + For loop motor moving clock and anti-clock wise ......................................... 32
3. Servo motor + potentiometer controller ....................................................................... 33
4. Servo + Sensor (distance control over motor movement) ........................................... 34
8. Advanced I/O Functions .................................................................................................. 36
Using Analog Inputs and Outputs ........................................................................................ 36
Analog Inputs ................................................................................................................... 36
Example: Reading a Potentiometer .................................................................................. 37
Analog Outputs .................................................................................................................... 37
Example: Controlling LED Brightness ............................................................................ 38
Digital Inputs and Outputs ................................................................................................... 38
Digital Inputs ....................................................................................................................... 38
Example: Reading a Button ............................................................................................. 39
Digital Outputs ..................................................................................................................... 39
Example: Controlling an LED ......................................................................................... 40
Summary ......................................................................................................................... 40
9. Communication Functions ............................................................................................... 41
Serial Communication (UART) ........................................................................................... 41
I2C Communication Protocol .............................................................................................. 41
Example: Master Device Sending Data ........................................................................... 42
1. Display Potentiometer Voltage on I2C LCD ................................................................... 42
Code: ................................................................................................................................ 43
2. Display Distance Measured by Ultrasonic Sensor on I2C LCD ...................................... 44
Code: ................................................................................................................................ 44
10. Light Sensitive Sensors ...................................................................................................... 46
1. Reading and Displaying LDR Values with Arduino ....................................................... 46
Code: ................................................................................................................................ 47
2. Controlling LED Brightness with an LDR and Displaying Values on an I2C LCD ....... 48
Code: ................................................................................................................................ 48
11. Understanding the Basics of Photodiodes.......................................................................... 50
Code: ................................................................................................................................ 51
12. Reading Analog Sensor Values and Controlling an LED Brightness ............................... 52
Code: ................................................................................................................................ 52
13. Using Interrupt Functions in Arduino ................................................................................ 54
Code: ................................................................................................................................ 54
Test 1 Resolution
Description of the Simulation:
This Tinkercad simulation illustrates an Arduino Uno project that controls a series of LEDs to
create dynamic light animations. The setup includes green and red LEDs connected to digital
pins 2 through 9 on the Arduino, with resistors to limit current. The provided Arduino code
initializes the LED pins as outputs and sequences the LEDs to turn on and off, producing
moving light patterns. This project demonstrates the basics of digital I/O operations and LED
control using Arduino programming.

Description of the Code:


This Arduino code is designed to create dynamic animations using two sets of LEDs: green
and red. Each set of LEDs is connected to specific pins on the Arduino board. The code
alternates between turning on and off the green and red LEDs in a sequential manner to create
moving light patterns.
PROGRAM

// Define LED pins


const int greenLedPins[] = {2, 3, 4, 5, 6, 7, 8, 9}; // Green LEDs connected to pins 2 to 9
const int redLedPins[] = {9, 8, 7, 6, 5, 4, 3, 2}; // Red LEDs connected to pins 9 to 2

// Define delay between LED movements


const int delayTime = 100; // Adjust as needed for desired speed

void setup()
{
// Set LED pins as output
for (int i = 0; i < 8; i++)
{
pinMode(greenLedPins[i], OUTPUT);
pinMode(redLedPins[i], OUTPUT);
}
}

void loop()
{
// Switch on green LEDs
for (int i = 0; i < 8; i++)
{
digitalWrite(greenLedPins[i], HIGH);
}
delay(1000); // Wait for 1 second to see the green LEDs

// Move green LEDs from right to left


for (int i = 0; i < 8; i++)
{
digitalWrite(greenLedPins[i], LOW);
delay(delayTime);
digitalWrite(greenLedPins[i + 1], HIGH);
}

// Move red LEDs from right to left


for (int i = 0; i < 8; i++)
{
digitalWrite(redLedPins[i], LOW);
delay(delayTime);
digitalWrite(redLedPins[i + 1], HIGH);
}

// Change color and direction after sweep


for (int i = 0; i < 8; i++)
{
digitalWrite(greenLedPins[i], LOW);
digitalWrite(redLedPins[i], LOW);
delay(delayTime);
digitalWrite(greenLedPins[7 - i], HIGH);
digitalWrite(redLedPins[7 - i], HIGH);
delay(delayTime);
}
// Move LEDs simultaneously to the middle
for (int i = 0; i < 4; i++)
{
digitalWrite(greenLedPins[i], LOW);
digitalWrite(redLedPins[i], LOW);
digitalWrite(greenLedPins[7 - i], LOW);
digitalWrite(redLedPins[7 - i], LOW);
digitalWrite(greenLedPins[3 - i], HIGH);
digitalWrite(redLedPins[3 - i], HIGH);
digitalWrite(greenLedPins[4 + i], HIGH);
digitalWrite(redLedPins[4 + i], HIGH);
delay(delayTime);
}
}

This Arduino code controls two sets of LEDs (green and red) connected to specific pins on the
Arduino board to create dynamic animations. It defines arrays for green and red LED pins, and
a delay time for the animation speed. In the setup function, each pin is configured as an output.
In the loop function, the code first turns on all green LEDs for 1 second, then moves the green
LEDs from right to left by turning them off sequentially with a delay. Next, it performs the
same movement with the red LEDs. After completing the sweeps, the LEDs are turned off and
turned back on in reverse order. Finally, the LEDs move simultaneously towards the center,
creating a converging effect. This code demonstrates basic digital I/O operations and timing in
Arduino programming to produce interactive light animations.
1. Test 2 Preparation

1. Basic Arithmetic Operations


In Arduino, basic arithmetic operations are straightforward and similar to other
programming languages. These operations include addition, subtraction, multiplication,
and division.

Code

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

void loop()
{
int a = 10;
int b = 5;

int sum = a + b; // Addition


int diff = a - b; // Subtraction
int prod = a * b; // Multiplication
float quot = (float)a / b; // Division (type cast to float for accurate
result)

double pi = 3.14159;
double radius = 2.5;
double area = pi * radius * radius; // Calculate the area of a circle

String greeting = "Hello, Arduino!";

Serial.print("Sum: ");
Serial.println(sum);
Serial.print("Difference: ");
Serial.println(diff);
Serial.print("Product: ");
Serial.println(prod);
Serial.print("Quotient: ");
Serial.println(quot);

Serial.print("Area of circle with radius ");


Serial.print(radius);
Serial.print(" is: ");
Serial.println(area);
Serial.print("Greeting message: ");
Serial.println(greeting);

delay(1000); // Wait for 1 second before repeating


}

Results

Setup Function
• Serial.begin(9600): Initializes serial communication at a baud rate of 9600 bits
per second.
Loop Function

• Integer (int):
• int a = 10, b = 5: Defines two integer variables.
• int sum = a + b: Stores the result of addition.
• int diff = a - b: Stores the result of subtraction.
• int prod = a * b: Stores the result of multiplication.
• Float (float):
• float quot = (float)a / b: Performs division and casts the result to a
float for accurate division.

• Double (double):
• double pi = 3.14159: Defines a double variable to store the value of π
(pi).
• double radius = 2.5: Defines a double variable to store the radius of a
circle.
• double area = pi * radius * radius : Calculates the area of the circle
using the formula π * r² and stores it in a double variable.

• String (String):
• String greeting = "Hello, Arduino!": Defines a string variable with a
greeting message.

2. Mathematical Functions in Arduino


Trigonometric Functions (sin, cos, tan):
Arduino provides sin(), cos(), and tan() functions which take a float value (angle in
radians) and return a float value.
Example Code:

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

// Trigonometric Functions
float angle = 45.0; // Angle in degrees
float radiansValue = radians(angle); // Convert angle to radians

Serial.println("Trigonometric Functions:");
Serial.print("sin(45 degrees): ");
Serial.println(sin(radiansValue));
Serial.print("cos(45 degrees): ");
Serial.println(cos(radiansValue));
Serial.print("tan(45 degrees): ");
Serial.println(tan(radiansValue));
Serial.println();

// Logarithmic and Exponential Functions


float num = 10.0;

Serial.println("Logarithmic and Exponential Functions:");


Serial.print("Natural log of 10: ");
Serial.println(log(num)); // Natural logarithm
Serial.print("Log base 10 of 10: ");
Serial.println(log10(num)); // Base-10 logarithm
Serial.print("exp(2): ");
Serial.println(exp(2)); // Exponential function
Serial.println();

// Random Number Generation and Manipulation


randomSeed(analogRead(0)); // Initialize random number generator

Serial.println("Random Number Generation and Manipulation:");


Serial.print("Random number between 0 and 99: ");
Serial.println(random(100));
Serial.print("Random number between 50 and 100: ");
Serial.println(random(50, 101));

Serial.println();
}

void loop()
{
// Nothing to do here
}
Explanation:
1. Trigonometric Functions:

• sin(), cos(), and tan() functions are used to calculate the sine, cosine,
and tangent of an angle.
• The radians() function converts an angle in degrees to radians.

2. Logarithmic and Exponential Functions:

• log() calculates the natural logarithm of a number.


• log10() calculates the base-10 logarithm of a number.
• exp() calculates the exponential value of a number.

3. Random Number Generation and Manipulation:

• randomSeed() initializes the random number generator.


• random() generates random numbers within a specified range.

Summary
This sketch demonstrates the use of trigonometric functions, logarithmic and
exponential functions, and random number generation in Arduino. By combining these
functions in one program, you can perform complex mathematical calculations and
generate random values for various applications in your Arduino projects.
3. Loops in Arduino
Loops are fundamental in programming for repeating a block of code multiple times.
Arduino supports several types of loops, including for, while, and do-while.

For Loop
A for loop is used when you know in advance how many times you want to execute a
statement or a block of statements

Example: Blinking an LED 10 time

const int ledPin = 13; // Pin connected to the LED

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

void loop()
{
for (int i = 0; i < 10; i++)
{
digitalWrite(ledPin, HIGH); // Turn the LED on
delay(500); // Wait for half a second
digitalWrite(ledPin, LOW); // Turn the LED off
delay(500); // Wait for half a second
}
delay(5000); // Wait for 5 seconds before repeating the loop
}
While Loop
A while loop repeats a block of code as long as a specified condition is true.

Example: Blinking an LED at least once while a button is pressed

const int ledPin = 13; // Pin connected to the LED


const int buttonPin = 2; // Pin connected to the button

void setup()
{
pinMode(ledPin, OUTPUT); // Set the LED pin as an output
pinMode(buttonPin, INPUT); // Set the button pin as an input
}

void loop()
{
while (digitalRead(buttonPin) == HIGH)
{ // While the button is pressed
digitalWrite(ledPin, HIGH); // Turn the LED on
delay(500); // Wait for half a second
digitalWrite(ledPin, LOW); // Turn the LED off
delay(500); // Wait for half a second
}
}
Do-While Loop
A do-while loop is similar to a while loop, but it guarantees that the code block will be
executed at least once.

Example: Blinking an LED at least once while a button is pressed

const int ledPin = 13; // Pin connected to the LED


const int buttonPin = 2; // Pin connected to the button

void setup()
{
pinMode(ledPin, OUTPUT); // Set the LED pin as an output
pinMode(buttonPin, INPUT); // Set the button pin as an input
}

void loop()
{
do
{
digitalWrite(ledPin, HIGH); // Turn the LED on
delay(500); // Wait for half a second
digitalWrite(ledPin, LOW); // Turn the LED off
delay(500); // Wait for half a second
} while (digitalRead(buttonPin) == HIGH); // While the button is pressed
}
Nested Loops
Loops can be nested inside each other, which is useful for working with multi-
dimensional arrays or performing repetitive tasks within another repetitive task.

Example: Nested Loops to Blink LEDs

const int ledPins[] = {13, 12, 11}; // Array of LED pins

void setup()
{
for (int i = 0; i < 3; i++)
{
pinMode(ledPins[i], OUTPUT); // Set each LED pin as an output
}
}

void loop()
{
for (int i = 0; i < 3; i++)
{ // Outer loop
for (int j = 0; j < 3; j++)
{ // Inner loop
digitalWrite(ledPins[j], HIGH); // Turn the LED on
delay(500); // Wait for half a second
digitalWrite(ledPins[j], LOW); // Turn the LED off
delay(500); // Wait for half a second
}
}
}
Summary
• For Loop: Use when you know the number of iterations.
• While Loop: Use when the number of iterations depends on a condition.
• Do-While Loop: Use when you need the code block to execute at least once,
regardless of the condition.
• Nested Loops: Use for complex repetitive tasks or working with multi-
dimensional arrays.

4. Declaring and Initializing Arrays

Integer Array

int numbers[5]; // Declare an array of 5 integers

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

// Initialize the array elements


numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;

// Print the array elements


for (int i = 0; i < 5; i++)
{
Serial.print("numbers[");
Serial.print(i);
Serial.print("] = ");
Serial.println(numbers[i]);
}
}

void loop()
{
// Nothing to do here
}
Demonstrating Various Array Types in Arduino
This Arduino sketch demonstrates the use of different types of arrays, including integer
arrays, float arrays, double arrays, char arrays, String object arrays, and multi-
dimensional arrays. Each array type is initialized with sample values and printed to the
Serial Monitor for easy observation. This example provides a comprehensive overview
of how to handle and utilize different data types in arrays within an Arduino program.
Example Code with Various Array Types

void setup()
{
Serial.begin(9600); // Initialize serial communication at 9600 bps
// Integer Array
int intArray[5] = {10, 20, 30, 40, 50};
Serial.println("Integer Array:");
for (int i = 0; i < 5; i++)
{
Serial.println(intArray[i]);
}

// Float Array
float floatArray[3] = {1.1, 2.2, 3.3};
Serial.println("Float Array:");
for (int i = 0; i < 3; i++)
{
Serial.println(floatArray[i], 2); // Print with 2 decimal places
}

// Double Array
double doubleArray[3] = {1.11111, 2.22222, 3.33333};
Serial.println("Double Array:");
for (int i = 0; i < 3; i++)
{
Serial.println(doubleArray[i], 5); // Print with 5 decimal places
}

// Char Array (String)


char charArray[] = "Hello, Arduino!";
Serial.println("Char Array:");
Serial.println(charArray);

// String Object Array


String stringArray[3] = {"String 1", "String 2", "String 3"};
Serial.println("String Object Array:");
for (int i = 0; i < 3; i++)
{
Serial.println(stringArray[i]);
}

// Multi-Dimensional Arrays
int multiDimArray[2][3] =
{
{1, 2, 3},
{4, 5, 6}
};
Serial.println("Multi-Dimensional Array:");
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 3; j++)
{
Serial.print(multiDimArray[i][j]);
Serial.print(" ");
}
Serial.println();
}
}

void loop()
{
// Nothing to do here
}

Summary
• Integer Array: int intArray[]
• Float Array: float floatArray[]
• Double Array: double doubleArray[]
• Char Array: char charArray[]
• String Object Array: String stringArray[]
• Multi-Dimensional Arrays: int multiDimArray[][]

This example demonstrates how to declare, initialize, and use various types of arrays in
Arduino, and how to print their values using serial communication
5. Basic Switch Case Example
This example will demonstrate how to use switch cases to perform different actions
based on the value of a variable.

Code

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

int number = 2; // Example variable to use with switch case

switch (number)
{
case 1:
Serial.println("Case 1: The number is 1");
break;
case 2:
Serial.println("Case 2: The number is 2");
break;
case 3:
Serial.println("Case 3: The number is 3");
break;
default:
Serial.println("Default case: The number is not 1, 2, or 3");
break;
}
}

void loop()
{
// Nothing to do here
}
6. Basic if, else if, else Example
This example will demonstrate how to use if, else if, and else statements to perform
different actions based on the value of a variable.

Logic Table
Below is a table that summarizes various conditions you can use with if statements in
Arduino. Each row includes the condition, an explanation, and an example code snippet.

Explanation and Example Code


Here’s an example that uses multiple conditions to demonstrate their usage:

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

int a = 5;
int b = 10;
int c = 15;
int d = 20;
// Equal to
if (a == 5)
{
Serial.println("a is equal to 5");
}

// Not equal to
if (b != 5)
{
Serial.println("b is not equal to 5");
}

// Less than
if (a < b)
{
Serial.println("a is less than b");
}

// Less than or equal to


if (b <= 10)
{
Serial.println("b is less than or equal to 10");
}

// Greater than
if (c > b)
{
Serial.println("c is greater than b");
}

// Greater than or equal to


if (d >= 20)
{
Serial.println("d is greater than or equal to 20");
}

// Logical AND
if (a < b && c > b)
{
Serial.println("a is less than b AND c is greater than b");
}

// Logical OR
if (a > b || c > b)
{
Serial.println("a is greater than b OR c is greater than b");
}
}

void loop()
{
// Nothing to do here
}
Explanation of the Example Code

1. Equal to (==):

• Checks if a is equal to 5.
• Prints "a is equal to 5" if true.

2. Not equal to (!=):

• Checks if b is not equal to 5.


• Prints "b is not equal to 5" if true.

3. Less than (<):

• Checks if a is less than b.


• Prints "a is less than b" if true.

4. Less than or equal to (<=):

• Checks if b is less than or equal to 10.


• Prints "b is less than or equal to 10" if true.

5. Greater than (>):

• Checks if c is greater than b.


• Prints "c is greater than b" if true.

6. Greater than or equal to (>=):

• Checks if d is greater than or equal to 20.


• Prints "d is greater than or equal to 20" if true.

7. Logical AND (&&):

• Checks if a is less than b and c is greater than b.


• Prints "a is less than b AND c is greater than b" if both conditions are true.

8. Logical OR (||):

• Checks if a is greater than b or c is greater than b.


• Prints "a is greater than b OR c is greater than b" if either condition is true.

By using these conditions in if, else if, and else statements, you can control the flow
of your program based on various logical and comparison conditions.
7. Various Serial Methods
Here is an example that demonstrates various Serial methods in Arduino, including
initialization, sending and receiving data, and handling different data types.

Example 1: Reading and Printing a String

Code

void setup()
{
Serial.begin(9600); // Start serial communication at 9600 bps
Serial.println("Type a message and press Enter:");
}

void loop()
{
if (Serial.available())
{
String input = Serial.readString(); // Read the input as a string
Serial.print("You typed: ");
Serial.println(input); // Print the string
}
}
Example 2: Reading and Printing a Float

Code
void setup()
{
Serial.begin(9600); // Start serial communication at 9600 bps
Serial.println("Type a float value and press Enter:");
}

void loop()
{
if (Serial.available())
{
String input = Serial.readString(); // Read the input as a string
float floatValue = input.toFloat(); // Convert the string to float

Serial.print("You typed (float): ");


Serial.println(floatValue, 6); // Print the float value with 6 decimal places
}
}
Example 3: Reading and Printing a Double

Code
void setup()
{
Serial.begin(9600); // Start serial communication at 9600 bps
Serial.println("Type a double value and press Enter:");
}

void loop()
{
if (Serial.available())
{
String input = Serial.readString(); // Read the input as a string
double doubleValue = input.toDouble(); // Convert the string to double

Serial.print("You typed (double): ");


Serial.println(doubleValue, 6); // Print the double value with 6 decimal places
}
}
Example 4: Reading and Printing an Integer

Code
void setup()
{
Serial.begin(9600); // Start serial communication at 9600 bps
Serial.println("Type an integer and press Enter:");
}

void loop()
{
if (Serial.available())
{
int number = Serial.parseInt(); // Read the input as an integer

// Ensure to consume the newline character from the input buffer


while (Serial.available() && Serial.read() != '\n') { }

// Check if there was actual input


if (number != 0 || Serial.peek() == '0')
{
Serial.print("You typed: ");
Serial.println(number); // Print the integer
}
}
}

Example 5: Reading and Printing a Character


Code

void setup()
{
Serial.begin(9600); // Start serial communication at 9600 bps
Serial.println("Type a character and press Enter:");
}

void loop()
{
if (Serial.available())
{
char incomingChar = Serial.read(); // Read the input as a character

// Check if the character is printable


if (isPrintable(incomingChar))
{
Serial.print("You typed: ");
Serial.println(incomingChar); // Print the character
}
}
}

Summary
1. String
• Read: String input = Serial.readString();
• Print: Serial.println(input);
2. Float
• Read: float floatValue = Serial.readString().toFloat();
• Print: Serial.println(floatValue, 6);
3. Double
• Read: double doubleValue = Serial.readString().toDouble();
• Print: Serial.println(doubleValue, 6);
4. Integer
• Read: int number = Serial.parseInt();
• Print: Serial.println(number);
5. Character
• Read: char incomingChar = Serial.read();
• Print: Serial.println(incomingChar);

These examples should help you understand how to read and print different data types
using serial communication in Arduino.
7. Servo Motors
1. Basics of Servo Motors

Code

#include <Servo.h>

Servo myservo; // Create a servo object to control a servo

void setup()
{
myservo.attach(9); // Attach the servo to pin 9
}

void loop()
{
myservo.write(0); // Set servo to 0 degrees
delay(1000); // Wait for 1 second
myservo.write(90); // Set servo to 90 degrees
delay(1000); // Wait for 1 second
myservo.write(180); // Set servo to 180 degrees
delay(1000); // Wait for 1 second
}
2. Servo + For loop motor moving clock and anti-clock wise

Code

#include <Servo.h>

Servo myservo;

int pos = 0;

void setup()
{
myservo.attach(9);
}

void loop()
{
for(pos = 0; pos <= 180; pos += 1)
{
myservo.write(pos);
delay(15);
}

for(pos = 180; pos >= 180; pos -= 1)


{
myservo.write(pos);
delay(15);
}
}
3. Servo motor + potentiometer controller

Code

#include <Servo.h>

Servo Servo1;

int servoPin = 9;
int potPin = A0;

void setup()
{
Servo1.attach(servoPin);
}

void loop()
{
int reading = analogRead(potPin);
int angle = map(reading, 0, 1023, 0, 180);
Servo1.write(angle);
}
Mapping range

4. Servo + Sensor (distance control over motor movement)


Code

#include <Servo.h>
Servo servo1;
int trigPin = 7;
int echoPin = 6;
long distance;
long duration;

void setup()
{
servo1.attach(9);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);// put your setup code here, to run once:
}

void loop()
{
ultra();
servo1.write(0);
if(distance <= 10)
{
servo1.write(180);
}
}

void ultra()
{
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = duration*0.034/2;
}
8. Advanced I/O Functions
In Arduino, advanced input and output (I/O) functions are essential for interacting with
various sensors, actuators, and other components. Here, we'll delve into the details of
using analog inputs and outputs, digital inputs and outputs, working with sensors and
actuators, and debouncing techniques for buttons and switches.

Using Analog Inputs and Outputs


Analog Inputs
Analog inputs allow the Arduino to read a range of values from sensors, such as
temperature sensors, potentiometers, and light sensors. The Arduino's analog pins (A0
to A5) can read values ranging from 0 to 1023.

Serial Port
Example: Reading a Potentiometer

int potPin = A0; // Analog input pin connected to the potentiometer


int potValue = 0; // Variable to store the potentiometer value

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

void loop()
{
potValue = analogRead(potPin); // Read the analog input
Serial.println(potValue); // Print the value to the serial monitor
delay(100); // Wait for 100 milliseconds
}

Analog Outputs
Analog outputs (PWM) allow the Arduino to output a range of values to components like
LEDs and motors. PWM pins on the Arduino are marked with a '~' symbol (e.g., pins 3,
5, 6, 9, 10, 11).
Example: Controlling LED Brightness

int ledPin = 9; // PWM output pin connected to the LED


int brightness = 0; // Variable to store the brightness value

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

void loop()
{
for (brightness = 0; brightness <= 255; brightness++)
{ // Increase brightness
analogWrite(ledPin, brightness); // Set the brightness
delay(10); // Wait for 10 milliseconds
}
for (brightness = 255; brightness >= 0; brightness--)
{ // Decrease brightness
analogWrite(ledPin, brightness); // Set the brightness
delay(10); // Wait for 10 milliseconds
}
}

Digital Inputs and Outputs


Digital Inputs
Digital inputs allow the Arduino to read the state (HIGH or LOW) of digital sensors and
switches.
Example: Reading a Button

int buttonPin = 2; // Digital input pin connected to the button


int buttonState = 0; // Variable to store the button state

void setup()
{
pinMode(buttonPin, INPUT); // Set the button pin as an input
Serial.begin(9600); // Initialize serial communication at 9600 bps
}

void loop()
{
buttonState = digitalRead(buttonPin); // Read the digital input
Serial.println(buttonState); // Print the state to the serial
monitor
delay(100); // Wait for 100 milliseconds
}

Digital Outputs
Digital outputs allow the Arduino to control digital devices like LEDs, relays, and
motors.
Example: Controlling an LED

int ledPin = 13; // Digital output pin connected to the LED

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

void loop()
{
digitalWrite(ledPin, HIGH); // Turn the LED on
delay(1000); // Wait for 1 second
digitalWrite(ledPin, LOW); // Turn the LED off
delay(1000); // Wait for 1 second
}

Summary
• Analog Inputs/Outputs: Use analogRead() for inputs and analogWrite() for
PWM outputs.
• Digital Inputs/Outputs: Use digitalRead() and digitalWrite() for digital I/O.
9. Communication Functions
Arduino supports various communication protocols that allow it to communicate with
other devices, such as computers, sensors, and other microcontrollers. Here, we'll focus
on serial communication (UART), I2C, and SPI communication protocols, including
examples of how to write code for each.

Serial Communication (UART)


Serial communication is a simple and commonly used communication protocol. It uses
two wires: TX (transmit) and RX (receive).

I2C Communication Protocol


I2C (Inter-Integrated Circuit) is a two-wire communication protocol, which uses a
master-slave architecture.

• SDA (Data Line)


• SCL (Clock Line)
Example: Master Device Sending Data

#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x27, 16, 2);

void setup()
{
lcd.init();
lcd.backlight();
}

void loop()
{
lcd.setCursor(0, 0);
lcd.println("Henock");

lcd.setCursor(0, 1);
lcd.println("Hnk");
}

1. Display Potentiometer Voltage on I2C LCD

This Arduino program reads the value from a potentiometer, converts it to a voltage,
and displays the voltage on an I2C LCD. The code demonstrates the use of analog inputs,
serial communication, and I2C communication to interact with the LCD. The voltage is
updated and displayed every half second on both the Serial Monitor and the LCD screen.
Code:

#include <Wire.h>
#include <LiquidCrystal_I2C.h>

// Set the LCD address to 0x27 for a 16 chars and 2 line display
LiquidCrystal_I2C lcd(0x27, 16, 2);
const int potPin = A0; // Pin connected to the potentiometer

void setup()
{
Serial.begin(9600); // Initialize serial communication at 9600 bps
lcd.begin(16, 2); // Initialize the LCD with 16 columns and 2 rows
lcd.backlight(); // Turn on the backlight
lcd.clear(); // Clear the LCD screen
}

void loop()
{
int potValue = analogRead(potPin); // Read the potentiometer value
float voltage = potValue * (5.0 / 1023.0); // Convert the value to voltage

// Print the voltage to the Serial Monitor


Serial.print("Potentiometer Voltage: ");
Serial.println(voltage);

// Display the voltage on the LCD


lcd.setCursor(0, 0); // Set the cursor to the first row
lcd.print("Voltage: ");
lcd.setCursor(0, 1); // Set the cursor to the second row
lcd.print(voltage, 2); // Print the voltage with 2 decimal places
lcd.print(" V");

delay(500); // Wait for half a second before repeating


}

This program continuously updates and displays the voltage from the potentiometer,
demonstrating real-time data acquisition and display using Arduino and an I2C LCD.
2. Display Distance Measured by Ultrasonic Sensor on I2C LCD

This Arduino program uses an ultrasonic sensor to measure the distance to an object
and displays the measured distance on an I2C LCD. The distance is also printed to the
Serial Monitor. The code demonstrates the integration of an ultrasonic sensor with I2C
LCD display to provide real-time distance measurements.

Code:

#include <Wire.h>
#include <LiquidCrystal_I2C.h>

// Initialize the LCD with I2C address 0x27, 16 columns, and 2 rows
LiquidCrystal_I2C lcd(0x27, 16, 2);

// Pins for the ultrasonic sensor


const int trigPin = 9;
const int echoPin = 10;

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

// Initialize the LCD


lcd.begin(16, 2);
lcd.backlight();
lcd.clear();

// Initialize the ultrasonic sensor pins


pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}

void loop()
{
// Send a pulse to the ultrasonic sensor
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);

// Measure the duration of the echo pulse


long duration = pulseIn(echoPin, HIGH);

// Calculate the distance in centimeters


float distance = duration * 0.034 / 2;

// Print the distance to the Serial Monitor


Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");

// Display the distance on the LCD


lcd.setCursor(0, 0);
lcd.print("Distance: ");
lcd.setCursor(0, 1);
lcd.print(distance);
lcd.print(" cm");

// Wait for a bit before the next loop


delay(500);
}

This program integrates an ultrasonic sensor with an I2C LCD to measure and display
distances. The sensor sends out a pulse and measures the time it takes for the echo to
return, calculating the distance based on the speed of sound. The measured distance is
displayed on both the Serial Monitor and the LCD, providing a real-time distance
reading.
10. Light Sensitive Sensors
Light-sensitive sensors detect light levels and convert them into an electrical signal that
can be read by microcontrollers like the Arduino. The two most common types of light
sensors are Light Dependent Resistors (LDRs) and photodiodes.

1. Reading and Displaying LDR Values with Arduino


In this example, we will demonstrate how to read values from a Light Dependent
Resistor (LDR) using an Arduino. The LDR is a type of resistor whose resistance varies
based on the amount of light falling on it. By connecting the LDR to an analog input pin
on the Arduino, we can measure the light intensity and display the readings on the
Serial Monitor. This basic setup can be used as a foundation for more complex projects,
such as adjusting the brightness of an LED based on ambient light levels or creating a
light-sensitive alarm system.
Code:

const int LDR_PIN = A0;

void setup()
{
Serial.begin(9600);
}

void loop()
{
int ldr_value = analogRead(LDR_PIN);
Serial.print("LDR value: ");
Serial.println(ldr_value);
delay(1000); // wait for 1 second before reading again
}

This example provides a simple way to monitor light intensity using an LDR and an
Arduino, and display the readings on the Serial Monitor.
2. Controlling LED Brightness with an LDR and Displaying Values on
an I2C LCD
This project demonstrates how to control the brightness of an LED using an LDR (Light
Dependent Resistor) and display the LDR values on an I2C LCD. An LDR varies its
resistance based on the amount of light falling on it, which allows us to measure light
intensity. By reading the analog value from the LDR, we can adjust the brightness of an
LED accordingly. Additionally, the current LDR value is displayed on an I2C LCD,
providing real-time feedback of the light intensity.

Code:

#include <Wire.h>
#include <LiquidCrystal_I2C.h>

// Initialize the LCD with I2C address 0x27, 16 columns, and 2 rows
LiquidCrystal_I2C lcd(0x27, 16, 2);

// Pin for the LDR


const int LDR_PIN = A0;
// Pin for the LED
const int ledPin = 9;

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

// Initialize the LCD


lcd.begin(16, 2);
lcd.backlight();
lcd.clear();

// Initialize the LED pin as an output


pinMode(ledPin, OUTPUT);
}

void loop()
{
// Read the LDR value
int ldrValue = analogRead(LDR_PIN);

// Print the LDR value to the Serial Monitor


Serial.print("LDR value: ");
Serial.println(ldrValue);

// Map the LDR value to a PWM range (0-255) for LED brightness control
int ledBrightness = map(ldrValue, 0, 1023, 0, 255);

// Set the LED brightness


analogWrite(ledPin, ledBrightness);

// Display the LDR value and LED brightness on the LCD


lcd.setCursor(0, 0);
lcd.print("LDR Value: ");
lcd.setCursor(0, 1);
lcd.print(ldrValue);

// Wait for a bit before the next loop


delay(500);
}

This project reads the value from an LDR to adjust the brightness of an LED. The LDR
value is also displayed on an I2C LCD, providing real-time feedback of the light intensity.
This setup is useful for applications requiring automatic light adjustment based on
ambient light conditions, such as nightlights or light-sensitive alarms.
11. Understanding the Basics of Photodiodes
A photodiode is a semiconductor device that converts light into an electrical current.
The current is generated when photons are absorbed in the photodiode's active region.
Photodiodes are used in various applications, including light detection, optical
communication, and safety systems.

To map the range of the photodiode values to a more meaningful range, such as 0 to
100, you can use the map function in Arduino. This function is useful to scale the raw
analog values (which range from 0 to 1023) to a desired range.
Code:

const int photodiodePin = A0; // Pin connected to the photodiode

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

void loop()
{
int photodiodeValue = analogRead(photodiodePin); // Read the photodiode
value

// Map the photodiode value from 0-1023 to 0-100


int mappedValue = map(photodiodeValue, 0, 1023, 0, 100);

// Print the raw and mapped photodiode values to the Serial Monitor
Serial.print("Raw Photodiode value: ");
Serial.print(photodiodeValue);
Serial.print(" - Mapped value: ");
Serial.println(mappedValue);

delay(1000); // Wait for 1 second before reading again


}

This code reads the value from a photodiode and maps the raw analog value (0-1023) to
a more user-friendly range (0-100). The mapped value is then printed to the Serial
Monitor along with the raw value. This mapping is useful for scaling sensor values to a
desired range for further processing or display.
12. Reading Analog Sensor Values and Controlling an
LED Brightness
This Arduino sketch demonstrates how to read analog values from a sensor, map these
values to control the brightness of an LED, and print the sensor values to the Serial
Monitor. The sketch uses pin A0 for the analog sensor input and pin 2 for the LED
output. By reading the sensor values and mapping them to a PWM range, the brightness
of the LED is adjusted in real-time based on the sensor input.

Code:

int sensorValue = 0;

void setup()
{
pinMode(A0, INPUT);
Serial.begin(9600);
pinMode(2, OUTPUT);
}
void loop()
{
// read the value from the sensor
sensorValue = analogRead(A0);
// print the sensor reading so you know its range
Serial.println(sensorValue);
// map the sensor reading to a range for the LED
analogWrite(2, map(sensorValue, 0, 1023, 0, 255));
delay(100); // Wait for 100 millisecond(s)
}

The photodiode generates a current proportional to the light intensity, which is then read
by the Arduino's analog input pin and displayed on the Serial Monitor. This setup can be
expanded for various applications, such as creating light-sensitive alarms or adjusting the
brightness of an LED based on ambient light conditions.
13. Using Interrupt Functions in Arduino
This example demonstrates how to use interrupt functions in Arduino to handle real-time
events. Interrupts allow the Arduino to respond immediately to a change in a pin's state,
bypassing the main program loop. In this example, we will use a button to trigger an
interrupt that toggles the state of an LED. This setup ensures that the LED changes state
immediately when the button is pressed, regardless of what the main loop is doing.

Code:

const int buttonPin = 2; // Pin connected to the button


const int ledPin = 13; // Pin connected to the LED
volatile bool ledState = false; // LED state variable

void setup()
{
pinMode(buttonPin, INPUT_PULLUP); // Set the button pin as input with
internal pull-up resistor
pinMode(ledPin, OUTPUT); // Set the LED pin as output
attachInterrupt(digitalPinToInterrupt(buttonPin), toggleLED, FALLING); //
Attach interrupt to the button pin
}

void loop()
{
// Main loop does nothing, all action happens in the interrupt
}
// Interrupt service routine to toggle the LED
void toggleLED()
{
ledState = !ledState; // Toggle the LED state
digitalWrite(ledPin, ledState); // Write the LED state
}

This example demonstrates how to use interrupts in Arduino to handle real-time


events. By attaching an interrupt to a button pin, the Arduino can immediately respond
to button presses by toggling the state of an LED. This approach ensures that the LED
responds instantly to button presses, regardless of the execution of the main program
loop. Interrupts are useful for handling time-sensitive tasks and events that require
immediate attention.
2. Test 3 Preparation

This session will focus on


practical evaluations under test
conditions, specifically
covering Binary Counters,
Motors, and the Infrared
Transmitter and Receiver
Module.
REFERNCES
[1] YouTube, "My Official Channel," YouTube, Available:
https://www.youtube.com/channel/UCaLDS2fvP0E4oTWv_RkMMTg.

[2] henockhnk, "Learn WebGL," YouTube, Available:


https://www.youtube.com/watch?v=dX6DpkWcv7c&list=PLrZbkNpNVSwzugPtGNOBa5R
7LO_vgxg4p.

[3] henockhnk, "hOVx02rbs78," YouTube, Available:


https://www.youtube.com/watch?v=hOVx02rbs78&list=PLrZbkNpNVSwwzMtG_VGgIL1B
gt2P8QBNw.

[4] henockhnk, "RyMdYZ6m4cg," YouTube, Available:


https://www.youtube.com/watch?v=RyMdYZ6m4cg&list=PLrZbkNpNVSwwtSPeQ3h9biyT
DXjGMyZw_.

[5] henockhnk, "P8_Ndp47SmA," YouTube, Available:


https://www.youtube.com/watch?v=P8_Ndp47SmA&list=PLrZbkNpNVSwy9xNtR8ecrPq_2
dG_T75iS.

[6] henockhnk, "TikTok," TikTok, Available: https://www.tiktok.com/@henockhnk?lang=en.

[7] henockhnk, "TikTok," TikTok, Available:


https://www.tiktok.com/@henockhnk?is_from_webapp=1&sender_device=pc.

[8] henockhnk, "GitHub - henockhnk," GitHub, Available: https://github.com/henockhnk.


[9] hnk, "Stack Overflow - hnk," Stack Overflow, Available:
https://stackoverflow.com/users/21151442/hnk.
____________
LEARN ARDUINO
B E C O M E R E A D Y

Summary: This textbook provides a comprehensive guide to


Arduino programming, covering basic and advanced concepts in
electronics and microcontroller applications.

Subtitle: Master the Art of Arduino programming and electronics.


Learn, Create, and Explore Fascinating Arduino Projects.

Author information: Henock, also known as HNK, is a computer


engineering student with a passion for combining technology and
design. He seeks simplicity and elegance in his code and strives to
deliver intuitive user experiences. With his background in
engineering and design, Henock brings a unique perspective and
wealth of knowledge to his writing on Arduino technology.

Discover how to bring electronics to life


HORIZON
through dynamic interactive projects and HNK
innovative applications.

You might also like