ECEL 12 Activity 1 (Getting Started with Robot Assembly and Programming)
ECEL 12 Activity 1 (Getting Started with Robot Assembly and Programming)
Activity 1
Getting Started with Robot Assembly and Programming
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.
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.
Types of End-Effectors
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.
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.
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.
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.
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
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:
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).
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.
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.
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.
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.
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.
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.
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;
}
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.)
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.
# 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:
Numeric
Boolean
Sequence
Mapping
Set
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.
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()
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.")
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()
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.
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.
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.
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
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.
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.
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.
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.
6. Discuss a summary of your observations and analyses in this part of the activity.
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.
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.
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.
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.
6. Discuss a summary of your observations and analyses in this part of the activity.
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.
#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
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.
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.
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.
4. Design a mechanism where the PIR sensor and servo motors can operate collaboratively
but independently.
6. Discuss a summary of your observations and analyses in this part of the activity.
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.
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.
Software Setup
1. Setup Flask on Raspberry Pi: Install Flask and required libraries.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
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);
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.
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.
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?
6. Discuss a summary of your observations and analyses in this part of the activity.