0% found this document useful (0 votes)
3 views

ECEL 12 Activity 1 (Getting Started with Robot Assembly and Programming)

The document provides an overview of robotics technology, covering its multidisciplinary nature, historical evolution, and essential components such as power sources, controllers, actuators, and sensors. It also discusses Asimov's Three Laws of Robotics, various types of robotic systems, and the significance of mechatronics in designing intelligent machines. Additionally, it highlights the importance of embedded systems and control theory in robotics applications.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

ECEL 12 Activity 1 (Getting Started with Robot Assembly and Programming)

The document provides an overview of robotics technology, covering its multidisciplinary nature, historical evolution, and essential components such as power sources, controllers, actuators, and sensors. It also discusses Asimov's Three Laws of Robotics, various types of robotic systems, and the significance of mechatronics in designing intelligent machines. Additionally, it highlights the importance of embedded systems and control theory in robotics applications.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 60

ECEL 12: ELECTIVE 2 (ROBOTICS TECHNOLOGY)

Activity 1
Getting Started with Robot Assembly and Programming

Robotics is a multidisciplinary field that combines aspects of mechanical engineering, electrical


engineering, computer science, and mathematics to design, build, and control robotic systems.
These systems can range from simple manipulators to complex autonomous robots capable of
performing various tasks in diverse environments. In this context, robots are programmable
machines capable of carrying out tasks autonomously or semi-autonomously, often performing
actions that are too dangerous, repetitive, or precise for humans.

Asimov’s Three Laws of Robotics: intended to be safety features that cannot be bypassed.
They are incorporated into almost all of the positronic robots in his science fiction stories.
Asimov's work helped to popularize the idea of robots and created the word "robotics".
1. A robot must not injure a human being or through inaction, allow a human being to come
to harm.
2. A robot must obey the orders given to it by human beings, except when such orders
would conflict with the First Law.
3. A robot must protect its own existence as long as such protection does not conflict with
the First or Second Laws.

Main Classifications of Robotic Systems

Common Aspects of Robotic Systems:


✓ All robots have some kind of mechanical construction, a frame, form or shape designed
to achieve a particular task.
✓ Robots have electrical components which power and control the machinery.
✓ All robots contain some level of computer programming code.

Iloilo Science and Technology University 1


ECEL 12: ELECTIVE 2 (ROBOTICS TECHNOLOGY)
History and Evolution of Robotics
1921: The term ‘robot’ is first used by Czech writer Karel Capek.
1939: Electro, a humanoid robot, debuts at the World’s Fair, smoking cigarettes and blowing
up balloons.
1941: Isaac Asimov formulates the Three Laws of Robotics.
1948: William Grey Walter creates the first autonomous robot with complex behavior.
1950: Alan Turing publishes the concept of Turing's Test, which tests machine intelligence.
1951: Marvin Minsky builds the first neurocomputer, SNARC.
1954: George Devol invents the first digitally operated and programmable robot.
1956: Field of AI research is founded at a Dartmouth conference.
1960: Frank Rosenblatt constructs Mark I Perceptron, the first neural network computer.
1961: GM installs the first Unimate robot to lift and stack hot pieces of metal.
1966: ELIZA, the first chatbot, is developed.
1968: Mobile robot “Shakey” is introduced.
1972: Stanford researcher develops PARRY, a chatbot simulating a paranoid schizophrenic.
1974: Intel produces its second-generation 8080 general-purpose chips.
1979: SCARA, an articulated robot arm, is developed for assembly lines.
1984: General Robotics Corp develops RB5X, the first robot capable of learning from its
environment.
1985: Jaron Lanier coins the phrase "virtual reality."
1986: Honda creates the EO, the first humanoid robot to walk on two feet.
1988: Researchers launch Jabberwacky, an AI chatbot designed to learn through
conversation.
1990: Tom Caudell coins the term "augmented reality."
1997: Deep Blue defeats Garry Kasparov in a chess match.
2000: ASIMO, a humanoid robot by Honda, debuts.
2004: Google launches a 3D version of Street View.
2011: IBM introduces Watson, a language-processing system.
2012: Google introduces its first AI voice assistant.
2016: Amazon makes its first drone delivery in the UK.
2020: The drone industry is valued at $127 billion.

Iloilo Science and Technology University 2


ECEL 12: ELECTIVE 2 (ROBOTICS TECHNOLOGY)
Primary Components of a Robotic System
• Power Source – mostly (lead-acid) batteries are used, but other potential power sources
include:
• Controller – involves three distinct phases – perception, processing, and action.
• Actuators – convert stored energy into movement; most popular actuators are electric
motors and linear actuators
• Sensors – allow robots to receive information about a certain measurement of the
environment or internal components to give them warnings about safety or errors, and to
provide real-time information of the task it is performing

• Manipulation Components – used to manipulate objects; pick up, modify, destroy, or


otherwise have an effect; the "hands" of a robot are often referred to as end effectors,
while the "arm" is referred to as a manipulator
• Locomotion Mechanism – allow robots to maneuver in a way that somehow mimics
humans, animals, and various objects
• Environmental Interaction and Navigation – combination of navigation hardware and
software for traversing robot’s environment
• Human-Machine Interaction – sensory intelligence for robots to work effectively with
humans in various environments

Iloilo Science and Technology University 3


ECEL 12: ELECTIVE 2 (ROBOTICS TECHNOLOGY)
Basic Architecture of a Robotic System

The robot model represents the physical structure and


kinematics of the robot crucial for understanding its
capabilities, motion range, workspace, and mechanical
design considerations. This includes parameters such
as dimensions, joints, links, degrees of freedom, and
geometric properties. Types of robot models include
articulated robots (with multiple revolute or prismatic
joints), Selective Compliance Assembly Robot Arm
(SCARA) robots, delta robots, cartesian robots,
humanoid robots, and more.

Degrees of freedom (DoF) is the number of independent parameters that define the
configuration or motion of a robotic machine. Each DoF represents a specific way in which the
system can move or change its configuration. The mechanical arm or end-effector of the robot
is responsible for performing tasks such as picking, placing, assembling, welding, cutting, or
painting. It consists of joints, links, end-effectors (grippers, tools), and kinematic chains that
enable precise and controlled motion. Its design, kinematics, workspace, payload capacity, and
dexterity influence the robot's capabilities and applications.

Iloilo Science and Technology University 4


ECEL 12: ELECTIVE 2 (ROBOTICS TECHNOLOGY)

Types of End-Effectors

Types of Robot Motion

Mechatronics is an interdisciplinary field that values systems thinking and an interdisciplinary


approach to problem solving related to designing products and manufacturing processes. In
connection to robotics, it integrates mechanical engineering, electronics, control systems, and
computer science to design and create intelligent systems or machines.

Iloilo Science and Technology University 5


ECEL 12: ELECTIVE 2 (ROBOTICS TECHNOLOGY)
A machine is any device that transmits or modifies energy to do a job better and faster and
more powerfully than a human being does. In physics, the 6 simple machines are:

Machine elements and design are fundamental aspects of mechatronics and robotics,
encompassing the mechanical components, structures, and systems that form the basis of
these intelligent systems. Here’s a brief discussion on each of these components:
1. Structural Elements:
• Frames and Chassis: Frames provide structural support and rigidity to mechatronic
and robotic systems. Chassis design considerations include material selection (e.g.,
aluminum, steel, carbon fiber), weight optimization, stiffness, vibration damping, and
mounting points for components.
• Enclosures and Casings: Enclosures protect internal components from
environmental factors (dust, moisture, impact) and provide a safe and ergonomic
housing for mechatronic and robotic systems. Enclosure design includes accessibility
for maintenance, heat dissipation, cable management, and aesthetics.
• Sensor Placement: Proper sensor placement and mounting ensure accurate data
acquisition, minimal interference, and optimal performance.
• Integration with Mechanical Components: Integrating sensors with mechanical
components involves designing sensor mounts, brackets, housings, and interfaces
for reliable attachment and alignment. Considerations include sensor orientation,
protection from external factors, and accessibility for calibration and maintenance.

Iloilo Science and Technology University 6


ECEL 12: ELECTIVE 2 (ROBOTICS TECHNOLOGY)

2. Mechanism Elements:
• Gears and Mechanisms: Gears are essential for power transmission, speed
reduction, torque amplification, and motion control in mechatronic and robotic
systems. They include spur gears, bevel gears, worm gears, planetary gears, and
rack-and-pinion mechanisms.
• Linkages and Joints: Mechanical linkages and joints enable complex motion and
manipulation in robotic systems. Examples include revolute joints (for rotational
motion), prismatic joints (for linear motion), kinematic chains, parallel mechanisms,
and articulated manipulators. Design considerations include kinematics, dynamics,
workspace analysis, and stiffness requirements.
• Bearings and Shafts: Bearings support rotating components and reduce friction,
allowing smooth and reliable motion. Types of bearings include ball bearings, roller
bearings, plain bearings, and thrust bearings. Shaft design involves considerations
such as material selection, diameter sizing, length, load capacity, and alignment.

Iloilo Science and Technology University 7


ECEL 12: ELECTIVE 2 (ROBOTICS TECHNOLOGY)
3. Control Elements:
• Sensors and Actuators: Sensors play a vital role in mechatronic and robotic
systems for feedback control, environmental sensing, and safety. On the other hand,
actuators such as motors (DC motors, stepper motors, servo motors) are crucial for
generating mechanical motion in mechatronic and robotic systems.
• Embedded System: Controller embedded as part of a complete device with a
dedicated function within a larger mechanical or electrical system, often with real-
time computing constraints.
• Drive Systems: Drive systems transmit power from motors to mechanical
components using mechanisms like belts, pulleys, chains, gears, and couplings.
Design considerations include power transmission efficiency, speed regulation,
backlash, and torque transfer capabilities.

Robotics often relies on various sensors such as proximity sensors, temperature sensors,
accelerometers, gyroscopes, and cameras. Understanding how to interface these sensors with
microcontrollers or microprocessors, including signal conditioning, calibration, and data
acquisition, is essential for accurate sensor readings. Actuators like motors, servos, and solenoids
are used for movement, manipulation, and control in robotics. Knowledge of motor types, motor
drivers, pulse width modulation (PWM) for speed control, and feedback mechanisms (encoders,
position sensors) is necessary for precise actuator control.

Iloilo Science and Technology University 8


ECEL 12: ELECTIVE 2 (ROBOTICS TECHNOLOGY)

Embedded systems are specialized computer systems designed to perform specific tasks
within larger systems or devices. Typically built with dedicated hardware and software to meet
the requirements of the target application, they are primarily composed of the following key
components, each playing a crucial role in its functionality:
• Microcontroller/Microprocessor: This is responsible for executing instructions and
controlling the system's operations. Microcontrollers are microchips with a CPU,
memory, input/output ports, and sometimes specialized peripherals like converters
ADCs and timers, while microprocessors are more powerful and may require additional
components like external memory and support chips.
• Memory: Embedded systems use different types of memory:
o Random Access Memory (RAM): Stores data and program instructions temporarily
while the system is running.
o Read-Only Memory (ROM) /Flash Memory: Holds the firmware or embedded
software that initializes the system and performs essential functions. It retains data
even when power is off.
o Electrically Erasable Programmable Read-Only Memory (EEPROM): Stores
configuration settings and non-volatile data that can be modified occasionally.

Iloilo Science and Technology University 9


ECEL 12: ELECTIVE 2 (ROBOTICS TECHNOLOGY)
• Input/Output (I/O) Interfaces: These interfaces connect the embedded system to
external devices such as sensors, actuators, displays, communication modules (like
Ethernet, Wi-Fi, Bluetooth), and storage devices. Examples of I/O interfaces include
General Purpose Input/Output (GPIO), Universal Asynchronous Receiver-Transmitter
(UART), Serial Peripheral Interface (SPI), Inter-Integrated Circuit (I2C), and Analog-to-
Digital/Digital-to-Analog Converters (ADC/DAC).
• Power Supply: Embedded systems require a stable and appropriate power source,
which may include batteries, DC power supplies, or power management circuits for
efficient energy usage.

• Operating System (OS): In some embedded systems, an OS manages resources,


provides abstraction layers, and facilitates multitasking and communication between
software components. Common embedded OS choices include:
o Real-Time Operating Systems (RTOS): Designed for time-critical applications
where tasks must be executed within specific time constraints. Examples include
FreeRTOS, RTLinux, and VxWorks.
o Linux-based OS: Offers a more general-purpose environment with support for
networking, file systems, and a wide range of software tools. Popular choices for
embedded Linux include Embedded Linux, Yocto Project, and Buildroot.
• Bare-metal Programming: In simpler embedded systems or applications with strict
resource constraints, developers may directly control hardware without using a full-
fledged OS, known as bare-metal programming.
• Programming Languages: The choice of programming language depends on factors
such as system requirements, performance, developer expertise, and available
libraries/tools. Two commonly used languages for embedded systems are C and Python:

Iloilo Science and Technology University 10


ECEL 12: ELECTIVE 2 (ROBOTICS TECHNOLOGY)
o C: Widely used in embedded systems due to its efficiency, low-level hardware
access, and close-to-the-hardware programming capabilities. C is suitable for
tasks like device drivers, low-level control, and real-time processing where
performance and resource utilization are critical.
o Python: Known for its simplicity, readability, and extensive libraries, especially for
higher-level application development, rapid prototyping, and tasks that don't
require real-time constraints. Python can interact with hardware through libraries
like RPi.GPIO for Raspberry Pi or MicroPython for microcontrollers.

For complex systems, designing Printed Circuit Boards (PCBs) involves creating layouts and
routing traces. Robotics projects must prioritize safety and reliability by implementing fail-safe
mechanisms, error handling, testing for robustness under different conditions, incorporating circuit
protection circuits, and complying with safety standards and regulations.

Control Systems

Iloilo Science and Technology University 11


ECEL 12: ELECTIVE 2 (ROBOTICS TECHNOLOGY)
Control Theory, a field of engineering and applied mathematics, focuses on the behavior of
dynamical systems and uses transfer functions to relate system inputs to outputs. At the core
of robotics, the controller acts as the system's brain, generating signals to drive actuators based
on sensor inputs and desired trajectories. Supporting this, electronics serves as the backbone,
enabling robots to sense, act, process signals, communicate, and manage power efficiently.

Embedded Systems:
• Microcontrollers: ideal for simple embedded applications that require low power
consumption and low cost; typically use ARM CPU
• Microprocessors: ideal for general-purpose computing applications, requiring more
complex functionality and processing power; typically use x86 CPU:

Iloilo Science and Technology University 12


ECEL 12: ELECTIVE 2 (ROBOTICS TECHNOLOGY)

Arduino (ATMega 328P 𝜇𝐶 – AVR)

Raspberry Pi (Broadcom BCM2711 𝜇𝑃 – ARM)

Human-Machine Interfaces (HMIs)

Iloilo Science and Technology University 13


ECEL 12: ELECTIVE 2 (ROBOTICS TECHNOLOGY)
Software is a set of instructions, data or programs used to operate computers and execute
specific tasks, typically stored on an external long-term memory device, such as a hard drive or
solid-state drive. Software engineering is the application of engineering principles for
analyzing user needs and designing, constructing, and testing end-user applications that will
satisfy such needs.

C programming is a fundamental and versatile language widely used in the field of electronics
and software development. As an electronics engineering instructor, it's crucial to provide
students with a solid understanding of key concepts within C programming, including coding
conventions, data types, constants, and variables. Some common conventions include:
• Indentation: Use consistent indentation to improve code readability.
• Naming Conventions: Follow a naming convention for variables, functions, and other
identifiers (e.g., camelCase, snake_case).
• Comments: Use comments to explain complex code or to provide context for the code.
• Braces Placement: Adopt a consistent style for placing braces (e.g., on a new line or
the same line).

Iloilo Science and Technology University 14


ECEL 12: ELECTIVE 2 (ROBOTICS TECHNOLOGY)
Arithmetic operators in C programming are used to perform mathematical operations on
variables and values. Logical operators are used to perform logical operations often used in
control flow statements and decision-making, while comparison operators are used to
compare two values.

Other Essential Symbols


• Semicolon (;): Used to terminate statements in C programming.
• Curly Braces ({}): Used to define a block of code (e.g., in functions, loops, or
conditionals).
• Parentheses (()): Used in function calls and to define precedence in expressions.
• Comma (,) and Colon (:): Used in various contexts, such as function arguments and
labels in a switch statement.

Data types in C programming are fundamental concepts that define the type of data a variable
can hold and the operations that can be performed on that data. C provides a rich set of data
types, each designed to handle different types of data and perform various operations.

Basic data types, also known as primary data types, in C are the simplest and most
fundamental data types. They include:
• int: Represents integers (whole numbers).
• float: Represents floating-point numbers with decimal places.
• char: Represents individual characters.
• double: Represents double-precision floating-point numbers.

Iloilo Science and Technology University 15


ECEL 12: ELECTIVE 2 (ROBOTICS TECHNOLOGY)
In a C code, a function declaration provides the function's name, return type, and parameters,
informing the compiler about the function's existence. It is in header files to declare functions
and serves as a contract between the calling code and the function's implementation. Typically,
Declarations reside in header files (.h) and ensure that the function can be used correctly.

A function definition, on the other hand, contains the implementation, specifying what the
function does. It is found in the body of the program or external source files. Definitions are
found in source files (.c) and contain the code that executes when the function is called.

Control statements in C programming are fundamental constructs that allow for control over
the flow of a program's execution. These statements enable branching, looping, and decision-
making based on conditions. Understanding control statements is essential for writing efficient
and flexible programs in C.

Iloilo Science and Technology University 16


ECEL 12: ELECTIVE 2 (ROBOTICS TECHNOLOGY)
Arduino programming involves writing code in its IDE, where C constructs like variables,
functions, loops, and conditionals are used to control microcontroller-based hardware. This
allows for the creation of interactive projects by interfacing sensors, actuators, and other
components. Understanding data types in Arduino programming is fundamental for efficient
code development. Basic data types, inherited from C/C++, include:
• int: Represents integers (whole numbers).
• float: Represents floating-point numbers with decimal places.
• char: Represents individual characters.
• boolean: Represents true (1) or false (0).

These derived data types are created by combining basic data types or other derived types:
• arrays: Collections of elements of the same data type.
• pointers: Variables that hold memory addresses.
• structures: Bundles together different types of data under a single name.

In Arduino programming, variables are used to store different types of data. Each variable must
have a specific data type, such as int (integer), float (floating-point), char (character), etc. Data
types determine the type of data that a variable can hold and the operations that can be
performed on that data.

Iloilo Science and Technology University 17


ECEL 12: ELECTIVE 2 (ROBOTICS TECHNOLOGY)

Functions in Arduino programming follow C-style syntax and are essential for organizing code
and promoting reusability. They have a return type, a name, parameters, and a body. Arduino
allows you to extend functionality through libraries. Libraries contain pre-written code to simplify
complex tasks. You include libraries using #include directive. Here's an example using the
Servo library to control a servo motor:

#include <Servo.h>
Servo myServo; // Create a servo object
void setup() {
myServo.attach(9); // Attaches the servo on pin 9
}
void loop() {
myServo.write(90); // Rotate the servo to 90 degrees
delay(1000);
myServo.write(0); // Rotate the servo to 0 degrees
delay(1000);
}

In Arduino, "attributes" refer to variables or constants, and "methods" are synonymous with
functions. Variables and constants are used to store and manage data, acting as attributes of a
program. Functions in Arduino programming encapsulate behavior and can be considered as
methods. They allow for modularity, code reusability, and efficient organization of code, and
they can take parameters as input and return values as output. The Serial functions
demonstrate the use of functions and the dot (.) operator to access member functions.

Iloilo Science and Technology University 18


ECEL 12: ELECTIVE 2 (ROBOTICS TECHNOLOGY)
int add(int a, int b) {
return a + b;
}
void setup() {
Serial.begin(9600);
Serial.println("The sum is: " + String(add(5, 3)));
}
void loop() {
// Code inside the loop function
}

Conditional statements in Arduino programming, derived from C/C++, are essential constructs
that determine the flow of program execution. They enable branching, looping, and decision-
making based on conditions, allowing for the creation of dynamic and efficient Arduino codes.
The if-else statement in Arduino programming, like in C, evaluates a condition and executes
a block of code if the condition is true; otherwise, it executes an alternative block if provided.

int sensorValue = analogRead(A0);


void setup() {
Serial.begin(9600);
}
void loop() {
if (sensorValue > 500) {
Serial.println("Sensor value is greater than 500");
} else {
Serial.println("Sensor value is less than or equal to 500");
}
delay(1000);
}

Loops in Arduino programming allow for the efficient repetition of code, making it easier to
perform tasks such as reading sensors, controlling actuators, and managing data.
• for loop: like in C, allows you to specify an initialization, a condition, and an iteration
expression in a compact statement. It continues to execute while the condition is true.
• while loop: continues to execute as long as the specified condition is true.
• do-while loop: is similar to the while loop, but the condition is evaluated at the end of
each iteration, ensuring the loop will execute at least once, even if the condition is false.

Iloilo Science and Technology University 19


ECEL 12: ELECTIVE 2 (ROBOTICS TECHNOLOGY)

In an Arduino sketch, the void loop() function is a fundamental part where the main logic
and actions of the program reside, and it's designed to run in a loop indefinitely after the void
setup() function has been executed once. As the entry point for the main program, it executes
its contents in a continuous loop and its relationship with iterative statements include:
• Imitating Iterative Behavior: Any iterative behavior, typically achieved using loops in C
programming, can be replicated within the void loop() function.
• Creating Controlled Loops: Within void loop(),controlled loops are created using
conditions. An if statement can be used to control when a block of code executes.
• Handling Sensors and Inputs: In many Arduino applications, iterative behavior is
essential for continuously reading sensors or handling inputs (e.g., button presses).

#include <stdio.h>
int main() {
for (int i = 0; i < 5; i++) {
printf("Iteration %d\n", i);
}
int count = 0;
while (count < 5) {
printf("Count is %d\n", count);
count++;
}
int num = 0;
do {
printf("Number is %d\n", num);
num++;
} while (num < 5);
return 0;
}

Iloilo Science and Technology University 20


ECEL 12: ELECTIVE 2 (ROBOTICS TECHNOLOGY)

Tinkercad is a virtual platform that allows users to simulate and prototype Arduino projects
without physical components. The following are the steps to get started with this tool for
developing an Arduino project:
• Access Tinkercad: Visit the Tinkercad website (www.tinkercad.com) and sign up for a
free account.
• Create a New Project: Once logged in, click on Create New Design. Choose the
Circuits option to access the circuit design tool.
• Add Components: Drag and drop components from the sidebar onto the workspace.
Choose Arduino boards, sensors, LEDs, and more.
• Connect Components: Use wires to connect components just like you would in a real
circuit. Click on a component's pin, drag to the target pin, and release.
• Write Code: Click on the Arduino board to open the code editor. Write your code using
the Arduino programming language.
• Simulate and Test: Hit the "Start Simulation" button to test your circuit and code
virtually. Observe how components interact in real-time.
• Iterate and Learn: Tinkercad's virtual environment allows you to iterate, troubleshoot,
and learn without using physical components. (See also this video tutorial playlist.)

Iloilo Science and Technology University 21


ECEL 12: ELECTIVE 2 (ROBOTICS TECHNOLOGY)
Python is a high-level, beginner-friendly programming language known for its simplicity,
readability, and extensive standard library. It is a popular choice for both beginners and
experienced developers since it is a versatile programming language that facilitates rapid
development. Here’s how to get started with Python programming:
1. Install Python:
▪ Download Python: Visit the official Python website at python.org and go to the
Downloads section. Choose the version suitable for your operating system
(Windows, macOS, or Linux) and download the installer.
▪ Run the Installer: Run the downloaded installer. During installation, check the box
that says "Add Python to PATH" to make it easier to run from the command line.
▪ Verify Installation: Open a command prompt (Windows) or terminal (macOS/Linux)
and type python --version or python -V to verify that Python has been
installed. You should see the version number.
2. Set Up a Development Environment:
▪ Text Editor or IDE: Choose a text
editor or an integrated development
environment (IDE) for writing Python
code. A popular choice for beginners
is Visual Studio Code,
▪ Create a Workspace: Create a folder on your computer to organize your Python
projects. This will be your workspace where you store your Python files.
3. Write Your First Python Program:
▪ Write Hello World: Open your chosen text editor or IDE and type the following
code to print "Hello, World!" to the console:
print("Hello, World!")
▪ Save the File: Save the file with a .py extension, for example, hello_world.py.
4. Run Your Python Program:
▪ Open Terminal or Command Prompt: Open a terminal or command prompt.
▪ Navigate to Your Workspace: Use the cd command to navigate to the folder
where you saved your Python file. For example:
cd path/to/your/workspace
▪ Run the Python Script: Type the following command to run your Python script:
python hello_world.py

Iloilo Science and Technology University 22


ECEL 12: ELECTIVE 2 (ROBOTICS TECHNOLOGY)
With its clear and readable code, Python follows coding conventions outlined in PEP 8, serving
as guidelines to enhance the consistency and maintainability of Python code, including
1. Indentation: Use 4 spaces per indentation level.
2. Maximum Line Length: Limit lines to max. 79 characters for code and 72 for docstrings.
3. Imports: Should usually be on separate lines and grouped in the following order:
✓ Standard library imports.
✓ Related third-party imports.
✓ Local application/library specific imports.
4. Whitespace in Expressions and Statements: Avoid extraneous whitespace when:
✓ Immediately inside parentheses, brackets, or braces.
✓ Immediately before a comma, semicolon, or colon.
✓ Immediately before the open parenthesis that starts the function call’s argument list.

In Python, a function is a reusable block of code that performs a specific task and can be
defined using the def keyword, followed by the function name, parameters, and a colon. Its
body is indented and contains the code to be executed when the function is called. It can have
parameters and return values, allowing for flexibility and reusability in code. Here’s an example:

Function definition refers to creating a named block of reusable code that performs a specific
task, may accept parameters, and may return a value. A function is defined using Python’s def
keyword, allowing you to encapsulate a block of reusable code. Meanwhile, function call is the
process of executing a function by referencing its name and providing the required arguments (if
any), thereby initiating its defined behavior. A function is called by using its name followed by
parentheses, optionally passing arguments inside the parentheses.

Iloilo Science and Technology University 23


ECEL 12: ELECTIVE 2 (ROBOTICS TECHNOLOGY)
Variables in Python are dynamically typed, meaning you can reassign them to different types.
Variable names should be descriptive and follow PEP 8 conventions. They can contain letters
(except for reserved words), numbers, and underscores but cannot start with a number. Python
supports a variety of fundamental data types of each variable value interpreted at runtime and
are not declared explicitly, To assign a value to a variable, use the assignment operator ‘= ′.

# Variable assignment
name = "John"
age = 25
height = 1.75
is_student = True
# Variable reassignment
age = 26

As a dynamically-typed programming language, Python does not require to declare the data
type of a variable explicitly. Python supports a variety of fundamental data types that allow
developers to work with different kinds of information. Here are some data types in Python:

Data Type Description Example

Numeric

int Integers (whole numbers) x = 10

float Floating-point numbers (decimal numbers) x = 3.14

complex Complex numbers x = 2+3j

Boolean

bool Boolean values (True or False) x = True

Sequence

str Strings (sequence of characters) x = "Hello, world!"

list Ordered collection of items (mutable) x = [1, 2, 3, "apple"]

tuple Ordered collection of items (immutable) x = (1, 2, 3, "apple")

range Sequence of numbers x = range(10)

Mapping

dict Unordered collection of key-value pairs x = {"name": "Alice", "age": 30}

Set

set Unordered collection of unique items x = {1, 2, 3}

frozenset Unordered collection of unique items (immutable) x = frozenset({1, 2, 3})

Iloilo Science and Technology University 24


ECEL 12: ELECTIVE 2 (ROBOTICS TECHNOLOGY)
In Python programming, control structures are constructs that manage the flow of the
program's execution. They determine how code is executed, depending on their type:

Conditional Statements (Selection)


1. if Statement: Executes a block of code if a specified condition is true.
2. elif Statement: Allows checking additional conditions if the preceding if statement's
condition is false.
3. else Statement: Provides a block of code to execute when none of the preceding
conditions is true

Iterative Statements (Iteration


1. for Loop: Iterates over a sequence (e.g., a list, tuple, string) or other iterable objects.
2. while Loop: Repeats a block of code as long as a specified condition is true.
3. break and continue: break exits the loop prematurely based on a condition, while
continue skips the rest of the code inside the loop for the current iteration and moves to
the next iteration.

Exception handling allows us to gracefully handle and recover from errors or exceptions that
occur during the execution of a program. It provides a mechanism to catch and handle these
exceptions, allowing the program to continue running and providing meaningful error messages
to the user.

Iloilo Science and Technology University 25


ECEL 12: ELECTIVE 2 (ROBOTICS TECHNOLOGY)
Below is a simple Python program simulating basic control for a robot arm. It uses basic control
structures (if-else, loops) and exception handling to ensure the user inputs valid commands.

def move_robot_arm(command):
if command == "up":
print("Robot arm is moving up.")
elif command == "down":
print("Robot arm is moving down.")
elif command == "left":
print("Robot arm is moving left.")
elif command == "right":
print("Robot arm is moving right.")
elif command == "stop":
print("Robot arm has stopped.")
else:
print("Invalid command. Please try again.")
def main():
print("Welcome to the Robot Arm Control Program!")
print("Available commands: 'up', 'down', 'left', 'right', 'stop'.")
print("Type 'exit' to end the program.")
while True:
try:
# Get user input
command = input("Enter a command for the robot arm:
").strip().lower()
# Handle 'exit' command to break the loop
if command == "exit":
print("Exiting the Robot Arm Control Program. Goodbye!")
break
# Call the function to move the robot arm
move_robot_arm(command)
except Exception as e:
# Handle unexpected errors
print(f"An error occurred: {e}. Please try again.")
if __name__ == "__main__":
main()

Iloilo Science and Technology University 26


ECEL 12: ELECTIVE 2 (ROBOTICS TECHNOLOGY)
Python supports object-oriented programming, a programming paradigm that organizes code
into objects, which are instances of classes. A class is a blueprint that defines the structure and
behavior of objects. Python classes encapsulate data (attributes) and behavior (methods) into a
single unit. This approach promotes code organization, reuse, and flexibility. You can create an
object or instance of a class and access its attributes and methods.

Attributes are characteristics or properties that describe an object. They are like variables that
belong to an object and define its state. In Python classes, attributes are defined within the class
and are accessed using dot notation. Methods, on the other hand, are functions that define the
behavior of the object. They are defined within the class and are called on class instances using
dot notation. For example:

class Person:
def __init__(self, name, age):
self.name = name
self.age = age

def greet(self):
print(f"Hello, I’m {self.name} and I’m {self.age} years old.")

# Creating an instance of the Person class


person1 = Person("John", 25)

# Calling the greet method


person1.greet()

# Output: Hello, I’m John and I’m 25 years old.

Iloilo Science and Technology University 27


ECEL 12: ELECTIVE 2 (ROBOTICS TECHNOLOGY)
Here’s a simple Python program that demonstrates basic classes and methods for robotics,
focusing on a robot with speed and distance tracking:

class Robot:
def __init__(self, name, speed=1):
"""Initialize the robot with a name and default speed."""
self.name = name
self.speed = speed # Speed in units per move
self.distance_traveled = 0 # Total distance traveled
def set_speed(self, speed):
"""Set the robot's speed."""
if speed > 0:
self.speed = speed
print(f"{self.name}'s speed set to {self.speed}.")
else:
print("Speed must be a positive value!")
def move_forward(self, steps=1):
"""Move the robot forward by a certain number of steps."""
self.distance_traveled += self.speed * steps
print(f"{self.name} moved forward {steps} steps. Total distance:
{self.distance_traveled} units.")
def get_status(self):
"""Display the robot's current status."""
print(f"{self.name} is moving at speed {self.speed}. Distance
traveled: {self.distance_traveled} units.")
# Example usage
if __name__ == "__main__":
# Create a Robot object
robot = Robot("Speedy")
# Set speed and move the robot
robot.set_speed(3)
robot.move_forward(5)
# Check the robot's status
robot.get_status()
# Adjust speed and move again
robot.set_speed(2)
robot.move_forward(3)
robot.get_status()

Iloilo Science and Technology University 28


ECEL 12: ELECTIVE 2 (ROBOTICS TECHNOLOGY)
One notable example of an embedded system in robotics is the Raspberry Pi, which is a credit
card-sized single-board computer, known for its affordability, versatility, and ease of use. This
microprocessor module, Raspberry Pi has become a popular platform for developing various
applications, including internet-of-things (IoT) devices, robotics, automation systems, and more.

Raspberry Pi offers numerous features that make it an ideal platform for various applications:
✓ Processing Power: Raspberry Pi is equipped with a Broadcom system-on-a-chip (SoC)
that provides sufficient processing power for most computing tasks.
✓ Input/Output (I/O) Options: It has a variety of connectivity options, including USB ports,
HDMI output, Ethernet port, and GPIO pins, allowing users to connect peripherals and
sensors to interact with the physical world.
✓ Operating System Support: Raspberry Pi supports a range of operating systems,
including Linux distributions like Raspbian, Ubuntu, and Fedora, enabling users to
choose the one that best suits their needs.
✓ Programming Capabilities: Raspberry Pi supports multiple programming languages,
such as Python and C/C++, making it suitable for both pros and beginners.
✓ Expansion Possibilities: The Raspberry Pi GPIO pins allow users to connect additional
modules and create complex projects involving electronics, robotics, and automation.

Iloilo Science and Technology University 29


ECEL 12: ELECTIVE 2 (ROBOTICS TECHNOLOGY)
Raspberry Pi provides a cost-effective and powerful platform for developing embedded systems.
Its small form factor, low power consumption, and General-Purpose Input/Output (GPIO) pins
make it ideal for interfacing with external components, such as sensors, actuators, and displays.
Raspberry Pi also supports a variety of operating systems, including Linux distributions like
Raspbian, which provide a stable and flexible environment for running embedded applications.
Other Raspberry Pi key features useful in robotics include an HDMI output for displays, and
onboard networking capabilities such as Wi-Fi, ethernet, and Bluetooth.

To get started with Raspberry Pi, follow these steps:


1. Obtain a Raspberry Pi board: Make sure to check the specifications and select the
appropriate model for your needs.
2. Prepare a MicroSD Card: Raspberry Pi requires an SD card to store the operating
system and other files. Format a MicroSD card and download the Raspberry Pi imager
from the official Raspberry Pi website.
3. Install the Operating System: Use the Raspberry Pi Imager software to write the
downloaded operating system image onto the MicroSD card.
a. Once the download is complete, run the installer and follow the on-screen
instructions to install the Raspberry Pi Imager on your computer.
b. Launch the Raspberry Pi Imager application.
c. In the Raspberry Pi Imager window, click on "CHOOSE OS" and select
"Raspberry Pi OS" from the list.
d. Next, click on "CHOOSE STORAGE" to select the SD card where you want to
install Raspberry Pi OS. Make sure to select the correct SD card, as all data on
the selected SD card will be erased during the installation process.
e. Once the OS and storage have been selected, click on "WRITE" to begin the
installation process. A warning message will appear, informing you that all data
on the selected storage will be erased. Click "YES" to proceed.
f. The Raspberry Pi Imager will begin downloading the selected OS image and
writing it to the SD card. This process may take several minutes depending on
the speed of your internet connection and the SD card.
g. Once the installation process is complete, you will see a message indicating that
the process was successful.
h. Eject the SD card from and insert it into the SD card slot on the Raspberry Pi.

Iloilo Science and Technology University 30


ECEL 12: ELECTIVE 2 (ROBOTICS TECHNOLOGY)

4. Connect Peripherals: Connect a keyboard, mouse, display (via HDMI), and power
supply to the Raspberry Pi board. Ensure that all connections are secure.
5. Power On: Once everything is connected, power on the Raspberry Pi by plugging in the
power supply. The OS will boot up, and you will see the desktop environment.
6. Initial Configuration: Follow the on-screen instructions to complete the initial setup of
Raspberry Pi OS, including setting up the Wi-Fi network, choosing a password, and
configuring preferences.

Iloilo Science and Technology University 31


ECEL 12: ELECTIVE 2 (ROBOTICS TECHNOLOGY)
Robot control software is a set of instructions that tells a robot how to perform tasks. As the
brain behind the operation of a robot, it enables robot perception, decision-making, and task
performance. When dealing with time-critical tasks, such as precise motion control or sensor
data processing, a standard OS may fall short due to unpredictable delays in task scheduling.
This is where Real-Time Operating Systems (RTOS) come into play.

Key Components of RTOS for Robotics


• Task Scheduler: Determines the order and timing of task execution based on priority
levels, ensuring deadlines are met.
• Interrupt Handling: Responds to hardware events (e.g., sensor triggers) immediately,
bypassing normal task scheduling.
• Inter-Task Communication (ITC): Mechanisms like queues, semaphores, and
message passing allow tasks to share data and coordinate actions.
• Timers and Clocks: Accurate timing mechanisms ensure precise control over periodic
tasks like motor PWM generation.
• Memory Management: Efficient allocation and protection of memory prevent conflicts
and ensure stable operation in multi-tasking environments.

Iloilo Science and Technology University 32


ECEL 12: ELECTIVE 2 (ROBOTICS TECHNOLOGY)
ROS is an open-source framework that provides tools, libraries, and packages for writing robot
software. It is a specialized OS designed for applications where timing is critical. Unlike general-
purpose OS like Linux or Windows, RTOS provides deterministic responses, ensuring tasks are
executed within strict deadlines.

Popular RTOS for Robotics


• FreeRTOS: Open-source, widely used for embedded systems and compatible with
various microcontrollers.
• VxWorks: Commercial RTOS designed for industrial and mission-critical applications.
• ChibiOS/RT: Lightweight and open-source, suitable for resource-constrained devices.
• Real-Time Executive for Multiprocessor Systems (RTEMS): Open-source, designed
for embedded systems.
• Zephyr: Open-source, optimized for IoT and robotics applications.

RTOS vs. General-Purpose Operating Systems (GPOS)

Iloilo Science and Technology University 33


ECEL 12: ELECTIVE 2 (ROBOTICS TECHNOLOGY)
A graphical user interface (GUI) is an interface that allows users to interact with a computer
system using graphical elements such as icons, buttons, and menus. It provides a more user-
friendly way to control and interact with software applications compared to command-line
interfaces. In this section, we will explore the concept of GUI and how it works in Python.

In Python, there are several libraries available for creating GUI applications. One of the most
popular libraries is Tkinter, which is a cross-platform library provides a set of components and
tools for building GUI applications consisting of various elements and controls that enable users
to interact with the software. Here are some commonly used GUI elements:
• Windows and Frames: Container that represents a graphical window displayed on the
screen as the primary container for other GUI elements. Frames are containers that can
be placed inside windows to group related elements together.
• Labels: Used to display text or images in a GUI to provide information or instructions to
the user and are typically used to provide descriptions or titles for other GUI elements.
• Buttons: Allow users to activate a specific function or event associated with.
• Text Entry Fields (Input Boxes): Used to allow users to enter and edit text-based data.
for tasks that require user input, such as filling out forms or entering search queries.
• Menus and Menu Items: Provide a way to organize a set of related actions or options in
a GUI application. They are typically displayed as a horizontal or vertical list of options.
• Checkboxes and Radio Buttons: Used for selecting options from a predefined list.
Checkboxes are for multiple options, while radio buttons are for one option at a time.
• Dialog Boxes: Used to display messages or alerts to users. They can also be used to
prompt users for input or confirm their actions.

Iloilo Science and Technology University 34


ECEL 12: ELECTIVE 2 (ROBOTICS TECHNOLOGY)

To create a GUI application in Python using Tkinter, you need to follow these steps:
1. Import the Tkinter library.
import tkinter as tk
2. Create an instance of the Tk class:
root = tk.Tk()
3. Define and configure the GUI elements.
4. Use the pack() method to place the elements inside the window or frame.
5. Call the mainloop() method to start the event loop, which handles user interactions
and updates the GUI.

Here is a simple example of a GUI application that displays a window with a label and a button:

import tkinter as tk
def display_message():
label.config(text="Hello, GUI!")
root = tk.Tk()
root.title("My GUI Application")
label = tk.Label(root, text="Welcome to My GUI Application")
label.pack()
button = tk.Button(root, text="Click Me", command=display_message)
button.pack()
root.mainloop()

In the given example, we create a window using tk.Tk() and set its title. We then create a
label and a button using tk.Label() and tk.Button() respectively. The button is
configured to call the display_message() function when clicked. The label's text is updated
when the button is clicked.s

Iloilo Science and Technology University 35


ECEL 12: ELECTIVE 2 (ROBOTICS TECHNOLOGY)
Web applications are GUIs that can be accessed from any device with a web browser,
including tablets and smartphones. Python provides frameworks such as Django, Flask, and
Pyramid for building web-based GUIs with a structured way of developing web applications and
handling tasks such as routing, handling user requests, and rendering HTML templates.

Web development encompasses the process of creating dynamic and interactive websites and
web applications. Frontend development focuses on the client-side aspects, involving HTML,
CSS, and JavaScript to design and implement user interfaces, navigation, visual elements, and
interactivity within web browsers. Backend development, on the other hand, deals with server-
side logic, databases, APIs, and server configurations to manage data storage, processing, user
authentication, and server-client communication. See example and its demo in this link.

To display content and enable interactive features, web browsers act as the gateway for users
to access and navigate web pages, which are the digital documents comprising text, images,
multimedia, hyperlinks, and interactive elements that users interact with. The Uniform
Resource Locator (URL) serves as the unique identifier for a web page, allowing users to
access it via a browser. Hyperlinks are essential elements within web pages, enabling
navigation between pages, resources, and external content by linking to other URLs.

Iloilo Science and Technology University 36


ECEL 12: ELECTIVE 2 (ROBOTICS TECHNOLOGY)
Hands-On Activity 1.1
Assembly of a Basic 6-DoF Arduino Robotic Arm

This task is aimed at gaining hands-on experience on assembling and operating a basic 6-DoF
manipulation robot. It involves a robotics kit, which includes structural components, 6 pcs. Of
MG996R servo motors, a PCA9685PW 16 Channel Servo Shield Driver, and an Arduino board.
It also provides demonstration of robot motion configuration, as well as the concept of degrees
of freedom, particularly within the context of manipulation robots.

(see tutorial: https://www.youtube.com/watch?v=vvqUnWweFDs&ab_channel=SriTuHobby)

Required Components and Tools:


1. 6-DoF Manipulation Robot Kit
2. 6x MG996R Servo Motor
3. PCA9685PW 16 Channel Servo Shield Driver
4. Arduino Board
5. Screwdriver and Long-Nose Pliers
6. Computer (for programming via Arduino IDE)

Iloilo Science and Technology University 37


ECEL 12: ELECTIVE 2 (ROBOTICS TECHNOLOGY)

Safety Guides:
✓ Ensure the robotic arm frame is stable before tightening screws.
✓ Use a firm grip on the screwdriver to prevent slipping.
✓ Hold small parts securely with long-nose pliers to avoid injury.
✓ Check all joints and screws for tightness before operating the arm.
✓ Secure proper cable management.
✓ Observe the illustrated instructions and see video tutorials for more information.

Iloilo Science and Technology University 38


ECEL 12: ELECTIVE 2 (ROBOTICS TECHNOLOGY)
Assessment: Use the provided space below to answer or provide what is being asked.

1. How does the choice of 6-DoF impact the robot's ability to perform complex tasks? How
might fewer or additional degrees of freedom change the robot's applications?

2. Why is the integration of the PCA9685 16-Channel Servo Shield Driver critical for
managing multiple servo motors in this project?

3. In what ways can the calibration of servo motors affect the accuracy and repeatability of the
robot’s movements? How would improper calibration influence the robot's performance?

4. Design an algorithm for Arduino that ensures the robot’s end-effector reaches a target
position while considering the limitations of servo motion range and load capacity.

Iloilo Science and Technology University 39


ECEL 12: ELECTIVE 2 (ROBOTICS TECHNOLOGY)
5. Briefly describe your output in Item No.4.

6. Discuss a summary of your observations and analyses in this part of the activity.

Iloilo Science and Technology University 40


ECEL 12: ELECTIVE 2 (ROBOTICS TECHNOLOGY)
Hands-On Activity 1.2
Assembly of a Basic ESP32 4-Wheeled Robot

This task covers assembly and operation of the Makerlab ESP32 WiFi Camera 4WD Smart
Robot Kit, which includes the ESP32 CAM control board with WiFi connectivity. It provides
demonstration of a robot's real-time image transmission capabilities, gaining insights into
applications such as remote monitoring and first-person view (FPV) operation.

Required Components and Tools:


1. Makerlab ESP32 WiFi Camera 4WD Smart Robot Kit
2. 2x Lithium (18650) Battery
3. Screwdriver and Long-Nose Pliers
4. Smartphone or Tablet (for video monitoring)

As mobile robot technology advances, their capabilities are expanding to include AI, advanced
sensors, and autonomous navigation. By integrating features such as real-time imaging, WiFi
control, and strong mobility, these are not only valuable tools for professional applications but
also provide an engaging way to learn and experiment with robotics technology.

Iloilo Science and Technology University 41


ECEL 12: ELECTIVE 2 (ROBOTICS TECHNOLOGY)
The Makerlab ESP32 WiFi Camera 4WD Smart Robot Kit is a beginner-friendly platform for
exploring electronics, programming, and robotics. Acting as a remote-controlled car, it features:
• Real-Time Image Transfer: A built-in camera provides live video streaming for
enhanced exploration and monitoring.
• FPV Operation: Control and view your robot's surroundings from a first-person
perspective using a mobile device.
• WiFi Control: Connect to the car's WiFi hotspot to operate it seamlessly via your phone
or tablet.
• Strong Power: Equipped with a robust motor system for smooth and reliable
performance.

Mobile robots, like the Makerlab ESP32 WiFi Camera 4WD Smart Robot Kit, represent a
significant advancement in robotics, offering flexibility and adaptability in diverse environments.
Unlike stationary robots, mobile robots are designed to move through physical spaces,
performing tasks such as exploration, monitoring, or transportation. Their ability to navigate
autonomously or via remote control opens up a wide range of possibilities in fields like security,
surveillance, logistics, and education.

Iloilo Science and Technology University 42


ECEL 12: ELECTIVE 2 (ROBOTICS TECHNOLOGY)
Assessment: Use the provided space below to answer or provide what is being asked.

1. How does the integration of real-time image transmission aid in navigating mobile robots in
unfamiliar or obstructed environments?

2. What are the key factors to consider when designing an efficient path-planning algorithm
for a WiFi-controlled mobile robot operating in a dynamic environment?

3. What trade-offs exist between ESP32 CAM control board’s compact design and its processing
capabilities? How might these trade-offs limit the robot's performance in more complex tasks?

4. Propose a navigation strategy that combines FPV operation with pre-programmed routes
for efficient exploration of an unfamiliar area.

Iloilo Science and Technology University 43


ECEL 12: ELECTIVE 2 (ROBOTICS TECHNOLOGY)
5. Briefly describe your output in Item No.4.

6. Discuss a summary of your observations and analyses in this part of the activity.

Iloilo Science and Technology University 44


ECEL 12: ELECTIVE 2 (ROBOTICS TECHNOLOGY)
Hands-On Activity 1.3:
Programming a Basic Arduino Robot via Tinkercad

This task involves using Tikercad to program and simulate an Arduino board for controlling two
servo motors with buttons for manual adjustments. Additionally, a PIR motion sensor triggers
the servos to move to a specified position (90 degrees) for 3 seconds when motion is detected,
and then they return to their previous positions.

Required Components and Tools:


1. Arduino UNO (or compatible)
2. 2x Servo Motors
3. PIR Motion Sensor
4. 4x Push Buttons
5. 4x 10kΩ Resistors (for pull-down configuration of the buttons)
6. Breadboard
7. Jumper Wires
8. Computer with Installed Arduino IDE
9. 5V Power Supply (optional)
10. Internet Connection (for simulating via Tinkercad)

Iloilo Science and Technology University 45


ECEL 12: ELECTIVE 2 (ROBOTICS TECHNOLOGY)
Hardware Setup
1. Connecting the Servo Motors:
• Servo 1:
✓ Signal (Yellow/Orange) wire to pin 9.
✓ Power (Red) wire to 5V.
✓ Ground (Black/Brown) wire to GND.
• Servo 2:
✓ Signal (Yellow/Orange) wire to pin 10.
✓ Power (Red) wire to 5V.
✓ Ground (Black/Brown) wire to GND.
2. Connecting the PIR Motion Sensor:
• VCC pin of the PIR sensor to 5V.
• GND pin of the PIR sensor to GND.
• OUT pin of the PIR sensor to pin 2 on the Arduino.
3. Connecting the Push Buttons:
• Button 1 (Increase Servo 1):
✓ One side to pin 3.
✓ The other side to GND through a 10kΩ resistor.
✓ Connect the side going to pin 3 to 5V.
• Button 2 (Decrease Servo 1):
✓ One side to pin 4.
✓ The other side to GND through a 10kΩ resistor.
✓ Connect the side going to pin 4 to 5V.
• Button 3 (Increase Servo 2):
✓ One side to pin 5.
✓ The other side to GND through a 10kΩ resistor.
✓ Connect the side going to pin 5 to 5V.
• Button 4 (Decrease Servo 2):
✓ One side to pin 6.
✓ The other side to GND through a 10kΩ resistor.
✓ Connect the side going to pin 6 to 5V.

Iloilo Science and Technology University 46


ECEL 12: ELECTIVE 2 (ROBOTICS TECHNOLOGY)
Software Setup
1. Arduino Code:

#include <Servo.h>
Servo servo1, servo2;
int pos1 = 90, pos2 = 90; // Initial positions for the servos
const int btn1_inc = 3, btn1_dec = 4, btn2_inc = 5, btn2_dec = 6;
const int pirPin = 2; // PIR sensor pin
bool motionDetected = false;
int prevPos1, prevPos2;
void setup() {
servo1.attach(9);
servo2.attach(10);
pinMode(btn1_inc, INPUT_PULLUP);
pinMode(btn1_dec, INPUT_PULLUP);
pinMode(btn2_inc, INPUT_PULLUP);
pinMode(btn2_dec, INPUT_PULLUP);
pinMode(pirPin, INPUT);
servo1.write(pos1);
servo2.write(pos2);
}
void loop() {
// Check for button presses to adjust servo positions
if (!digitalRead(btn1_inc) && pos1 < 180) pos1++;
if (!digitalRead(btn1_dec) && pos1 > 0) pos1--;
if (!digitalRead(btn2_inc) && pos2 < 180) pos2++;
if (!digitalRead(btn2_dec) && pos2 > 0) pos2--;
// Check for motion detection from the PIR sensor
if (digitalRead(pirPin) == HIGH && !motionDetected) {
motionDetected = true;
// Store previous positions before moving to 90 degrees
prevPos1 = pos1;
prevPos2 = pos2;
// Move both servos to 90 degrees
pos1 = 90;
pos2 = 90;
servo1.write(pos1);
servo2.write(pos2);
delay(3000); // Keep the servos at 90 deg. for 3 seconds

Iloilo Science and Technology University 47


ECEL 12: ELECTIVE 2 (ROBOTICS TECHNOLOGY)
// Return the servos to their previous positions
pos1 = prevPos1;
pos2 = prevPos2;
servo1.write(pos1);
servo2.write(pos2);
// Reset the motion detected flag after handling
motionDetected = false;
}
// Update servo positions for button adjustments
servo1.write(pos1);
servo2.write(pos2);
delay(15); // Small delay for smooth movement
}

2. Code Explanation:
• Libraries: Includes the Servo library to control the servos.
• Servo Initialization: Initializes servo1 and servo2, attaching them to pins 9 and 10.
• Button and Sensor Setup: Configures button pins as INPUT_PULLUP for stable
reading, and the PIR sensor pin as INPUT.
• Manual Control: Reads button states to increment or decrement the servo angles
within the range of 0 to 180 degrees.
• Motion Detection: Checks the PIR sensor for motion. If motion is detected, it
stores the current positions, moves both servos to 90 degrees for 3 seconds, and
then returns them to their original positions.
• Servo Movement: Updates servo positions in each loop iteration for smooth
transitions.
3. Upload the Code:
• Connect your Arduino to your computer via USB.
• Open the Arduino IDE and copy the code into a new sketch.
• Select the correct board (Tools > Board > Arduino UNO) and port (Tools > Port).
• Click Upload to upload the code to your Arduino.

Iloilo Science and Technology University 48


ECEL 12: ELECTIVE 2 (ROBOTICS TECHNOLOGY)
Circuit and Code Testing
1. Test Button Control: Press each button to verify that servo1 and servo2 respond
correctly by increasing or decreasing their angles.
2. Test PIR Sensor: Move in front of the PIR sensor. Both servos should move to 90
degrees for 3 seconds and then return to their last position.
3. Adjust PIR Sensitivity (if needed): Adjust the sensitivity and delay knobs on the PIR
sensor to change the detection range and time before re-triggering.

Project Notes
✓ Ensure the servo motors are not drawing too much current, as this might reset the
Arduino. Consider using an external power source for the servos if needed.
✓ The PIR sensor might need a minute to calibrate when first powered on. During this
time, avoid any motion in front of it.
✓ The delay(15) in the loop is for smooth servo movement. Adjust this value if the
response time needs to be faster or slower.

Iloilo Science and Technology University 49


ECEL 12: ELECTIVE 2 (ROBOTICS TECHNOLOGY)
Assessment: Use the provided space below to answer what is being asked.

1. How does the integration of a PIR motion sensor with servo motors improve the automation
of a system? In what real-world applications could this setup be effectively utilized?

2. Discuss the ways that using Tinkercad to simulate this Arduino project help identify
potential issues in the hardware and programming.

3. What considerations should be made when programming the Arduino to handle


simultaneous inputs from buttons and a PIR motion sensor?

4. Design a mechanism where the PIR sensor and servo motors can operate collaboratively
but independently.

Iloilo Science and Technology University 50


ECEL 12: ELECTIVE 2 (ROBOTICS TECHNOLOGY)
5. Briefly describe your output in Item No.4.

6. Discuss a summary of your observations and analyses in this part of the activity.

Iloilo Science and Technology University 51


ECEL 12: ELECTIVE 2 (ROBOTICS TECHNOLOGY)
Hands-On Activity 1.4
Raspberry Pi-Based Robot Control Software

This task involves creating a web-based interface for controlling two servo motors and
monitoring motion detection using a PIR sensor. The web interface is hosted on a Raspberry Pi
and communicates with an Arduino via USB to perform the control tasks. Users can manually
adjust the servos or monitor motion detection status in real time.

Required Components and Tools:


1. Raspberry Pi (any model with internet connectivity)
2. Arduino UNO (or compatible)
3. 2x Servo Motors
4. PIR Motion Sensor
5. Computer with Installed Arduino IDE (for uploading Arduino code)
6. Breadboard and Jumper Wires
7. 5V Power Supply (optional, for external power to the servos)
8. Internet Connection (for Raspberry Pi setup and web access)

Hardware Setup
1. Connecting the Servo Motors:
• Servo 1:
✓ Signal (Yellow/Orange) wire to pin 9.
✓ Power (Red) wire to 5V.
✓ Ground (Black/Brown) wire to GND.

Iloilo Science and Technology University 52


ECEL 12: ELECTIVE 2 (ROBOTICS TECHNOLOGY)
• Servo 2:
✓ Signal (Yellow/Orange) wire to pin 10.
✓ Power (Red) wire to 5V.
✓ Ground (Black/Brown) wire to GND.
2. Connecting the PIR Motion Sensor:
• VCC pin of the PIR sensor to 5V.
• GND pin of the PIR sensor to GND.
• OUT pin of the PIR sensor to pin 2 on the Arduino.
3. Connecting Arduino to Raspberry Pi:
• Use a USB cable to connect the Arduino to the Raspberry Pi.

4. Optional: External Power Supply:


• If servos draw too much current, connect them to an external 5V power supply,
ensuring GND is shared with the Arduino.

Software Setup
1. Setup Flask on Raspberry Pi: Install Flask and required libraries.

sudo apt update


sudo apt install python3-pip
pip3 install flask pyserial

2. Directory Structure: Create the structure below.


project/

├── app.py # Main Flask application


├── static/
│ ├── styles.css # Optional CSS for styling
│ └── script.js # JavaScript for handling button clicks
and updates
├── templates/
│ └── index.html # HTML file for the web interface

Iloilo Science and Technology University 53


ECEL 12: ELECTIVE 2 (ROBOTICS TECHNOLOGY)
3. Flask Backend (app.py): This file handles serial communication with the Arduino and
serves the web interface.

from flask import Flask, render_template, jsonify, request


import serial
import time
# Initialize Flask app
app = Flask(__name__)
# Configure serial communication with Arduino
arduino = serial.Serial('/dev/ttyUSB0', 9600, timeout=1)
time.sleep(2) # Wait for Arduino to reset
@app.route('/')
def index():
return render_template('index.html')
@app.route('/servo', methods=['POST'])
def control_servo():
data = request.json
servo = data.get('servo')
action = data.get('action')
# Send command to Arduino
if servo and action:
command = f"{servo}:{action}\n" # Example: "servo1:inc\n"
arduino.write(command.encode())
return jsonify({"success": True, "command": command})
return jsonify({"success": False, "error": "Invalid data"})
@app.route('/motion', methods=['GET'])
def check_motion():
# Read motion detection status from Arduino
arduino.write(b"motion:status\n")
status = arduino.readline().decode().strip()
return jsonify({"motion_detected": status == "1"})
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000, debug=True)

4. HTML UI (templates/index.html): The web interface uses Bootstrap for styling.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">

Iloilo Science and Technology University 54


ECEL 12: ELECTIVE 2 (ROBOTICS TECHNOLOGY)
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Servo Control</title>
<link href="https://cdn.jsdelivr.net/npm/[email protected]
alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="/static/script.js" defer></script>
</head>
<body>
<div class="container mt-4">
<h1 class="text-center">Servo Motor Control</h1>
<div class="row mt-4">
<div class="col-md-6 text-center">
<h3>Servo 1</h3>
<button class="btn btn-primary"
onclick="controlServo('servo1',
'inc')">Increase</button>
<button class="btn btn-secondary"
onclick="controlServo('servo1',
'dec')">Decrease</button>
</div>
<div class="col-md-6 text-center">
<h3>Servo 2</h3>
<button class="btn btn-primary"
onclick="controlServo('servo2',
'inc')">Increase</button>
<button class="btn btn-secondary"
onclick="controlServo('servo2',
'dec')">Decrease</button>
</div>
</div>
<div class="row mt-4 text-center">
<h3>Motion Detection</h3>
<p id="motion-status" class="text-danger">Motion not
detected</p>
</div>
</div>
</body>
</html>

5. JavaScript (static/script.js): This script handles button clicks and updates.

function controlServo(servo, action) {


fetch('/servo', {

Iloilo Science and Technology University 55


ECEL 12: ELECTIVE 2 (ROBOTICS TECHNOLOGY)
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ servo, action })
})
.then(response => response.json())
.then(data => {
if (!data.success) {
alert("Failed to send command");
}
});
}
function updateMotionStatus() {
fetch('/motion')
.then(response => response.json())
.then(data => {
const statusElement = document.getElementById("motion-status");
if (data.motion_detected) {
statusElement.textContent = "Motion detected!";
statusElement.className = "text-success";
} else {
statusElement.textContent = "Motion not detected";
statusElement.className = "text-danger";
}
});
}
// Periodically update motion detection status
setInterval(updateMotionStatus, 1000);

6. Arduino Code Adjustments: Modify the Arduino code to parse commands received
from the Raspberry Pi and respond with motion detection status.

#include <Servo.h>
Servo servo1, servo2;
int pos1 = 90, pos2 = 90;
const int pirPin = 2;
bool motionDetected = false;
void setup() {
servo1.attach(9);
servo2.attach(10);
pinMode(pirPin, INPUT);
servo1.write(pos1);
servo2.write(pos2);

Iloilo Science and Technology University 56


ECEL 12: ELECTIVE 2 (ROBOTICS TECHNOLOGY)
Serial.begin(9600);
}
void loop() {
// Check for commands from Raspberry Pi
if (Serial.available()) {
String command = Serial.readStringUntil('\n');
if (command.startsWith("servo1:inc") && pos1 < 180) pos1++;
else if (command.startsWith("servo1:dec") && pos1 > 0) pos1--;
else if (command.startsWith("servo2:inc") && pos2 < 180) pos2++;
else if (command.startsWith("servo2:dec") && pos2 > 0) pos2--;
else if (command.startsWith("motion:status")) {
Serial.println(digitalRead(pirPin));
}
}
// Update servos
servo1.write(pos1);
servo2.write(pos2);
delay(15);
}

Code Explanation:
• Flask Backend (Raspberry Pi):
▪ Serial Communication: The Flask app sends commands (e.g., increase/decrease
servo angles) via USB to the Arduino and reads motion detection status.
▪ Web Interface: Serves the HTML page to control servos and view motion status in
real time.
• Frontend (HTML + JavaScript):
▪ Servo Controls: Buttons for manually increasing/decreasing servo angles for each
motor.
▪ Motion Status: Real-time updates on motion detection.
• Arduino Code:
▪ Libraries: Includes the Servo library to control the motors.
▪ Servo Initialization: Sets up servo1 and servo2 on pins 9 and 10.
▪ Motion Detection: Reads the PIR sensor status and sends responses to the
Raspberry Pi.
▪ Command Handling: Parses incoming commands from the Raspberry Pi.

Iloilo Science and Technology University 57


ECEL 12: ELECTIVE 2 (ROBOTICS TECHNOLOGY)
Testing the System
1. Run the Flask App: Start the Flask app on the Raspberry Pi and access the web
interface from a browser at http://<Raspberry_Pi_IP>:5000.s
2. Test Servo Controls: Use the web buttons to increase or decrease the servo angles.
Ensure smooth movements between 0 and 180 degrees.
3. Test Motion Detection: Move in front of the PIR sensor. Verify that the motion status
updates in the web interface.
4. Verify Real-Time Updates: Ensure that the interface updates motion detection status
every second.

Project Notes
✓ Servo Power: If the servos cause the Arduino to reset due to high current draw, use an
external 5V power supply for the servos.
✓ PIR Sensor Calibration: Allow 1-2 minutes for the PIR sensor to stabilize after powering
on. Avoid motion during this time.
✓ Smooth Servo Movements: The delay in the Arduino code ensures smooth servo
transitions. Adjust if faster response is needed.
✓ Network Access: Ensure the Raspberry Pi and client device (browser) are on the same
network to access the web interface.

Iloilo Science and Technology University 58


ECEL 12: ELECTIVE 2 (ROBOTICS TECHNOLOGY)
Assessment: Use the provided space below to answer or provide what is being asked.

1. What considerations are essential for seamless USB communication between a Raspberry
Pi and an Arduino in a robotic system ? How can data synchronization be maintained?

2. Discuss the challenges that could arise in providing real-time servo adjustments via the
web interface, and how could these challenges be mitigated.

3. Summarize the benefits and challenges of using real-time operating systems (RTOS) on
Raspberry Pi for robotic control. How do they compare to standard Linux distributions?

4. Create a basic web-based control software for a robotic system implemented on a


Raspberry Pi board. This should feature both manipulation and mobile robot functionalities.

Iloilo Science and Technology University 59


ECEL 12: ELECTIVE 2 (ROBOTICS TECHNOLOGY)
5. Briefly describe your output in Item No.4.

6. Discuss a summary of your observations and analyses in this part of the activity.

Iloilo Science and Technology University 60

You might also like