Learn Arduino HNK
Learn Arduino HNK
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
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
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
Code
void setup()
{
Serial.begin(9600); // Initialize serial communication at 9600 bps
}
void loop()
{
int a = 10;
int b = 5;
double pi = 3.14159;
double radius = 2.5;
double area = pi * radius * radius; // Calculate the area of a circle
Serial.print("Sum: ");
Serial.println(sum);
Serial.print("Difference: ");
Serial.println(diff);
Serial.print("Product: ");
Serial.println(prod);
Serial.print("Quotient: ");
Serial.println(quot);
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.
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();
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.
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
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.
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.
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.
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.
Integer Array
void setup()
{
Serial.begin(9600); // Initialize serial communication at 9600 bps
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
}
// 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
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.
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");
}
// Greater than
if (c > b)
{
Serial.println("c is greater than b");
}
// 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.
8. Logical OR (||):
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.
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
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
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
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
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>
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);
}
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
#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.
Serial Port
Example: Reading a Potentiometer
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
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
}
}
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
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.
#include <LiquidCrystal_I2C.h>
void setup()
{
lcd.init();
lcd.backlight();
}
void loop()
{
lcd.setCursor(0, 0);
lcd.println("Henock");
lcd.setCursor(0, 1);
lcd.println("Hnk");
}
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
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);
void setup()
{
// Initialize serial communication
Serial.begin(9600);
void loop()
{
// Send a pulse to the ultrasonic sensor
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
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.
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);
void setup()
{
// Initialize serial communication
Serial.begin(9600);
void loop()
{
// Read the LDR value
int ldrValue = analogRead(LDR_PIN);
// Map the LDR value to a PWM range (0-255) for LED brightness control
int ledBrightness = map(ldrValue, 0, 1023, 0, 255);
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:
void setup()
{
Serial.begin(9600); // Initialize serial communication at 9600 bps
}
void loop()
{
int photodiodeValue = analogRead(photodiodePin); // Read the photodiode
value
// 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);
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:
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
}