0% found this document useful (0 votes)
45 views38 pages

Lab Robotics

The AIL332 Robotics Lab Manual outlines the objectives, vision, and mission of the Department of Artificial Intelligence and Data Science at MITS, focusing on robotics education. It includes detailed program educational objectives, outcomes, and specific outcomes related to AI and data science, along with a list of experiments involving Arduino interfacing and intelligent systems. The manual also emphasizes safety precautions and proper lab conduct for students participating in the robotics lab.

Uploaded by

akshayapius
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
45 views38 pages

Lab Robotics

The AIL332 Robotics Lab Manual outlines the objectives, vision, and mission of the Department of Artificial Intelligence and Data Science at MITS, focusing on robotics education. It includes detailed program educational objectives, outcomes, and specific outcomes related to AI and data science, along with a list of experiments involving Arduino interfacing and intelligent systems. The manual also emphasizes safety precautions and proper lab conduct for students participating in the robotics lab.

Uploaded by

akshayapius
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

AIL332 Robotics Lab Manual

Lab Manual

AIL332 ROBOTICS LAB

Dept. of CS AI, MITS


AIL332 Robotics Lab Manual

DEPARTMENT OF ARTIFICIAL
INTELLIGENCE AND DATA SCIENCE

LAB MANUAL

Course Name: AIL332 ROBOTICS LAB

Semester: VI

Prepared by Approved by

Dr. Arunkant A Jose Dr.Suma Mary Idicula


Assistant Professor, ECE Head of the Department, AI&DS

Dept. of CS AI, MITS


AIL332 Robotics Lab Manual

VISION

“To be a centre of excellence for learning and research in engineering and technology, producing
intellectually well-equipped and socially committed citizens possessing an ethical value
system.”.

MISSION

1. Offer a well-balanced programme of instruction, practical exercise and opportunities in


technology.
2. Foster innovation and ideation of technological solution on a sustained basis.
3. Nurture a value system in students and engender in them a spirit of inquiry.

VISION OF AI &DS DEPARTMENT


To excel globally in teaching, research, and technology development & transfer in the field of
Artificial Intelligence and Data science with a spirit of social commitment.

MISSION OF AI&DS DEPARTMENT

1.Facilitate learning and innovative research in the frontier areas of AI & DS like Natural
language Processing, Robotics and Computer Vision.
2.Drive students for technology development and transfer to solve socially relevant problems.
3.Create socially responsible professionals.

PROGRAM EDUCATIONAL OBJECTIVES (PEO)


PE01:Design AI models to automate various processes in industrial applications.
PEO2:Interpret and visualize high dimensional data for decision making systems.

PROGRAMME OUTCOMES (POs)

Dept. of CS AI, MITS


AIL332 Robotics Lab Manual

PO1. Engineering Knowledge: Apply knowledge of mathematics, science, engineering


fundamentals, and an engineering specialization to the solution of complex engineering
problems.
PO2. Problem Analysis: Identify, formulate, research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of mathematics,
natural sciences, and engineering sciences.
PO3. Design/development of Solutions: Design solutions for complex engineering problems and
design system components or processes that meet t h e specified needs with appropriate
consideration for the public health and safety, and the cultural, societal, and environmental
considerations.
PO4. Conduct Investigations of Complex Problems: Use research-based knowledge and research
methods including design of experiments, analysis and interpretation of data, and synthesis of the
information to provide valid conclusions.
PO5. Modern Tool usage: Create, select, and apply appropriate techniques, resources, and
modern engineering and IT tools including prediction and modelling to complex engineering
activities with an understanding of the limitations.
PO6. The Engineer and Society: Apply reasoning informed by the contextual knowledge to
assess societal, health, safety, legal and cultural issues and the consequent responsibilities
relevant to the professional engineering practice.
PO7. Environment and Sustainability: Understand the impact of the professional engineering
solutions in societal and environmental contexts, and demonstrate the knowledge of, and need
for sustainable development.
PO8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and
norms of the engineering practice.
PO9. Individual and Team Work: Function effectively as an individual, and as a member or
leader in diverse teams, and in multidisciplinary settings.
PO10. Communication: Communicate effectively on complex engineering activities with the
engineering community and with society at large, such as, being able to comprehend and write
effective reports and design documentation, make effective presentations, and give and receive
clear instructions.
PO11. Project Management and Finance: Demonstrate knowledge and understanding of the

Dept. of CS AI, MITS


AIL332 Robotics Lab Manual

engineering and management principles and apply these to one’s own work, as a member and
leader in a team, to manage projects and in multidisciplinary environments.
PO12. Life-long Learning: Recognize the need for, and have the preparation and ability to
engage in independent and life-long learning in the broadest context of technological change.

PROGRAMME SPECIFIC OUTCOMES (PSOs)

Student of the AI &DS program will:


PSO1.Design solutions relating to big data problems.
PSO2. Implement AI Techniques to human language processing, computer vision and decision
making.
PSO3.Develop computational models for system automation.

LIST OF EXPERIMENTS

Part A: Interfacing sensors and actuators

Dept. of CS AI, MITS


AIL332 Robotics Lab Manual

1. Familiarization of Arduino IDE,Arduino microcontroller I/O interfacing( LED,


LCD,Serial Monitor)
2. Interfacing IR and Ultrasonic sensor with Arduino
3. Interfacing DC motors with arduino - speed and direction control
4. Interfacing Servo Motors with Arduino - angle of rotation

Part B: Intelligent systems


5. Writing a Simple Publisher and Subscriber, Simple Service and Client,Recording and
playing back data, Reading messages from a bag file(Python/C++)
6. Touch Sensors interfacing and feedback system
7. Line following Robot using IR sensor
8. Object detection using any one standard algorithm

PRECAUTIONS

Dept. of CS AI, MITS


AIL332 Robotics Lab Manual

1. PROPER UNIFORM AND ID CARD IS MANDATORY.


2. WHEN YOU ENTER THE LAB IT IS MANDATORY TO RECORD YOUR ENTRY IN
THE LOG REGISTER PROVIDED FOR THE PURPOSE
3. BEFORE STARTING THE LAB WORKS, ENSURE ALL COMPUTERS ARE IN
WORKING CONDITION.
4. THEY SHOULD FILL UP THE ISSUE REGISTER FOR THE INSTRUMENTS NEEDED
TO DO THE EXPERIMENTS AND GET THEM ISSUED
5. MAINTAIN STRICT DISCIPLINE IN THE LAB.
6. ARRANGE THE FURNITURE IN PROPER ORDER BEFORE LEAVING THE LAB.
7. SWITCH OFF ALL ELECTRICAL EQUIPMENTS BEFORE LEAVING THE ROOM.
8. INFORM FACULTY/LAB STAFF IN CASE OF ANY DOUBT OR FAULT.
9. DO NOT KEEP THE EQUIPMENTS ON WHEN NOT IN USE.
10. BROWSING IS NOT ALLOWED UNLESS REQUIRED AS PART OF THE SESSION. IN
THAT CASE, PRESENCE OF FACULTY/LAB STAFF IS MANDATORY.
11. NO REMOVABLE DEVICES AND MOBILE PHONES ARE ALLOWED IN THE LAB.
12. DO NOT ATTEMPT TO EXPERIMENT OR TAMPER WITH EQUIPMENTS OR
COMPONENTS.
13. EATABLES ARE NOT ALLOWED IN THE LAB PREMISES.
14. DO NOT MOVE THE EQUIPMENTS FROM THE DESIGNATED TABLE WITHOUT
INFORMING THE
FACULTY/LAB STAFF.

EXPERIMENT 1
Familiarization of Arduino IDE, Arduino microcontroller, I/O interfacing (LED, LCD, Serial
Monitor)

Dept. of CS AI, MITS


AIL332 Robotics Lab Manual

AIM : To Familiarization of Arduino IDE, Arduino microcontroller, I/O interfacing (LED,


LCD, Serial Monitor)

Requirements : Computer with ARDUINO, LED, LCD

THEORY :

Arduino Software (IDE):- Includes the built in support for the boards in the following list, all
based on the AVR Core. The Boards Manager included in the standard installation allows to add
support for the growing number of new boards based on different cores like Arduino Due,
Arduino Zero, Edison, Galileo and so on.
● Arduino Yún An ATmega32u4 running at 16 MHz with auto-reset, 12 Analog In, 20
Digital I/O and 7 PWM.
● Arduino Uno An ATmega328P running at 16 MHz with auto-reset, 6 Analog In, 14
Digital I/O and 6 PWM.
● Arduino Diecimila or Duemilanove w/ ATmega168 An ATmega168 running at 16 MHz
with auto-reset.
● Arduino Nano w/ ATmega328P An ATmega328P running at 16 MHz with auto-reset.
Has eight analog inputs.
● Arduino Mega 2560 An ATmega2560 running at 16 MHz with auto-reset, 16 Analog In,
54 Digital I/O and 15 PWM.
● Arduino Mega An ATmega1280 running at 16 MHz with auto-reset, 16 Analog In, 54
Digital I/O and 15 PWM.
● Arduino Mega ADK An ATmega2560 running at 16 MHz with auto-reset, 16 Analog In,
54 Digital I/O and 15 PWM.
● Arduino Leonardo An ATmega32u4 running at 16 MHz with auto-reset, 12 Analog In,
20 Digital I/O and 7 PWM.
● Arduino Micro An ATmega32u4 running at 16 MHz with auto-reset, 12 Analog In, 20
Digital I/O and 7 PWM.
● Arduino Esplora An ATmega32u4 running at 16 MHz with auto-reset.
● Arduino Mini w/ ATmega328P An ATmega328P running at 16 MHz with auto-reset, 8
Analog In, 14 Digital I/O and 6 PWM.

Dept. of CS AI, MITS


AIL332 Robotics Lab Manual

● Arduino Ethernet Equivalent to Arduino UNO with an Ethernet shield: An ATmega328P


running at 16 MHz with auto-reset, 6 Analog In, 14 Digital I/O and 6 PWM.
● Arduino Fio An ATmega328P running at 8 MHz with auto-reset. Equivalent to Arduino
Pro or Pro Mini (3.3V, 8 MHz) w/ ATmega328P, 6 Analog In, 14 Digital I/O and 6
PWM.
● Arduino BT w/ ATmega328P ATmega328P running at 16 MHz. The bootloader burned
(4 KB) includes codes to initialize the on-board Bluetooth® module, 6 Analog In, 14
Digital I/O and 6 PWM..
● LilyPad Arduino USB An ATmega32u4 running at 8 MHz with auto-reset, 4 Analog In,
9 Digital I/O and 4 PWM.
● LilyPad Arduino An ATmega168 or ATmega132 running at 8 MHz with auto-reset, 6
Analog In, 14 Digital I/O and 6 PWM.
● Arduino Pro or Pro Mini (5V, 16 MHz) w/ ATmega328P An ATmega328P running at 16
MHz with auto-reset. Equivalent to Arduino Duemilanove or Nano w/ ATmega328P; 6
Analog In, 14 Digital I/O and 6 PWM.
● Arduino NG or older w/ ATmega168 An ATmega168 running at 16 MHzwithout auto-
reset. Compilation and upload is equivalent to Arduino Diecimila or Duemilanove w/
ATmega168, but the bootloader burned has a slower timeout (and blinks the pin 13 LED
three times on reset); 6 Analog In, 14 Digital I/O and 6 PWM.
● Arduino Robot Control An ATmega328P running at 16 MHz with auto-reset.
● Arduino Robot Motor An ATmega328P running at 16 MHz with auto-reset.
Arduino microcontroller:- The board selection has two effects: it sets the parameters (e.g. CPU
speed and baud rate) used when compiling and uploading sketches; and sets and the file and fuse
settings used by the burn bootloader command. Some of the board definitions differ only in the
latter, so even if you've been uploading successfully with a particular
Interfacing LED:- The built-in LED that most Arduino boards have. This LED is connected to a
digital pin and its number may vary from board type to board type. To make your life easier, we
have a constant that is specified in every board descriptor file. This constant
is LED_BUILTIN and allows you to control the built-in LED easily. Here is the correspondence
between the constant and the digital pin.

Dept. of CS AI, MITS


AIL332 Robotics Lab Manual

Interfacing LCD:- The LCDs have a parallel interface, meaning that the microcontroller has to
manipulate several interface pins at once to control the display. The interface consists of the
following pins:
● A register select (RS) pin that controls where in the LCD's memory you're writing data
to. You can select either the data register, which holds what goes on the screen, or an
instruction register, which is where the LCD's controller looks for instructions on what to
do next.
● A Read/Write (R/W) pin that selects reading mode or writing mode

● An Enable pin that enables writing to the registers

● 8 data pins (D0 -D7). The states of these pins (high or low) are the bits that you're writing
to a register when you write, or the values you're reading when you read.
There's also a display contrast pin (Vo), power supply pins (+5V and GND) and LED Backlight
(Bklt+ and BKlt-) pins that you can use to power the LCD, control the display contrast, and turn
on and off the LED backlight, respectively.
The process of controlling the display involves putting the data that form the image of what you
want to display into the data registers, then putting instructions in the instruction register.
The Liquid Crystal Library simplifies this for you so you don't need to know the low-level
instructions.
The Hitachi-compatible LCDs can be controlled in two modes: 4-bit or 8-bit. The 4-bit mode
requires seven I/O pins from the Arduino, while the 8-bit mode requires 11 pins. For displaying
text on the screen, you can do most everything in 4-bit mode, so example shows how to control a
16x2 LCD in 4-bit mode.

Serial Monitor:- The Arduino IDE has a feature that can be a great help in debugging sketches
or controlling Arduino from your computer's keyboard.The Serial Monitor is a separate pop-up
window that acts as a separate terminal that communicates by receiving and sending Serial
Data.Serial Data is sent over a single wire (but usually travels over USB in our case) and consists
of a series of 1's and 0's sent over the wire. Data can be sent in both directions (In our case on
two wires). will use the Serial Monitor to debug Arduino Software Sketches or to view data sent
by a working Sketch. You must have an Arduino connected by USB to your computer to be able
to activate the Serial Monitor.To get familiar with using the Serial Monitor, Copy and Paste the

Dept. of CS AI, MITS


AIL332 Robotics Lab Manual

following example Sketch into a blank Arduino IE window. Then Verify it and if it's OK,
Upload it. The next step will show you what to expect.
PROGRAMS

Interfacing LED

void setup() {
// initialize digital pin LED_BUILTIN as an output.
pinMode(LED_BUILTIN, OUTPUT);
}
// the loop function runs over and over again forever
void loop() {
digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH is the voltage level)
delay(1000); // wait for a second
digitalWrite(LED_BUILTIN, LOW); // turn the LED off by making the voltage LOW
delay(1000); // wait for a second
}
Interfacing LCD
#include <LiquidCrystal.h>
// initialize the library by associating any needed LCD interface pin
// with the arduino pin number it is connected to
const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);
void setup() {
// set up the LCD's number of columns and rows:
lcd.begin(16, 2);
// Print a message to the LCD.
lcd.print("hello, world!");
}
void loop() {
// set the cursor to column 0, line 1
// (note: line 1 is the second row, since counting begins with 0):
lcd.setCursor(0, 1);

Dept. of CS AI, MITS


AIL332 Robotics Lab Manual

// print the number of seconds since reset:


lcd.print(millis() / 1000);
}
Interfacing Serial Monitor
void setup()
{
Serial.begin(9600);
Serial.println("--- Start Serial Monitor SEND_RCVE ---");
Serial.println(" Type in Box above, . ");
Serial.println("(Decimal)(Hex)(Character)");
Serial.println();
}
//--(end setup )---
void loop() /****** LOOP: RUNS CONSTANTLY ******/
{
if (Serial.available() > 0)
{
ByteReceived = Serial.read();
Serial.print(ByteReceived);
Serial.print(" ");
Serial.print(ByteReceived, HEX);
Serial.print(" ");
Serial.print(char(ByteReceived));
if(ByteReceived == '1') // Single Quote! This is a character.
{
digitalWrite(led,HIGH);
Serial.print(" LED ON ");
}
if(ByteReceived == '0')
{
digitalWrite(led,LOW);

Dept. of CS AI, MITS


AIL332 Robotics Lab Manual

Serial.print(" LED OFF");


}
Serial.println(); // End the line
// END Serial Available
}
}
SCHEMATIC

Interfacing LED

Interfacing LCD

Dept. of CS AI, MITS


AIL332 Robotics Lab Manual

Interfacing Serial Monitor

RESULT

Dept. of CS AI, MITS


AIL332 Robotics Lab Manual

Familiarized Arduino IDE, Arduino microcontroller, I/O interfacing (LED, LCD, Serial
Monitor).

EXPERIMENT 2

Dept. of CS AI, MITS


AIL332 Robotics Lab Manual

Interfacing IR and Ultrasonic sensor with Arduino

AIM : To Interfacing IR and Ultrasonic sensor

Requirements: Computer with ARDUINO, IR Module, Ultrasonic sensor module

THEORY :

Interfacing IR:- The sensor output pin is connected to the digital pin 3. The IR or obstacle
sensor gives logic HIGH (1) as output when there is no obstacle in front of it, and it will give
logic LOW (0) output when an obstacle is placed in front of it. We need to read these logical
changes on the Arduino. The LED is an indicator which is connected to Arduino digital pin 11.
Interfacing the IR sensor with Arduino works using simple Logic. That is If Arduino reads LOW
data from the sensor output pin, LED should turn ON. Else if Arduino reads HIGH data from the
sensor output pin, LED should turn OFF.

Interfacing Ultrasonic sensor:- To trigger the ultrasonic Sensor for 10 microseconds to


generate ultrasonic wave from the transmitter part. If any object comes in front of the sensor
detection range. Then the ultrasonic wave reflects back from the object surface to the receiver
part. When the receiver receives the wave then the Eco pin provides high output. Now the
Arduino read the time duration between triggering and Receiving the wave by the sensor. Then
Arduino calculate the distance between the sensor and object by a simple formula
Distance= (Ultrasonic wave travel time x Speed of sound)/2 Where the speed of sound in Air is
around 340 meters/second or 0.034cm/µs.

PROGRAMS

Interfacing IR

int IRSensor = 3; // connect ir sensor to arduino pin 3


int LED = 11; // conect Led to arduino pin 13
void setup()
{
pinMode (IRSensor, INPUT); // sensor pin INPUT
pinMode (LED, OUTPUT); // Led pin OUTPUT
Serial.begin (9600); //// Starts the serial communication
}
void loop()
{
//Define a variables for read the IRsensor

Dept. of CS AI, MITS


AIL332 Robotics Lab Manual

int Sensordata = digitalRead (IRSensor);

// Prints the output data on the Serial Monitor


Serial.print("Sensor value:");
Serial.println(Sensordata);
if (Sensordata == 0) //Check the sensor output
{
digitalWrite(LED, HIGH); // LED High
}
else
{
digitalWrite(LED, LOW); // LED LOW
}
}
Interfacing Ultrasonic sensor

int trigpin = 3;
int echopin = 4;
long duration;
int distance;
void setup()
{
pinMode(trigpin,OUTPUT);
pinMode(echopin,INPUT);
Serial.begin (9600);
}
void loop()
{
digitalWrite(trigpin,LOW);
delayMicroseconds(2);
digitalWrite(trigpin,HIGH);
delayMicroseconds(10);

Dept. of CS AI, MITS


AIL332 Robotics Lab Manual

digitalWrite(trigpin,LOW);
duration = pulseIn(echopin,HIGH);
distance = duration*0.034/2;
Serial.print("distance:");
Serial.print(distance);
Serial.println(" cm");
delay(500);
}

SCHEMATIC
Interfacing IR

Interfacing Ultrasonic sensor

Dept. of CS AI, MITS


AIL332 Robotics Lab Manual

RESULT
Successfully interfaced IR and Ultrasonic sensor.

Dept. of CS AI, MITS


AIL332 Robotics Lab Manual

EXPERIMENT 3
Interfacing DC motors with Arduino - speed and direction control
AIM : To interface DC motors with Arduino - speed and direction control

Requirements : Computer with ARDUINO and DC motor

THEORY:- DC motor converts electrical energy in the form of Direct Current into mechanical
energy in the form of rotational motion of the motor shaft.The DC motor speed can be controlled
by applying varying DC voltage; whereas the direction of rotation of the motor can be changed
by reversing the direction of current through it.For applying varying voltage, we can make use of
PWM technique.For reversing the current, we can make use of H-Bridge circuit or motor driver
ICs that employ the H-Bridge technique.For more information about DC motors and how to use
them, H-Bridge circuit configurations, and PWM technique.

PROGRAMS

const int POT_input = A1; /* assign ADC Channel */


bool d1 = HIGH;
bool d2 = LOW;
void setup() {
pinMode(4, OUTPUT); /* Motor control pin 1 */
pinMode(7, OUTPUT); /* Motor control pin 2 */
pinMode(3, OUTPUT); /* PWM pin for Speed Control */
pinMode(2, INPUT_PULLUP); /* Interrupt pin for direction control */
attachInterrupt(digitalPinToInterrupt(2), motor, FALLING); /* Interrupt on falling edge on pin 2 */
}
void loop() {
int pwm_adc;
pwm_adc = analogRead(POT_input); /* Input from Potentiometer for speed control */
digitalWrite(4,d1);
digitalWrite(7,d2);
analogWrite(3, pwm_adc / 4);
}
void motor(){
d1 = !d1;
d2 = !d2;
_delay_ms(200);
}

Dept. of CS AI, MITS


AIL332 Robotics Lab Manual

SCHEMATIC

RESULT
Successfully interfaced DC motors with Arduino for speed and direction control.

Dept. of CS AI, MITS


AIL332 Robotics Lab Manual

EXPERIMENT 4
Interfacing Servo Motors with Arduino - angle of rotation

AIM : To interface Servo Motors with Arduino - angle of rotation

Requirements : Computer with ARDUINO & Servo Motors

THEORY:- A servo motor is an electrical device used to rotate objects at certain specified
angles. It’s just a basic motor that runs through the mechanism of the servo. They are used in
numerous applications such as toy cars, robotics, machines etc. Servo motors are measured in kg
/ cm (kilogram per centimeter). Servo motors are rated 3kg / cm or 6kg / cm etc. This kg / cm tell
you how much weight your servo engine can lift at a given distance. Generally servo motor
9G SG90 is used.Servo motors have 3 wires coming out of them. Out of which 2 are used
as Power pins (positive and negative) and the third one is used for the signal that is to be sent
from the MCU.All Servo motors operate on the principle of PWM (Pulse Width Modulation),
meaning their angle of rotation is controlled by the length of the pulse applied to their Control
PIN. Essentially, the servo motor consists of a DC motor powered by a variable resistor
(potentiometer – POT) and some gears.

PWM signals of different duty cycles

Dept. of CS AI, MITS


AIL332 Robotics Lab Manual

Servo motor SG90 can be rotated from 0 to 180 degree, but other servo motors can rotate
completely 360 degree depending upon manufacturer. By adding the correct width of the
Electrical Pulse to its control pin, this degree of rotation can be controlled.

PROGRAMS

// PWM supported pins in Arduino Uno are 3, 5, 6, 9, 10, and 11.


#define del 15
// include servo library, don't need to install externally already available in arduino IDE
#include <Servo.h>
// create servo object to control a servo
Servo myservo;
void setup() {
/* Attaches servo variable myservo to pin 9.
Using myservo you can use servo library inbuilt function, which control servo connected on
pin 9
*/ myservo.attach(9);
Serial.begin(9600);
}
void loop() {
// rotate servo motor from 0 to 180 degree
for (int i = 0 ; i <= 180 ; i++) {
// set servo motor angle to value i
myservo.write(i);
// prints i value to serial monitor
Serial.println(i);
delay(del);
}
// rotate servo motor from 180 to 0 degree
for (int i = 180 ; i >= 0 ; i--) {
myservo.write(i);
Serial.println(i);
delay(del);
}

Dept. of CS AI, MITS


AIL332 Robotics Lab Manual

SCHEMATIC

RESULT
Successfully interfaced Servo Motors with Arduino to vary angle of rotation.

Dept. of CS AI, MITS


AIL332 Robotics Lab Manual

EXPERIMENT 5
Writing a Simple Publisher and Subscriber, Simple Service and Client, Recording, and playing
back data, Reading messages from a bag file (Python)

AIM : To write a Simple Publisher and Subscriber, Simple Service and Client, Recording, and
playing back data, Reading messages from a bag file (Python)

Requirements :

THEORY:- A ROS Node can be a Publisher or a Subscriber. A Publisher is the one that puts the
messages of some standard Message Type to a particular Topic. The Subscriber on the other
hand subscribes to the Topic so that it receives the messages whenever any message is published
to the Topic

Services are another way to pass data between nodes in ROS. Services are just synchronous
remote procedure calls; they allow one node to call a function that executes in another node. We
define the inputs and outputs of this function similarly to the way we define new message types.
A ROS client library is a collection of code that eases the job of the ROS programmer. It takes
many of the ROS concepts and makes them accessible via code. In general, these libraries let you
write ROS nodes, publish and subscribe to topics, write and call services, and use the Parameter
Server.

A bag is a file format in ROS for storing ROS message data. Bags -- so named because of their
.bag extension -- have an important role in ROS, and a variety of tools have been written to allow
you to store, process, analyze, and visualize them.

The ROS Bag is a powerful tool for you to record and playback your simulation.

PROGRAMS

1. Writing a Publisher Node

1 #!/usr/bin/env python
2 # license removed for brevity
3 import rospy
4 from std_msgs.msg import String
5
6 def talker():
7 pub = rospy.Publisher('chatter', String, queue_size=10)
8 rospy.init_node('talker', anonymous=True)
9 rate = rospy.Rate(10) # 10hz
10 while not rospy.is_shutdown():

Dept. of CS AI, MITS


AIL332 Robotics Lab Manual

11 hello_str = "hello world %s" % rospy.get_time()


12 rospy.loginfo(hello_str)
13 pub.publish(hello_str)
14 rate.sleep()
15
16 if __name__ == '__main__':
17 try:
18 talker()
19 except rospy.ROSInterruptException:
20 pass

2. Writing the Subscriber Node


1 #!/usr/bin/env python
2 import rospy
3 from std_msgs.msg import String
4
5 def callback(data):
6 rospy.loginfo(rospy.get_caller_id() + "I heard %s", data.data)
7
8 def listener():
9
10 # In ROS, nodes are uniquely named. If two nodes with the same
11 # name are launched, the previous one is kicked off. The
12 # anonymous=True flag means that rospy will choose a unique
13 # name for our 'listener' node so that multiple listeners can
14 # run simultaneously.
15 rospy.init_node('listener', anonymous=True)
16
17 rospy.Subscriber("chatter", String, callback)
18
19 # spin() simply keeps python from exiting until this node is stopped
20 rospy.spin()
21
22 if __name__ == '__main__':
23 listener()

3. Writing the Service Node

1 #!/usr/bin/env python
2
3 from __future__ import print_function
4
5 from beginner_tutorials.srv import AddTwoInts,AddTwoIntsResponse
6 import rospy
7

Dept. of CS AI, MITS


AIL332 Robotics Lab Manual

8 def handle_add_two_ints(req):
9 print("Returning [%s + %s = %s]"%(req.a, req.b, (req.a + req.b)))
10 return AddTwoIntsResponse(req.a + req.b)
11
12 def add_two_ints_server():
13 rospy.init_node('add_two_ints_server')
14 s = rospy.Service('add_two_ints', AddTwoInts, handle_add_two_ints)
15 print("Ready to add two ints.")
16 rospy.spin()
17
18 if __name__ == "__main__":
19 add_two_ints_server()

4. Writing the Client Node

1 #!/usr/bin/env python
2
3 from __future__ import print_function
4
5 import sys
6 import rospy
7 from beginner_tutorials.srv import *
8
9 def add_two_ints_client(x, y):
10 rospy.wait_for_service('add_two_ints')
11 try:
12 add_two_ints = rospy.ServiceProxy('add_two_ints', AddTwoInts)
13 resp1 = add_two_ints(x, y)
14 return resp1.sum
15 except rospy.ServiceException as e:
16 print("Service call failed: %s"%e)
17
18 def usage():
19 return "%s [x y]"%sys.argv[0]
20
21 if __name__ == "__main__":
22 if len(sys.argv) == 3:
23 x = int(sys.argv[1])
24 y = int(sys.argv[2])
25 else:
26 print(usage())

Dept. of CS AI, MITS


AIL332 Robotics Lab Manual

27 sys.exit(1)
28 print("Requesting %s+%s"%(x, y))
29 print("%s + %s = %s"%(x, y, add_two_ints_client(x, y)))

OUTPUT

Writing the Publisher Node:


[INFO] [WallTime: 1314931831.774057] hello world 1314931831.77
[INFO] [WallTime: 1314931832.775497] hello world 1314931832.77
[INFO] [WallTime: 1314931833.778937] hello world 1314931833.78
[INFO] [WallTime: 1314931834.782059] hello world 1314931834.78
[INFO] [WallTime: 1314931835.784853] hello world 1314931835.78
[INFO] [WallTime: 1314931836.788106] hello world 1314931836.79

Writing the Subscriber Node:


[INFO] [WallTime: 1314931969.258941] /listener_17657_1314931968795I heard hello
world 1314931969.26
[INFO] [WallTime: 1314931970.262246] /listener_17657_1314931968795I heard hello
world 1314931970.26
[INFO] [WallTime: 1314931971.266348] /listener_17657_1314931968795I heard hello
world 1314931971.26
[INFO] [WallTime: 1314931972.270429] /listener_17657_1314931968795I heard hello
world 1314931972.27
[INFO] [WallTime: 1314931973.274382] /listener_17657_1314931968795I heard hello
world 1314931973.27
[INFO] [WallTime: 1314931974.277694] /listener_17657_1314931968795I heard hello
world 1314931974.28
[INFO] [WallTime: 1314931975.283708] /listener_17657_1314931968795I heard hello
world 1314931975.28

Result
Successfully accomplished a Simple Publisher and Subscriber, Simple Service and Client,
Recording, and playing back data, Reading messages from a bag file (Python).

Dept. of CS AI, MITS


AIL332 Robotics Lab Manual

EXPERIMENT 6
Touch Sensors interfacing and feedback system

AIM : To execute Touch Sensor interfacing and feedback system

Requirements : Touch Sensor, Arduino

THEORY:-

PROGRAMS

Code to detect LOW to HIGH

// constants won't change. They're used here to set pin numbers:


const int SENSOR_PIN = 7; // the Arduino's input pin that connects to the sensor's SIGNAL pin

// Variables will change:


int lastState = LOW; // the previous state from the input pin
int currentState; // the current reading from the input pin

void setup() {
// initialize serial communication at 9600 bits per second:
Serial.begin(9600);
// initialize the Arduino's pin as aninput
pinMode(SENSOR_PIN, INPUT);
}

Dept. of CS AI, MITS


AIL332 Robotics Lab Manual

void loop() {
// read the state of the the input pin:
currentState = digitalRead(SENSOR_PIN);

if(lastState == LOW && currentState == HIGH)


Serial.println("The sensor is touched");

// save the the last state


lastState = currentState;
}

RESULT
Successfully executed Touch Sensor interfacing and feedback system.

Dept. of CS AI, MITS


AIL332 Robotics Lab Manual

EXPERIMENT 7
Line following Robot using IR sensor

AIM : To developed a Line following Robot using IR sensor

Requirements :

● Arduino Board (UNO)


● USB –A to micro-USB cable
● Car chassis
● L298 motor driver module
● IR sensor module
● 12V Battery
● On-Off- Switch
● DC Female Connector Jack
● Connecting wires
● Soldering iron
● Solder wire
● Hot Melt Glue Gun

THEORY:-

The concept of the line follower robot is related to the transmitting and receiving of light. The white
colour reflects all the light that falls on it whereas the black colour absorbs all the light.In this line
follower robot, we have used IR transmitters and receivers ( also known as photodiodes). When IR light
falls on a white surface, it gets reflected back towards the IR receiver, generating some voltage changes
that are analyzed by the Arduino.When IR light falls on a black surface, it gets absorbed by the black
surface, and no rays are reflected back thus, the IR receiver doesn’t receive any rays.In this project, when
the IR sensor senses a white surface, an Arduino gets HIGH as input, and when it senses a black line, an
Arduino gets LOW as input. Based on these inputs, an Arduino Uno provides the proper output to control
the line follower.

PROGRAMS

#define MOTOR_SPEED 60

int mot1=9;

int mot2=6;

int mot3=5;

int mot4=3;

int left=13;

int right=12;

Dept. of CS AI, MITS


AIL332 Robotics Lab Manual

int Left=0;

int Right=0;

void LEFT (void);

void RIGHT (void);

void STOP (void);

void setup() {

pinMode(mot1,OUTPUT);

pinMode(mot2,OUTPUT);

pinMode(mot3,OUTPUT);

pinMode(mot4,OUTPUT);

pinMode(left,INPUT);

pinMode(right,INPUT);

digitalWrite(left,HIGH);

digitalWrite(right,HIGH);

void loop() {

analogWrite(mot1,MOTOR_SPEED);

analogWrite(mot2,0);

analogWrite(mot3,MOTOR_SPEED);

analogWrite(mot4,0);

while(1) {

Left=digitalRead(left);

Right=digitalRead(right);

Dept. of CS AI, MITS


AIL332 Robotics Lab Manual

if((Left==0 && Right==1)==1)

LEFT();

else if((Right==0 && Left==1)==1)

RIGHT();

void LEFT (void) {

analogWrite(mot3,0);

analogWrite(mot4,30);

while(Left==0) {

Left=digitalRead(left);

Right=digitalRead(right);

if(Right==0) {

int lprev=Left;

int rprev=Right;

STOP();

while(((lprev==Left)&&(rprev==Right))==1) {

Left=digitalRead(left);

Right=digitalRead(right);

analogWrite(mot1,MOTOR_SPEED);

analogWrite(mot2,0);

Dept. of CS AI, MITS


AIL332 Robotics Lab Manual

analogWrite(mot3,MOTOR_SPEED);

analogWrite(mot4,0);

void RIGHT (void) {

analogWrite(mot1,0);

analogWrite(mot2,30);

while(Right==0) {

Left=digitalRead(left);

Right=digitalRead(right);

if(Left==0) {

int lprev=Left;

int rprev=Right;

STOP();

while(((lprev==Left)&&(rprev==Right))==1) {

Left=digitalRead(left);

Right=digitalRead(right);

analogWrite(mot3,MOTOR_SPEED);

analogWrite(mot4,0);

analogWrite(mot1,MOTOR_SPEED);

Dept. of CS AI, MITS


AIL332 Robotics Lab Manual

analogWrite(mot2,0);

void STOP (void) {

analogWrite(mot1,0);

analogWrite(mot2,0);

analogWrite(mot3,0);

analogWrite(mot4,0);

RESULT
Successfully developed a Line following Robot using IR sensor.

Dept. of CS AI, MITS


AIL332 Robotics Lab Manual

EXPERIMENT 8
Object detection using any one standard algorithm
AIM : To implement any one standard object detection algorithm

Requirements : A computer with Python programming software

THEORY:-

Object Detection Using Sobel Edge Detector

Object detection is the task of finding and identifying objects in an image. Humans recognize a
multitude of objects in images with little effort, despite the fact that the image of the objects may
vary somewhat in different viewpoints and sizes. Shape is not only, but the most powerful
descriptor of image content. Shape is probably the most important property that is perceived
about objects. It allows predicting more facts about an object than other features, e.g. coloring.
Thus, recognizing shape is crucial for object recognition. Different types of edge detection
techniques are available. Canny-edge detection and sobel-edge detection are most common edge
detection techniques. In Sobel edge detector, the task of edge detection is fulfilled by performing
a 2D spatial gradient convolution operation on an image. This operator uses two convolution
masks Gx and Gy as given below.

Here, Gx and Gy are computed as,

Gx = -1z1+1z3-2z4+2z6-1z7+1z9

Gy = 1z1+2z2+1z3-1z7-2z8-1z9

Where Zi, i=1,2….9 are intensity levels of each pixel in the convolution window shown in fig

Dept. of CS AI, MITS


AIL332 Robotics Lab Manual

Sobel operator is a very simple and effective way for finding the edges in an image. The sobel
operator is used mostly for detecting horizontal and vertical edges.

PROGRAMS

import cv2
img = cv2.imread('E:\images\sss.png')
cv2.imshow('sss',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
B, G, R = cv2.split(img)

cv2.imshow("blue", B)
cv2.waitKey(0)

cv2.imshow("Green", G)
cv2.waitKey(0)

cv2.imshow("red", R)
cv2.waitKey(0)

# Converts to Gray color space


grayImg = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# Converts to HSV color space


hsvImage = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

# Converts to YCrCb color space


YCRImage = cv2.cvtColor(img, cv2.COLOR_BGR2YCrCb)

# Converts to LAB color space


LabImage = cv2.cvtColor(img, cv2.COLOR_BGR2LAB)

#Edge Detction

#Sobel Edge xorder


sobelXedge = cv2.Sobel(img, cv2.CV_64F,1,0,ksize=5)

#SobelEEdge Yorder
sobelYedge = cv2.Sobel(img, cv2.CV_64F,0,1,ksize=5)

#Sobel EdgeXY
SobelXYedge = cv2.Sobel(img,cv2.CV_64F,1,1,ksize=5)

#Canny Edge
#edges = cv2.Canny(grayImg, threshold1=30, threshold2=100)
#edges1 = cv2.Canny(grayImg, threshold1=50, threshold2=150)
#edges2 = cv2.Canny(hsvImage, threshold1=70, threshold2=200)

Dept. of CS AI, MITS


AIL332 Robotics Lab Manual

cv2.imshow('Original image',img)
cv2.imshow('Gray image',grayImg)
cv2.imshow('HSV image', hsvImage)
cv2.imshow('YCR image', YCRImage)
cv2.imshow('LAB image', LabImage)

#cv2.imshow('Canny Edge-30-100' ,edges)


#cv2.imshow('Canny Edge-50-150' ,edges1)
#cv2.imshow('Canny Edge-70-200' ,edges2)
cv2.imshow('Sobel X-Order Edge' ,sobelXedge)
cv2.imshow('Sobel Y-Order Edge' ,sobelYedge)
cv2.imshow('Sobel XY Order Edge' ,SobelXYedge)

cv2.waitKey(0)
cv2.destroyAllWindows()

RESULT
Successfully implemented a standard object detection algorithm.

Dept. of CS AI, MITS

You might also like