UNIT 3 - Introduction To Arduino Programming
UNIT 3 - Introduction To Arduino Programming
UNIT 3 - Introduction To Arduino Programming
programming
Introduction to Arduino
Arduino is a widely-used open-source platform for building electronics projects, especially in the
context of IoT (Internet of Things). It consists of a simple development board with a built-in
microcontroller and an easy-to-use software interface known as the Arduino IDE (Integrated
Development Environment). The combination of hardware and software makes Arduino an
excellent starting point for beginners and professionals alike in the world of electronics and
programming.
● Smart Homes: You can integrate various sensors (e.g., temperature, humidity, motion)
with Arduino to automate tasks in a smart home, such as controlling lights, heating, or
security systems based on real-time data.
● Smart Cities: Arduino can be used in applications like smart street lighting, air quality
monitoring, and waste management systems, where real-time data collection and
decision-making are critical.
● Healthcare and Smart Hospitals: IoT-based medical devices, such as temperature or
heartbeat monitors, can be easily developed using Arduino to assist in patient care and
health monitoring.
● Smart Transportation: Arduino can be used for applications like vehicle tracking, traffic
management, and intelligent transportation systems.
Arduino UNO
The Arduino UNO is one of the most popular and widely used Arduino boards. It is not the first
board released, but it has become the go-to choice for beginners and advanced users alike, due
to its simplicity, versatility, and extensive community support.
The Arduino UNO, based on the ATMEGA328P microcontroller, is known for its reliability and
ease of use. Below are its main features:
● Operating Voltage: 5V
○ The Arduino UNO runs at a standard 5V operating voltage, which is the most
common voltage for digital electronics.
● Input Voltage Range: 7V to 12V (recommended) / 6V to 20V (acceptable range)
○ This range ensures the Arduino UNO can work with a variety of power supplies,
such as batteries or wall adapters. However, a regulated 9V supply is typically
recommended.
● Digital I/O Pins: 14
○ The Arduino UNO has 14 digital I/O pins that can be used as either inputs or
outputs, allowing for flexible interfacing with sensors, switches, LEDs, motors,
etc.
● Analog Input Pins: 6
○ The board has 6 analog input pins (A0 to A5), used for reading analog signals
(e.g., from temperature sensors, light sensors, etc.).
● DC Current per I/O Pin: 40mA (maximum)
○ Each input/output pin can supply or sink up to 40mA of current. Exceeding this
value could damage the board, so it’s important to use appropriate resistors and
external components.
● Flash Memory: 32 KB
○ The ATMEGA328P microcontroller on the Arduino UNO has 32 KB of flash
memory, which is used to store the uploaded program (sketch). Of this, around 2
KB is used by the bootloader, leaving around 30 KB for the program.
Additional Features:
● USB Interface:
○ The Arduino UNO can be connected to a computer via USB for programming and
serial communication. The board has a built-in USB-to-serial converter for easy
communication between the board and your computer.
● Power Supply:
○ The Arduino UNO can be powered either through the USB connection or by an
external power supply (e.g., a 9V battery or wall adapter).
● LED Indicator:
○ The Arduino UNO includes a built-in LED on pin 13, which is useful for testing
simple programs and debugging.
● IoT Projects: Building connected devices for smart homes, smart agriculture, or weather
stations.
● Prototyping: Perfect for rapid prototyping of electronic projects due to its simplicity and
large ecosystem of components.
● Robotics: Used in robots for controlling motors, sensors, and communication.
● Home Automation: Arduino UNO can control appliances and lights in a smart home
setup.
● Wearable Tech: Simple wearable devices like fitness trackers can be built using Arduino
boards.
Power Supply
The Arduino Uno features 14 digital I/O pins which can be used for both input and output
operations. These can be controlled with functions like pinMode(), digitalWrite(), and
digitalRead().
TX and RX LEDs
The TX (transmit) and RX (receive) LEDs on the Arduino Uno indicate serial communication
activity.
● TX LED: Flashes when data is being sent from the Arduino.
● RX LED: Flashes when data is being received by the Arduino.
Both LEDs are connected to pins 0 (RX) and 1 (TX), which are used for UART serial
communication.
Digital I/O
● The Arduino Uno has 14 digital I/O pins (pins 0 to 13), which can be used for both
reading and writing digital values (HIGH or LOW).
● 6 of these pins (pins 3, 5, 6, 9, 10, 11) support PWM output, indicated by the ~ symbol.
● You can use these pins for controlling devices like motors, LEDs, and relays, or reading
signals from switches, sensors, and buttons.
● AREF (Analog Reference) is used to provide an external reference voltage for the
analog inputs (A0 to A5). By default, the reference is set to 5V, but you can change it to
any value between 0 and 5V.
Reset Pin
● The Reset pin allows you to restart the Arduino's program from the beginning, useful
when debugging or after uploading a new sketch.
● The board also has a built-in reset button to perform the same action.
Memory
The ATmega328P microcontroller used on the Arduino Uno has the following memory
configuration:
Communication
● The Arduino Uno supports UART TTL serial communication through pins TX (1) and
RX (0). You can communicate with a computer via the USB port using the built-in Serial
Monitor in the Arduino IDE.
● TX and RX LEDs on the board blink when serial data is being transmitted or received.
Arduino Reset
You can reset the Arduino Uno in two ways:
1. Using the Reset Button: Simply press the reset button on the board to restart the
program.
2. Using the RESET Pin: Connect an external reset button to the RESET pin to manually
reset the board.
Pin description:
How to Program Arduino
Once the circuit is set up on the breadboard, you'll need to upload the program (called a
sketch) to the Arduino. The sketch contains a series of instructions that guide the Arduino on
what actions to perform. The Arduino IDE (Integrated Development Environment) is the
software used to write and upload these sketches to the Arduino board.
1. void setup():
○ This function is called once when the program starts. It is used to set up the initial
configuration for the board, like setting pin modes (input or output), initializing
libraries, or starting serial communication.
Example:
void setup() {
pinMode(13, OUTPUT); // Set pin 13 as an output
}
○
2. void loop():
○ This function runs repeatedly after setup() has finished. The code inside the
loop() function keeps running until the board is powered off or reset.
Example:
void loop() {
digitalWrite(13, HIGH); // Turn the LED on
delay(1000); // Wait for 1 second
digitalWrite(13, LOW); // Turn the LED off
delay(1000); // Wait for 1 second
}
Operators in Arduino
Operators are used to perform operations on variables and data. Logical operators are
commonly used in if statements, while loops, and other conditional structures.
● Logical Operators:
if (a || b) {
// Executes if either a or b is true
}
if (a && b) {
// Executes if both a and b are true
}
if (!a) {
// Executes if a is false
}
Control statements allow you to make decisions or repeat actions in the program. Here are
some key control statements:
1. IF Statement:
if (condition) {
// Code to execute if condition is true
}
○
2. ELSE Statement:
if (condition) {
// Code if true
} else {
// Code if false
}
○
3. ELSE IF Statement:
○
4. FOR Statement:
○
5. WHILE Statement:
while (condition) {
// Code to repeat while condition is true
}
○
6. DO-WHILE Statement:
Similar to while, but the code inside the loop runs at least once before checking the condition.
do {
// Code to execute at least once
} while (condition);
○
7. SWITCH-CASE Statement:
Used to select one of many code blocks to execute based on a variable's value.
switch (variable) {
case 1:
// Code for case 1
break;
case 2:
// Code for case 2
break;
default:
// Code if no case matches
}
Loop Statements
1. WHILE Loop:
Runs as long as the condition is true. The loop may run infinitely if the condition is always true.
while (condition) {
// Code to repeat while condition is true
}
2. DO-WHILE Loop:
Similar to while, but it tests the condition after executing the loop body, ensuring that the loop
runs at least once.
do {
// Code to execute at least once
} while (condition);
3. FOR Loop:
Executes a set number of times. It's great for looping over ranges or collections.
4. Nested Loop:
You can place one loop inside another. This is useful for tasks like iterating through a 2D array.
5. Infinite Loop:
A loop that has no termination condition, causing it to run endlessly until the Arduino is powered
off.
while (true) {
// Code to run endlessly
}
One of the simplest Arduino programs is blinking an LED. It tests whether your Arduino board is
working and properly configured.
Code Example:
const int LED = 13; // LED connected to digital pin 13
void setup() {
pinMode(LED, OUTPUT); // Set pin 13 as output
}
void loop() {
digitalWrite(LED, HIGH); // Turn the LED on
delay(1000); // Wait for 1 second
digitalWrite(LED, LOW); // Turn the LED off
delay(1000); // Wait for 1 second
}
Program Explanation:
The initial code you provided will cause the LED to blink rapidly because the button press is
being detected too quickly. To make it more reliable, we need to add some logic to debounce
the button. This means ensuring that the button press is registered only once, even if it's
physically pressed multiple times due to bouncing.
void setup() {
pinMode(LED, OUTPUT); // LED pin as output
pinMode(BUTTON, INPUT); // BUTTON pin as input
}
void loop() {
int reading = digitalRead(BUTTON); // read the button input
Explanation:
1. Button Debouncing:
○ The main issue with the original code is that when you press a button, there are
tiny fluctuations in the signal, causing the Arduino to register multiple presses.
This is known as button bouncing. The debounceDelay (set to 50
milliseconds) ensures that the button state changes are only registered after this
delay, eliminating multiple readings from a single press.
2. Button State Management:
○ currentButtonState is used to track whether the button has been pressed or
released.
○ lastButtonState is used to compare the previous state of the button to the
current state, which helps detect a state change (press or release).
3. Toggling the LED:
○ state is the variable that keeps track of whether the LED should be ON or OFF
(1 for ON, 0 for OFF).
○ state = 1 - state; is a clever way to toggle the state. When the button is
pressed, it changes the state from 1 to 0, or 0 to 1, flipping the LED on or off.
4. LED Control:
○ If state == 1, the LED is turned on (digitalWrite(LED, HIGH)).
○ If state == 0, the LED is turned off (digitalWrite(LED, LOW)).
Behavior:
● The LED will now toggle between on and off each time you press the button, with proper
debouncing to avoid rapid toggling or multiple state changes.
In an Arduino project, sensors and actuators work together to interact with the physical
environment. Sensors convert physical parameters (like temperature, light, humidity) into
electrical signals that the Arduino can read. Actuators, on the other hand, respond to the signals
from the Arduino and perform physical actions (such as turning on an LED or moving a motor).
Let's explore a few common types of sensors and how to interface them with Arduino.
Types of Sensors
The DHT sensors can read both temperature and humidity values. These sensors have the
following pins:
To interface the DHT sensor with Arduino, you'll need to use a special library. The library
functions are:
#include "DHT.h"
void setup() {
Serial.begin(9600);
dht.begin();
}
void loop() {
float humidity = dht.readHumidity();
float temperature = dht.readTemperature(); // Read temperature in
Celsius
if (isnan(humidity) || isnan(temperature)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
Serial.print("Humidity: ");
Serial.print(humidity);
Serial.print("% Temperature: ");
Serial.print(temperature);
Serial.println("C");
The TMP36 is an analog temperature sensor that provides a voltage output corresponding to
the temperature. Here's an example of how to read the temperature data using the TMP36
sensor.
void setup() {
Serial.begin(9600);
}
void loop() {
float voltage, degreesC, degreesF;
voltage = getVoltage(temperaturePin); // Get the voltage from the
analog pin
degreesC = (voltage - 0.5) * 100.0; // Convert voltage to
temperature in Celsius
Serial.print("Voltage: ");
Serial.print(voltage);
Serial.print(" V Degrees Celsius: ");
Serial.println(degreesC);
A light sensor (also known as a photocell) is used to detect the intensity of light. The
resistance of the photocell decreases with an increase in light intensity.
In this example, the Arduino will turn an LED on when it detects low light (dark), and turn it off
when the light intensity is high.
void setup() {
Serial.begin(9600); // Start serial communication at 9600 baud rate
pinMode(ledPin, OUTPUT); // Set the LED pin as output
}
void loop() {
photocellReading = analogRead(photocellPin); // Read the light
sensor value
Serial.print("Light intensity: ");
Serial.println(photocellReading); // Print the sensor value to
Serial Monitor
// If it's dark (light intensity is below threshold), turn on the
LED
if (photocellReading < limit) {
digitalWrite(ledPin, HIGH); // Turn on the LED
} else {
digitalWrite(ledPin, LOW); // Turn off the LED
}
Key Concepts
Actuators are devices that convert energy or signals into mechanical motion. They play a vital
role in providing controlled motion to various components in a mechanical system. In the case of
Arduino projects, actuators like servo motors allow precise control over motion, making them
suitable for a wide range of applications like robotics, automation, and remote-controlled
devices.
Servo Motors
A servo motor is an electromechanical actuator that allows for precise control of angular
position, velocity, and acceleration. Unlike a regular DC motor, which just rotates continuously, a
servo motor can rotate to a specific position, usually within a range of 0 to 180 degrees,
depending on the servo.
The working principle of a servo motor involves gears and mechanical components that help
achieve precise movement. When an input signal is provided, the feedback circuit adjusts the
motor's position to match the desired angle. This makes the servo highly accurate and efficient
compared to regular motors.
To control a servo motor with Arduino, you only need three connections:
The Arduino uses PWM (Pulse Width Modulation) signals to control the servo. By sending
different PWM signals, you can control the angle at which the servo arm moves.
In this example, we will control the servo motor to move to different positions (0, 90, and 180
degrees) using the Servo library in Arduino.
void setup() {
// Attach the servo object to the specified pin
Servo1.attach(servoPin);
}
void loop() {
// Move the servo to 0 degrees (initial position)
Servo1.write(0);
delay(1000); // Wait for 1 second
1. Library: #include <Servo.h> includes the Servo library, which makes it easier to
control the servo motor.
2. Servo Object: Servo1.attach(servoPin) attaches the servo motor to the specified
pin (in this case, pin 3).
3. Servo Control: The Servo1.write(angle) function is used to set the desired angle
of the servo. The servo can be set to any position between 0 and 180 degrees.
4. Delay: The delay(1000) function waits for 1 second (1000 milliseconds) before
moving to the next position.
1. Robotic Arms: Servo motors control the movement of the arm to pick up objects.
2. Automated Systems: Used in systems like door locks, camera gimbals, etc.
3. RC Vehicles: In remote-controlled cars, servo motors control the steering mechanism.
Circuit diagram:
Linear actuators are devices that produce linear motion from rotational energy. They are
commonly used in various applications, such as in robotics, automation systems, and adjustable
furniture. You can control linear actuators using an Arduino by interfacing it with a motor driver
and programming the Arduino to send control signals.
Overview:
The Arduino controls the direction and speed of the actuator using digital pins, often through a
motor driver like an H-Bridge. The linear actuator moves forward or backward based on the
control signals sent by the Arduino.
Hardware Setup:
void setup() {
// Initialize the digital pins as outputs
pinMode(ENABLE1, OUTPUT);
pinMode(FWD1, OUTPUT);
pinMode(REV1, OUTPUT);
}
void loop() {
Speed = 255; // Set speed between 0 and 255 (255 is max speed)
1. Pin Setup:
○ ENABLE1 is the pin that enables the motor. When it is HIGH, the motor driver is
activated. When LOW, it is deactivated.
○ FWD1 and REV1 are the control pins for the forward and reverse directions of the
actuator. These pins use PWM signals to control the speed of the motor.
2. Functions:
○ Forward(): Sets the actuator to move forward. It enables the motor and applies
PWM to the forward pin while keeping the reverse pin off.
○ Reverse(): Sets the actuator to move backward by applying PWM to the
reverse pin and turning off the forward pin.
○ Stop(): Stops the actuator by disabling the motor and setting both direction pins
to zero.
3. Speed Control: The Speed variable controls the speed of the actuator. You can adjust
the PWM value (0 to 255) to set the desired speed. A value of 255 corresponds to
maximum speed, while 0 stops the actuator.
4. Timing:
○ The actuator moves forward for 5 seconds (delay(5000)) and then stops for 1
second (delay(1000)).
○ Afterward, the actuator moves backward for 5 seconds and stops again.
Additional Notes:
● Power Considerations: Make sure your motor driver and power supply can handle the
current required by the linear actuator.
● Motor Driver: The example assumes you are using a motor driver (e.g., L298N) to
control the linear actuator. Make sure to connect the motor driver correctly to your
Arduino and external power supply.
● Adjusting Speed: You can adjust the Speed variable in the code to make the actuator
move faster or slower. Values closer to 0 will make the actuator move slower, while
values closer to 255 will make it move faster.
● External Power Supply: Linear actuators typically need more current than the Arduino
can supply. Ensure you're using an external power supply for the actuator.