UNIT 3 - Introduction To Arduino Programming

Download as pdf or txt
Download as pdf or txt
You are on page 1of 27

UNIT 3: Introduction to Arduino

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.

Key Features of Arduino:

1. Open-Source and Programmable:


○ Arduino is open-source, meaning both the hardware and software are freely
available for modification and improvement. This makes it a versatile and
customizable platform for various applications.
2. Simple Development Environment (IDE):
○ The Arduino IDE is user-friendly and allows for easy development and upload of
programs (called "sketches") to the Arduino board. The IDE supports both analog
and digital inputs and outputs, making it suitable for a wide range of projects.
3. No Operating System:
○ Unlike more complex platforms like Raspberry Pi, Arduino operates without an
operating system. You simply load a single program, which is then executed on
the board. This makes it much simpler and faster to use for specific tasks.
4. Built-in Microcontroller:
○ The heart of the Arduino board is its microcontroller, which is responsible for
running the programs you upload. The microcontroller is capable of handling both
analog and digital signals, enabling a broad range of sensor-based applications.
5. Ease of Programming:
○ For those familiar with older microcontrollers like the 8051 or 8085, programming
an Arduino is much simpler. You don’t need any additional programming
hardware (like a separate programmer or complex interfacing ICs). The Arduino
board can be programmed directly through a USB connection.
6. Input and Output:
○ Arduino accepts both analog and digital inputs (e.g., sensors measuring
temperature, light, motion) and can produce digital outputs (e.g., turning on an
LED, controlling motors). This versatility makes it ideal for interactive projects.
7. Cost-Effective:
○ Arduino boards are relatively inexpensive compared to other development
platforms, making them an excellent choice for both learning and prototyping.
They also have a large community and many tutorials available, which further
lowers the barrier to entry.

Using Arduino in IoT Projects:

● 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.

How Arduino Works:

1. Installing the IDE:


○ To start programming an Arduino, the first step is to install the Arduino IDE on
your computer. It’s available for Windows, macOS, and Linux.
2. Uploading a Program (Sketch):
○ Once the IDE is installed, you can write a program (a "sketch") to control the
Arduino board. These sketches can involve reading inputs from sensors,
processing the data, and controlling outputs like LEDs or motors.
3. Connecting the Arduino:
○ After writing the program, you connect the Arduino to your computer via USB and
upload the sketch. There’s no need for additional hardware; the USB cable both
powers the Arduino and uploads the program.
4. Running the Program:
○ Once the program is uploaded, the Arduino will run it indefinitely until it is either
powered off or reprogrammed. Unlike systems with an operating system, there
are no background tasks or updates—only the specific program you uploaded
runs on the microcontroller.

Why Choose Arduino for IoT Projects?

● Simplicity: The ease of use, combined with a straightforward programming model,


makes Arduino ideal for beginners in the electronics and IoT space.
● Flexibility: It can handle a variety of tasks, from basic sensor data collection to
controlling complex actuators in a system.
● Community and Support: The large Arduino community provides ample resources,
tutorials, and libraries, which can speed up development and problem-solving.
● Scalability: Although it’s simple enough for beginners, Arduino can be used in more
complex IoT systems as well, offering scalability from small projects to larger ones.

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.

Types of Arduino Boards:

1. Arduino Boards Based on ATMEGA328 Microcontroller:


○ These boards are widely used and include models like the Arduino Uno, which
uses the ATMEGA328 microcontroller. These boards are great for beginners and
are supported by a large number of libraries and examples.
2. Arduino Boards Based on ATMEGA32u4 Microcontroller:
○ These boards are used in projects where USB communication is needed. An
example is the Arduino Leonardo, which uses the ATMEGA32u4 microcontroller
and has built-in USB support.
3. Arduino Boards Based on ATMEGA2560 Microcontroller:
○ These are more advanced boards with greater processing power and more
input/output pins, used for larger projects. The Arduino Mega is an example, with
a larger memory and more pins than the Uno.
4. Arduino Boards Based on AT91SAM3X8E Microcontroller:
○ This is a more powerful microcontroller found in boards like the Arduino Due. The
Arduino Due has 32-bit processing, making it suitable for more computationally
demanding tasks.

Features of Arduino UNO:

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.

Applications of Arduino UNO:

● 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 can be powered through two main methods:


1. USB Power:
○ The Arduino board can be powered directly via a USB cable connected to a
computer. This is commonly used for programming and serial communication.
2. External Power Supply:
○ The Arduino Uno can be powered using an external power supply like an
AC-to-DC adapter or a battery.
○ To connect an external power supply:
■ AC to DC Adapter: Plug it into the power jack on the Arduino board.
■ Battery: Connect the battery leads to the Vin pin and the GND pin of the
power connector. This ensures the Arduino gets the correct voltage.
3. The recommended voltage for the external power supply is 7V to 12V.

Input & Output Pins

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().

● Pin 2 & Pin 3 (External Interrupts):


○ These pins can trigger interrupts, allowing you to react to changes in input values
(e.g., from a sensor or button).
● Pins 3, 5, 6, 9, 10, 11 (PWM):
○ These pins are capable of PWM (Pulse Width Modulation) output, which allows
you to simulate analog output. You can control the brightness of LEDs, motor
speed, etc., using the analogWrite() function.
● SPI Pins (Pins 10, 11, 12, 13):
○ These pins are used for SPI (Serial Peripheral Interface) communication. Even
though SPI is supported by the hardware, it is not part of the core Arduino
language. You'll need additional libraries to use these for communication.
○ Pin 10: SS (Slave Select)
○ Pin 11: MOSI (Master Out Slave In)
○ Pin 12: MISO (Master In Slave Out)
○ Pin 13: SCK (Serial Clock)
● Pin 13 (LED):
○ This pin is connected to the on-board LED. When you set it to HIGH, the LED will
light up, and when set to LOW, the LED will turn off.
● Pin 4 (SDA) & Pin 5 (SCL) (I2C):
○ These pins are used for I2C communication with other devices, like sensors
and displays. You can use the Wire library to implement I2C communication.

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)

● 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:

● Flash Memory: 32 KB (for storing the program code)


● SRAM: 2 KB (for temporary data storage during execution)
● EEPROM: 1 KB (for storing persistent data that is not erased when the Arduino is
powered off)

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.

Structure of an Arduino Sketch

Every Arduino sketch has two main parts:

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:

OR (||): Returns true if either condition is true.

if (a || b) {
// Executes if either a or b is true
}

AND (&&): Returns true only if both conditions are true.

if (a && b) {
// Executes if both a and b are true
}

NOT (!): Reverses the logical state of a condition.

if (!a) {
// Executes if a is false
}

Arduino Control Statements

Control statements allow you to make decisions or repeat actions in the program. Here are
some key control statements:

1. IF Statement:

Used to check a condition and execute a block of code if it's true.

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


2. ELSE Statement:

Used to execute a different block of code if the if condition is false.

if (condition) {
// Code if true
} else {
// Code if false
}


3. ELSE IF Statement:

Checks multiple conditions in a series.


if (condition1) {
// Code if condition1 is true
} else if (condition2) {
// Code if condition2 is true
} else {
// Code if all conditions are false
}


4. FOR Statement:

A loop used to repeat a block of code a set number of times.

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


// Code to repeat 10 times
}


5. WHILE Statement:

Repeats a block of code as long as the condition is true.

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

Loops allow you to repeat actions multiple times:

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.

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


// Code to repeat 10 times
}

4. Nested Loop:

You can place one loop inside another. This is useful for tasks like iterating through a 2D array.

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


for (int j = 0; j < 3; j++) {
// Code to execute for each combination of i and j
}
}

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
}

Example: LED Blinking Program

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:

● setup(): Sets pin 13 as an output (this happens once).


● loop(): Repeats the following steps:
○ Turn the LED on by setting pin 13 to HIGH.
○ Wait for 1 second (delay(1000)).
○ Turn the LED off by setting pin 13 to LOW.
○ Wait for another second.
○ Repeat the loop.
Example: Turn On LED While Button is Pressed

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.

Here's the updated code with an explanation:

const int LED = 13; // the pin for the LED


const int BUTTON = 7; // the input pin where the pushbutton is
connected
int val = 0; // val will store the state of the input pin
int state = 0; // state will store LED state (0 or 1)
int lastButtonState = 0; // previous state of the button
int currentButtonState = 0; // current state of the button
unsigned long lastDebounceTime = 0; // last time button state was
checked
unsigned long debounceDelay = 50; // debounce time; increase if
necessary

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

// Check if the button state has changed (i.e., a press or


release)
if (reading != lastButtonState) {
lastDebounceTime = millis(); // reset debounce timer
}

// Only change the state if enough time has passed (debounced)


if ((millis() - lastDebounceTime) > debounceDelay) {
// If the button has been pressed (HIGH), toggle LED state
if (reading == HIGH && currentButtonState == 0) {
state = 1 - state; // Toggle the state (1 becomes 0, 0
becomes 1)
currentButtonState = 1; // Update the current button
state to pressed
} else if (reading == LOW) {
currentButtonState = 0; // Update the current button
state to released
}
}

// Apply the state to the LED (ON or OFF)


if (state == 1) {
digitalWrite(LED, HIGH); // Turn LED ON
} else {
digitalWrite(LED, LOW); // Turn LED OFF
}
lastButtonState = reading; // Store the current state for the
next loop
}

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.

Integration of Sensors and Actuators with Arduino

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

Some commonly used sensors include:

1. Temperature Sensor: Measures temperature in Celsius or Fahrenheit.


2. Humidity Sensor: Measures the amount of moisture in the air.
3. Compass Sensor: Measures orientation based on the Earth's magnetic field.
4. Light Sensor: Measures the intensity of light in the surroundings.
5. Sound Sensor: Detects sound levels.
6. Accelerometer: Measures acceleration or changes in movement.

Sensor Interface with Arduino

1. Digital Humidity and Temperature Sensor (DHT11/DHT22)

The DHT sensors can read both temperature and humidity values. These sensors have the
following pins:

● PIN 1 (VCC): 3.3V or 5V Power supply


● PIN 2 (Data): Data pin for reading temperature and humidity
● PIN 3 (NC): Not connected
● PIN 4 (Ground): Ground pin

To interface the DHT sensor with Arduino, you'll need to use a special library. The library
functions are:

● dht.readHumidity(): Reads the humidity value.


● dht.readTemperature(): Reads the temperature value.

Here's an example of how to interface the DHT sensor with Arduino:

#include "DHT.h"

#define DHTPIN 2 // Pin connected to DHT sensor


#define DHTTYPE DHT11 // DHT 11 sensor

DHT dht(DHTPIN, DHTTYPE);

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");

delay(2000); // Wait for 2 seconds before reading again


}

2. TMP36 Temperature Sensor

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.

const int temperaturePin = A0; // Pin where TMP36 is connected

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);

delay(1000); // Repeat once per second


}

3. Light Sensor (Photocell)

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.

int photocellPin = A0; // Pin where the photocell is connected


int ledPin = 13; // Pin where the LED is connected
int photocellReading; // Variable to store the light sensor reading
const float limit = 500; // Threshold value to determine dark/light

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
}

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


}

Key Concepts

1. Analog vs. Digital Sensors:


○ Analog Sensors: Provide a range of values (e.g., light sensor, temperature
sensor) and require an analogRead() to get the input value.
○ Digital Sensors: Provide only two states (e.g., HIGH or LOW) and require a
digitalRead().
2. Actuators:
○ Actuators (like LEDs, motors, or servos) are controlled based on the input from
sensors. For instance, you can turn on an LED when the light intensity is low, or
move a motor when a certain condition is met.
3. Sensor Calibration:
○ Some sensors, like temperature sensors, require calibration to ensure accurate
readings. Always check the datasheet for the sensor's specifications and
formulas to properly convert raw readings.

Actuators: Integration with Motors (Servo Motors)

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.

Components of a Servo Motor:

1. Motor: Provides the motion.


2. Feedback Circuit: Ensures the motor knows its current position.
3. Motor Driver: Controls the movement of the motor based on the input signal.

How Servo Motors Work:

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.

Integrating Servo Motors with Arduino

To control a servo motor with Arduino, you only need three connections:

1. Power (VCC): Powers the motor (usually 5V or 6V depending on the servo's


requirement).
2. Ground (GND): Connects to the ground.
3. Control Pin: The pin through which the Arduino will send signals to control the servo's
position.

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.

Arduino Code for Controlling a Servo Motor

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.

// Include the Servo library to control the servo


#include <Servo.h>
// Define the pin connected to the servo
int servoPin = 3;

// Create a servo object


Servo Servo1;

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

// Move the servo to 90 degrees (middle position)


Servo1.write(90);
delay(1000); // Wait for 1 second

// Move the servo to 180 degrees (end position)


Servo1.write(180);
delay(1000); // Wait for 1 second
}

Explanation of the Code:

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.

Practical Applications of Servo Motors:

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:

Using Arduino with Linear Actuators

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:

1. Arduino Board: For controlling the actuator.


2. Motor Driver (H-Bridge): For controlling the direction and speed of the actuator's motor.
3. Linear Actuator: The device that converts rotational motion into linear motion.
4. External Power Supply: Linear actuators often require more power than the Arduino
can provide, so an external power source is needed.
Pin Connections:

● ENABLE1: Enables the motor driver.


● FWD1: Controls the forward direction of the actuator.
● REV1: Controls the reverse direction of the actuator.
● Speed: Defines the speed of the actuator using PWM (Pulse Width Modulation).

Arduino Code to Control a Linear Actuator:

// Define pin numbers for controlling the linear actuator


int ENABLE1 = 8; // Enable pin
int FWD1 = 11; // Forward pin
int REV1 = 3; // Reverse pin
int Speed; // Speed control (0-255)

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)

// Move the actuator forward


Forward();
delay(5000); // Move forward for 5 seconds

// Stop the actuator


Stop();
delay(1000); // Wait for 1 second

// Move the actuator in reverse


Reverse();
delay(5000); // Move backward for 5 seconds

// Stop the actuator


Stop();
delay(1000); // Wait for 1 second
}

// Function to move the actuator forward


void Forward() {
digitalWrite(ENABLE1, HIGH); // Enable the motor driver
analogWrite(REV1, 0); // Stop reverse direction
analogWrite(FWD1, Speed); // Move forward at specified speed
}

// Function to reverse the actuator


void Reverse() {
digitalWrite(ENABLE1, HIGH); // Enable the motor driver
analogWrite(FWD1, 0); // Stop forward direction
analogWrite(REV1, Speed); // Move reverse at specified speed
}

// Function to stop the actuator


void Stop() {
digitalWrite(ENABLE1, LOW); // Disable the motor driver
analogWrite(FWD1, 0); // Stop the forward direction
analogWrite(REV1, 0); // Stop the reverse direction
}

Explanation of the Code:

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.

You might also like