Anda di halaman 1dari 125

DE-29 (DEE) YEAR 2011

NUST COLLEGE OF ELECTRICAL AND MECHANICAL ENGINEERING

CONTROL AND AUTOMATION OF SCARA (SELECTIVE COMPLIANT ASSEMBLY ROBOTIC ARM)


A PROJECT REPORT DE-29 (DEE)

Submitted by

NS AHMED HASSAN SYAN NS S.M. DANIAL HAIDER NS MUHAMMAD ZAIN NS S.M. ZOHAIB ABBAS
BACHELORS IN ELECTRICAL ENGINEERING 2011

PROJECT SUPERVISOR DR FAHAD MUMTAZ

COLLEGE OF ELECTRICAL AND MECHANICAL ENGINEERING PESHAWAR ROAD, RAWALPINDI

CONTROL AND AUTOMATION OF SCARA (SELECTIVE COMPLIANT ASSEMBLY ROBOTIC ARM)


A PROJECT REPORT DEGREE 29 (DEE)

Submitted by

NS AHMED HASSAN SYAN NS S.M. DANIAL HAIDER NS MUHAMMAD ZAIN NS S.M. ZOHAIB ABBAS
BACHELORS IN ELECTRICAL ENGINEERING

Year 2011
PROJECT SUPERVISOR DR. FAHAD MUMTAZ

COLLEGE OF ELECTRICAL AND MECHANICAL ENGINEERING PESHAWAR ROAD, RAWALPINDI

NUST COLLEGE OF ELECTRICAL AND MECHANICAL ENGINEERING

CONTROL AND AUTOMATION OF SCARA (SELECTIVE COMPLIANT ASSEMBLY ROBOTIC ARM)


Submitted by:
NS AHMED HASSAN SYAN NS S.M. DANIAL HAIDER NS MUHAMMAD ZAIN NS S.M. ZOHAIB ABBAS 2008-NUST-BE-ELEC-26 2008-NUST-BE-ELEC-64 2008-NUST-BE-ELEC-53 2008-NUST-BE-ELEC-67

Project Supervisor:

______________________
Dr. Fahad Mumtaz

Date:____________

Head of Department:

______________________
Dr. Mojeeb Bin Ihsan

Date:____________

DEPARTMENT OF ELECTRICAL ENGINEERING COLLEGE OF ELECTRICAL AND MECHANICAL ENGINEERING PESHAWAR ROAD, RAWALPINDI

Page 2 of 124

DECLARATION
We hereby declare that no portion of the work referred to in this Project Thesis has been submitted in support of an application for another degree or qualification of this of any other university or other institute of learning. If any act of plagiarism found, we are fully responsible for every disciplinary action taken against us depending upon the seriousness of the proven offence, even the cancellation of our degree.

COPYRIGHT STATEMENT
Copyright in text of this thesis rests with the Ahmed Hassan, Danial Haider, Muhammad Zain and Zohaib Abbas. Copies (by any process) either in full, or of extracts, may be made only in accordance with instructions given by the author and lodged in the Library of NUST College of E&ME. Details may be obtained by the Librarian. This page must form part of any such copies made. Further copies (by any process) of copies made in accordance with such instructions may not be made without the permission (in writing) of the author. The ownership of any intellectual property rights which may be described in this thesis is vested in NUST College of E&ME, subject to any prior agreement to the contrary, and may not be made available for use by third parties without the written permission of the College of E&ME, which will prescribe the terms and conditions of any such agreement. Further information on the conditions under which disclosures and exploitation may take place is available from the Library of NUST College of E&ME, Rawalpindi.

Page 3 of 124

ACKNOWLEDGEMENTS
We are thankful to Allah Almighty for enabling us to achieve our goals. We are thankful to our parents, for their constant support, guidance and affection. We are grateful to our Electrical Department and its members for supporting us in completing this project. We are really indebted to our project supervisor, Dr. Fahad Mumtaz, for his generous and kind support and valuable guidance. We are also thankful to Dr. Khalid Munawar, for his encouragement, support and help during the implementation of this project. We are also thankful to all our friends, especially Hassaan Saadat and Sohaib Afzal, for helping us completing this project.

Page 4 of 124

ABSTRACT
This project deals with the control and automation of SCARA robotic arm, which is widely used for industrial automation throughout the globe. It is capable performing several tasks in an industry. We have specifically designed it for automated drilling of a given PCB. The project is an amalgam of microcontroller hardware, control systems, DSP and computer networks. The final project takes a Gerber file/PCB layout from the user, applies image processing techniques on it to get the coordinates of the holes, applies inverse kinematics technique on them to get the angles for movement of the arms of the robot, and sends these angles to the microcontroller through serial communication. There the controller accordingly moves both the arms by driving the motors through H-bridges. PID control has been implemented for position control. Once the end effector has precisely reached the spot of drilling, a third motor moves the drill up and down to drill the hole.

Page 5 of 124

TABLE OF CONTENTS
Chapter no. Title Declaration and Copyright Certificate Acknowledgements Abstract Table of Contents List of Figures List of Tables Chapter 1 Introduction 1.1 1.2 1.3 1.4 1.5 What is a Robot? Industrial Applications of Robots What is SCARA? Comparison of SCARA with other Cartesian Robots Industrial Applications of SCARA Chapter 2 Mechanical Structure of SCARA 2.1 2.2 2.3 2.4 2.5 2.6 Links Joints Degree of Freedom End Effector Dimensions of the Structure Motors Chapter 3 Control of SCARA 3.1 3.2 3.3 3.4 3.4.1 3.4.2 3.4.3 Encoder Resolutions and Relations H-bridge Design System Identification PID Realization General PID Controller Zeigler-Nichols Tuning PID of our System 18 19 21 24 24 26 29 14 15 16 16 16 17 11 11 12 12 12 Page no. 3 4 5 6 8 10

Page 6 of 124

3.5

Software Simulations, Circuit Diagrams and PCB Layouts Chapter 4 Automation of SCARA

33

4.1 4.2 4.3 4.4 4.5 4.6 4.7 4.8

Interactive GUI Gerber File Processing Image Processing Scaling Transformation Inverse Kinematics Serial Communication Remote access over the internet Chapter 5 Summary/Limitations

42 68 70 75 76 77 81 88

5.1 5.2

Summary Limitations Chapter 6 Recommendations for Future Work Appendix

96 96 97

98

Page 7 of 124

LIST OF FIGURES
Sr. no. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 Figure no. 2.1 2.2 2.3 3.1 3.2 3.3 3.4 3.5 3.6 3.7 3.8 3.9 3.10 3.11 3.12 3.13 3.14 3.15 3.16 3.17 3.18 3.19 3.20 3.21 3.22 4.1 4.2 4.3 4.4 Title (a) Unary Link, (b) Binary Link, (c) Ternary Link Side view of SCARA Top view of SCARA Circuit diagram of H-bridge PCB Layout of the H-bridge Fully fabricated H-bridge Full open-loop block diagram Simplified open-loop block diagram Block diagram of parallel form of PID Step response of PI controller Ramp response of PD controller Response Curve for Zeigler-Nichols First Method Example system Step Response for a System tuned via Second Method SISO design tool toolbox PID implementation in Simulink (step input) Step response for PID implementation in Simulink PID implementation in Simulink (ramp input) Ramp response for PID implementation in Simulink PID implementation in Simulink (sinusoidal input) Sinusoid response for PID implementation in Simulink PCB layout of the first board PCB layout of the second board Proteus simulation of the first board Combined simulation of first and second board GUI layout Completed GUI Selecting a file from the hard drive Finding coordinates (a) from an image file (b) from a gerber file Page 8 of 124 Page no. 14 14 15 19 20 21 21 22 24 25 25 27 28 29 30 30 31 31 32 32 33 34 34 35 41 42 43 43 44

30 31 32 33 34 35 36 37 38 39

4.5 4.6 4.7 4.8 4.9 4.10 4.11 4.12 4.13 4.14

Finding the angles Transmitting angles to the controller Viewing coordinates and angles for a specific point PCB Layout PCB Layout with a white border around it Dilated image Image obtained after XORing Scatter plot of the coordinates Relation between the no. of pixels and distance in cms Scatter plot of the coordinates after scaling and transformation

44 45 45 70 70 71 72 72 75 76

40 41 42 43 44

4.15 4.16 4.17 4.18 4.19

Top view of SCARA Top view of SCARA showing the dimensions Top view of SCARA showing the dimensions Detailed dimensions of the top view Detailed dimensions of top view with bold right triangle

77 77 79 80 81

45 46 47 48

4.20 4.21 4.22 4.23

DB9 male and female connectors Schematic diagram of MAX-232 USB to serial converter with its cable Proteus simulation of serial communication with PIC18F452

82 83 84 87

49 50 51 52

4.24 4.25 4.26 4.27

PCB layout of serial communication board Fully fabricated serial communication board Website Entering data in the website

88 88 89 89

Page 9 of 124

LIST OF TABLES
Sr. no. 1 2 3 4 5 6 Table no. 3.1 3.2 3.3 3.4 4.1 4.2 Title Truth table of the effect of W1 and W2 on motor Experimental values of K and m Zeigler-Nichols Recipe First Method Zeigler Nichols Recipe Second Method Pin outs and pin functions of DB9 Transition table of RS-232 voltages and MAX-232 voltages 7 4.3 Parameter values of serial communication 84 Page no. 20 23 26 27 82 83

Page 10 of 124

SCARA

Chapter 1 : Introduction

Chapter 1: INTRODUCTION

1.1

What is a Robot?
A robot is re-programmable, multipurpose, electromechanical machine which is

capable of performing a variety of tasks on its own, or with some human or computer guidance. It is usually automated to perform a specific task, which is normally ascribed to humans. Some robots are also used for research into human-like systems, such as ASIMO and TOPIO.

1.2

Industrial Applications of Robots


An industrial robot is defined by ISO as an automatically controlled,

reprogrammable, multipurpose manipulator programmable in three or more axes. The use of robots in industry commenced in the 1960s. Today, about 90% of the robots work in industries and factories. They can perform critical tasks with greater accuracy, more speed, and more efficiency as compared to humans. Rapid improvements are also being made to make them more and more efficient. Some typical industrial applications of robots are: a) Welding applications b) Milling and drilling applications c) Painting applications d) Pick and place applications e) Assembly operations f) Packaging and palletizing g) Material handling h) Dispensing operations i) Screwing, wiring and fastening j) Laboratory applications k) Water jet cutting l) Product inspection and testing

Page 11 of 124

SCARA

Chapter 1 : Introduction

1.3

What is SCARA?
SCARA is an acronym for Selected Compliant Assembly Robotic Arm.

Sometimes the term Articulated is also used instead of Assembly. By virtue of the SCARA's parallel-axis joint layout, the arm is slightly compliant in the X-Y direction but rigid in the Z direction, hence the term Selective Compliant is used. This is advantageous for many types of assembly operations, i.e., inserting a round pin in a round hole without binding. The second attribute of the SCARA is the jointed two-link arm layout similar to our human arms, hence the often-used term, Articulated. This feature allows the arm to extend into confined areas and then retract or fold up out of the way. This is advantageous for transferring parts from one cell to another or for loading/unloading process stations that are enclosed.

1.4

Comparison of SCARA with other Cartesian Robots


SCARA has many advantages over the normal Cartesian robots. The most useful

feature is their high speed. They are about two times faster than the Cartesian system robots. Their standard cycle time is also about 20% less than the conventional robots. Furthermore, since their footprint is very small, they require very less area to mount. Their small base projection area and height also allow freedom in system design. They provide absolute feedback, which eliminates the need for returning to the origin again and again. On the other hand, SCARA robots are much expensive as compared to other robots. But considering all the advantages discussed above, cost is a fair tradeoff in this case.

1.5

Industrial Applications of SCARA


SCARA was invented in 1960s, in Japan, and since then it has found several

different applications in the industry. Today, many different variants of SCARA are available in the market, which serve different applications. Some of the applications of SCARA are: Pick and place Page 12 of 124

SCARA Packaging Automated drilling Automated welding Mechanical assembly Material handling Screw driving

Chapter 1 : Introduction

Now, in this project, we have first controlled SCARA and then specifically automated it for automated drilling of PCBs.

Page 13 of 124

SCARA

Chapter 2 : Mechanical Structure of SCARA

Chapter 2: MECHANICAL STRUCTURE OF SCARA

2.1

Links
A link can be formally defined as A rigid body with at least one particular point,

called a node, which supports the attachment of the link with other link. According to the number of nodes each link possesses, we can divide the links into 3 common categories: Unary Link: A link with a single node. Binary Link: A link with two nodes. Ternary Link: A link with three nodes.

(a)

(b)

(c)

Figure 2.1: (a) Unary Link, (b) Binary Link, (c) Ternary Link SCARA has four links as shown in the side view of SCARA below. Link - 1 and Link - 2 are binary links, whereas Link - 3 and Link - 4 are unary links.

Link - 2 Link - 3

Link - 1

End effector

Link - 4 Figure 2.2: Side view of SCARA Page 14 of 124

SCARA

Chapter 2 : Mechanical Structure of SCARA

2.2

Joints
A joint can be formally defined as The connection between two or more links at

their nodes. It constrains the motions of the connected links. If a joint connects only two links, the entity is also called a kinematic pair. Depending on the degrees of freedom (DOF) allowed for the kinematic pair, a joint can be classified as: one-DOF joint, twoDOF joint, three-DOF joint etc. In robotics, for the simplicity of kinematic and dynamic analysis, we use one-DOF joints because any joint with a higher order of DOFs can easily be treated as the combination of multiple one-DOF joints. In a kinematic pair, one degree of freedom (DOF) needs one independent parameter, which uniquely determines the relative geometry (position and/or orientation) of the two links in the kinematic pair. In three-dimensional space, any complex motion with respect to a reference coordinate system can be treated as the combination of two basic motions: translation and rotation. Therefore, if a joint imposes a translational motion, it is called a prismatic joint. If the constrained motion is rotational, it is called a revolute joint. SCARA has three joints: Two revolute joints; one each for rotating the link - 2 and the link - 3 One prismatic joint; for moving the end effector up and down along the z-axis The top view of SCARA is shown below. The joints have been labeled.

Prismatic Joint

Revolute Joints Figure 2.3: Top view of SCARA

Page 15 of 124

SCARA

Chapter 2 : Mechanical Structure of SCARA

2.3

Degree of Freedom
Degree of freedom (DOF) can be formally defined as The number of

independently controllable motions in a mechanical device. Generally speaking, a mechanical system's degrees of freedom refer to the number of independent parameters, which uniquely determine its geometry (or configuration) in space and time. Now although SCARA has three joints, and three motors to control these joints, but it Degree of Freedom is FOUR. It is considered as a specialty of SCARA. It is a 4DOF device because it covers all three dimensions (x,y,z) and also one angle (the angle between x and y).

2.4

End Effector
End Effector can be formally defined as An attachment at the end of a robot that

interacts with the environment. It is the last link or the end of the robot/robotic arm. It has to perform the operation for which the robot was built, such as a claw for pick and place. Since we have automated our robot for automated drilling of PCBs, so we attached a PCB drill to it as the end effector. It is a normal drill that operates on 12V DC. Separate adaptor was used to provide power to this drill.

2.5

Dimensions of the Structure


The base (Link - 4) and the Link - 1 of SCARA are made up of steel for strength.

Whereas the Link - 2 and the Link - 3 are made up of aluminum alloy for less weight. This increases speed, and also avoids the danger of falling on one side. The dimensions are given below: The base or the Link - 4 is 5cm high and 50x50cms in dimensions The Link - 1 is 50x16.8x16.8cms. The thickness of the walls of two sides is 0.4cm each, whereas that of the other two sides is 0.1cm each. The Link - 2 is 52.8cm long, 10cm high, and 10cm wide. The thickness of the walls is 0.4cm. The internal radius of the side curves is 5cm. The Link - 3 is 31.8cm long, 10cm high, and 10cm wide. The thickness of the walls is 0.4cm. The internal radius of the side curves is 5cm. Page 16 of 124

SCARA

Chapter 2 : Mechanical Structure of SCARA

2.6

Motors
Six motors have been used in the project. However, only three of them are

actually being used for moving the joints. The other three are being used to get the feedback. We have used, Two wiper motors, one each for rotating the Link - 2 and the Link - 3, about their respective revolute joints. One power window motor, at the prismatic joint, for moving the end effector up and down. Three servo motors, one at each joint, for taking the feedback. Separate encoders were not available in the market, so we had to buy these three servo motors which had optical encoders in them. The power pins of the servo motors were disconnected at all times. Only the encoder was given power, and its feedback was used.

Page 17 of 124

SCARA

Chapter 3 : Control of SCARA

Chapter 3: CONTROL OF SCARA

3.1

Encoder Resolutions and Relations


A rotary encoder, also called a shaft encoder, is an electro-mechanical device that

converts the angular position or motion of a shaft or axle to an analog or digital code. The output of incremental encoders provides information about the motion of the shaft which is typically further processed elsewhere into information such as speed, distance, RPM and position. The output of absolute encoders indicates the current position of the shaft, making them angle transducers. Rotary encoders are used in many applications that require precise shaft unlimited rotation - including industrial controls, robotics, special purpose photographic lenses, computer input devices (such as optomechanical mice and trackballs), and rotating radar platforms. There are two main types: Absolute Incremental (Relative). As discussed earlier, optical encoders were not available in the market. So we bought servo motors instead, which already had encoders in them. The resolution of these encoders was found to be: Encoder - 1: 286 Encoder - 2: 100 Encoder - 3: 286 After studying the gears and belts of the joints, we found out the relations between the degrees the arm turns and the number of pulses the encoder gives as feedback. Since the third motor moves the end effector up and down, so we measured its encoders relation in terms of centimeters moved and the number of pulses received correspondingly. The relations are: Encoder - 1: 1 degree = 4 pulses Encoder - 2: 1 degree = 1.5 pulses Encoder - 3: 1 cm = 1410 pulses

Page 18 of 124

SCARA

Chapter 3 : Control of SCARA

3.2

H-bridge Design
The name H-Bridge is derived from the actual shape of the switching circuit

which controls the motion of the motor. It is also known as Full Bridge. Basically there are four switching elements in any H-Bridge design. When these switches are turned on in pairs motor changes its direction accordingly. This attribute can be used to rotate the motor in either direction, and also to control its speed. Now the normal H-bridge ICs available in the market had a low current rating, which did not fulfill our requirements. So we had to design and fabricate our own Hbridges for driving the motors. The H-bridge we designed works with the help of TIP122 and TIP127 power transistors, and is capable of supporting current upto 5 Amperes. It proved to be very versatile and robust. It only requires four wires for 12V power supply and direction control. And it allows bidirectional control, breaking and freewheeling. The schematic is shown below. It consists of only two logic ICs and a bunch of transistors.

Figure 3.1: Circuit diagram of H-bridge

Page 19 of 124

SCARA

Chapter 3 : Control of SCARA

Q1, Q2, Q3 and Q4 are all 2N2222 BJTs. Any generic switching transistor can be used instead of them. In order to support high current, the resistors R2, R4, R5 and R10 we used were 1W rated. The wires W1 to W4 are for power supply and the logic signals for controlling the control. The wires W1 and W2 connected to the microcontroller for controlling the motor. The table below shows the effect of different combinations of the wires W1 and W2: Table 3.1: Truth table of the effect of W1 and W2 on motor Inputs W1 0 0 1 1 Where, 1 = Logic high = 5V 0 = Logic low = 0V The diodes D2 to D4 that are shown in the schematic diagram are simple rectifier diodes, with the forward current rating of 4A. The LED D1 lights up when there is power in the circuit. The PCB layout of the H-bridge is shown below: W2 0 1 0 1 Motor will be freewheeling Motor will turn clockwise Motor will turn anti-clockwise Motor will break Effect on motor

Figure 3.2: PCB Layout of the H-bridge Page 20 of 124

SCARA

Chapter 3 : Control of SCARA

The fully fabricated PCB came out to be just about 5cm x 5cm in dimension, and is shown below:

Figure 3.3: Fully fabricated H-bridge

3.3

System Identification
The power window and wiper motors attached to the links were old Nissan

motors. No datasheet came along with them; neither could we find one on the internet. So we had to manually find the transfer functions of all the motors/links. We used the least-squares solution to identify the discrete open-loop transfer functions of these motors. We used MATLAB for this procedure. We took the first motor and followed the following steps: 1. Suppose that the open loop block diagram of the system is: DC Motor (Position) u(kT) u(t) PWM Velocity Approximation z1 Tz Vel(kT)

ENC(t) s(m s + 1)

Figure 3.4: Full open-loop block diagram Since the motor has only angular feedback (optical encoder), so we approximated its velocity with the backwards difference rule.

Page 21 of 124

SCARA

Chapter 3 : Control of SCARA

2. Suppose that the simplified block diagram of the system is: DC Motor (Velocity) u(t) Vel(t) m s + 1

Vel(kT) ZOH

PWM

Figure 3.5: Simplified open-loop block diagram Here we assumed that our velocity approximation is exact and cancels the integrator in Figure 3.4s motor position transfer function. This helped simplify the identification but still allowed us to identify K and m. 3. In general, we carefully applied chosen inputs and measured the plant output(s). In our case, the model was quite simple and we found that a step input worked very well. Using Figure 3.5 as a guide, we derived the discrete transfer function by assuming a zero-order hold (ZOH) and taking the z-transform of the continuous system: ( ) ( ) Then, ( ) ( ) ( T) where, [1 ] and , we had to apply an [1 ( T T) + ] (1 ) { 1 ( ) } ( )

and the corresponding difference equation came out to be ( T T) ..(A)

and

4. In order to identify these two model parameters,

open-loop step input to the motor and stored the motors velocity response in an array. So we created a DSP application that outputs a constant step value to the motor. This application also sampled the optical encoder of the DC motor and used the radian values to estimate the speed of the motor in units of radians/second. 5. For the first two seconds of our run, we stored both the output value and the velocity value in separate arrays.

Page 22 of 124

SCARA

Chapter 3 : Control of SCARA

6. In MATLAB, we used the function C6X_getvar to upload our data to MATLABs workspace. Then we saved the runs data to a unique *.mat file so that we could use it later. 7. Then we plotted the motors response. From the plot, we found the value for K. Using the 63% rule, we also found an approximate value for m. 8. Using equation (A), and starting with k = 2 and ending with k = 2000, we compiled the data into 1999 equations that were a function of ( ) ( ) ( ) 9. Then we solved them for and and m using the equations for (1) + ( )+ ( 1) + (1) ( ) ( 1) and . i.e.:

by least-squares regression. And solved for K and . The value we recorded for and

were precise upto six decimal places. 10. Then we repeated the experiment three times, and took mean values. The values of K and m are shown below: Table 3.2: Experimental values of K and m K 1. 2. 3. 4. Mean: 0.3013 0.2373 0.2801 0.2659 0.27115

m
0.1578 0.2190 0.1831 0.2304 0.1975

11. Then we simply found the transfer function of the motor using the formula: + and it came out to be +

Page 23 of 124

SCARA

Chapter 3 : Control of SCARA

12. Similarly, we repeated the procedure for the other two motors. And their transfer functions came out to be, T and, 1 + respectively. 1 1 s+

3.4

PID Realization

3.4.1 General PID Controller


PID controllers are the most commonly used controller structures in industry. They do, however, present some challenges to control and instrumentation engineers in the aspect of tuning of the gains required for stability and good transient performance. One is that proposed by Ziegler and Nichols in the 1940's. The PID controller encapsulates three of the most important controller structures in a single package. The parallel form of a PID controller is shown below: (s) Kp + s + s

E(s)

Kds
Ki /s

U(s)

Figure 3.6: Block diagram of parallel form of PID Where, Kp = Proportional gain Kd = Derivative gain Ki = Integral gain The proportional gain helps us in establishing system stability and improving the transient response of the system, while the derivative gain is used when it is necessary to Page 24 of 124

SCARA

Chapter 3 : Control of SCARA

improve the closed loop response speed even further. Conceptually the effect of the derivative term is to feed information on the rate of change of the measured variable into the controller action. The most important term in the controller is the integrator gain that introduces a pole at s = 0 in the forward loop of the process. This makes the compensated open loop system (i.e. original system plus PID controller) a type 1 system at least; our knowledge of steady state errors tells us that such systems are required for perfect steady state set point tracking. In other words, for a unity feedback system, the perfect set point control can be achieved for the controller, C(s), if and only if 1. The open loop forward gain has a steady state gain of infinity i.e. (s) (s) 2. The system is closed loop stable. 3. Neither C(s) nor G(s) have zeros at the origin. The third point eliminates the possibility of the loop transfer function cancelling the effect of the integrator pole. The reset and rate times are of special significance in this regard:

The reset time is the time taken for the integrator term output to equal the proportional term output in response to a step change in input applied to a PI controller.

Figure 3.7: Step response of PI controller The rate time is the time taken for the proportional term output to equal the derivative term output in response to a ramp change input applied to a PD controller.

Figure 3.8: Ramp response of PD controller Page 25 of 124

SCARA

Chapter 3 : Control of SCARA

3.4.2 Ziegler-Nichols Tuning


In 1942 Ziegler and Nichols, both employees of Taylor Instruments, described two mathematical procedures, for the tuning of PID controllers. These procedures are now accepted as standard in control systems practice. Both techniques make a priori assumptions on the system model, but do not require that these models be specifically known. Ziegler-Nichols formulae for specifying the controllers are based on plant step responses. The First Method: The first method is applied to plants with step responses of the form displayed in Figure 4. This type of response is typical of a first order system with transportation delay, such as that induced by fluid flow from a tank along a pipe line. It is also typical of a plant made up of a series of first order systems. The response is characterised by two parameters, the delay time L, and the time constant T. These are found by drawing a tangent to the step response at its point of inflection and noting its intersections with the time axis and the steady state value. The plant model is therefore (s) Ts + 1

Zeigler and Nichols derived the following control parameters based on this model: Table 3.3: Zeigler-Nichols Recipe First Method PID Type P PI PID 1 Kp T T T 2L Ti = Kp/Ki Td = Kd/Kp 0 0 0.5L

Page 26 of 124

SCARA

Chapter 3 : Control of SCARA

Figure 3.9: Response Curve for Zeigler-Nichols First Method It can be noted that the response curve shown above is similar to that of the over damped second order systems. The Second Method: The second method is usually used for the plants that can be rendered unstable under proportional control. The technique is designed to result in a closed loop system with 25% overshoot. This is rarely achieved as Ziegler and Nichols determined the adjustments based on a specific plant model. The steps for tuning a PID controller via the 2nd method are as follows: Using only proportional feedback control: 1. Reduce the integrator and derivative gains to 0. 2. Increase Kp from 0 to some critical value Kcr, at which sustained oscillations occur. If they do not, then another method has to be applied. 3. Note the value of Kcr, and also the corresponding period of sustained oscillation, Pcr. The controller gains are now specified as follows: Table 3.4: Zeigler Nichols Recipe Second Method PID Type P PI PID Kp 0.5Kcr 0.45Kcr 1 0.6Kcr Ti Td 0 0

Page 27 of 124

SCARA Consider a process with transfer function (s)

Chapter 3 : Control of SCARA that is to be

)(

)(

placed under PID control. We can determine the limiting gain for stability (before oscillation) by using Routh-Hurwitz condition. The characteristic equation p(s), with proportional control is: E(s) R(s)
+

U(s) K G(s) Y(s)

Figure 3.10: Example system 1 + KG(s) = 0 (s+1)(s+3)(s+5) + K = 0 p(s) = s3 + 9s2 + 23s +15 + K = 0 The corresponding Routh array is s3 s2 s1 s0 1 9 192 K 15 + K 23 15 + K 0 0 0

From this we see that the range of K for stability is 15 + K > 0 K > 15 and 192 K > 0 K < 192. So, Kcr=192. When K = 192, we have imaginary roots since the s1 row is identically 0. The corresponding auxiliary equation is 9s2 + 15 + 192 = 0 which has roots at s = j4.8. Since this is a quadratic factor of the characteristic polynomial the sustained oscillation at the limiting value of K, Kcr, is at 4.8rad/s. Thus, Pcr = 1.31sec and Kcr = 192. This gives for full PID control from the table as Kp = 0.6Kcr = 115.2 Ki = 2Kp/Pcr = 177.2 and Kd = Kp Td = Kp/8 Pcr = 18.3 Page 28 of 124

SCARA

Chapter 3 : Control of SCARA

Analysis: The closed loop step response shows an overshoot performance of 50%, 100% over target. Given the dependence of the technique on a generic model, it is not surprising that the design objectives will almost always not be met. The technique, however, does provide an effective starting point for controller tuning.

Figure 3.11: Step Response for a System tuned via Second Method

3.4.3 PID of our System


We implemented PID control on our system using the Zeigler-Nichols Method in MATLAB. In MATLAB, there is a toolbox named SISO Design Tool. There in the tab of Automated Tuning, is the option of Zeigler-Nichols Tuning in the Tuning Algorithm drop down list. It automatically tuned our system.

Page 29 of 124

SCARA

Chapter 3 : Control of SCARA

Figure 3.12: SISO design tool toolbox After that, we implemented this PID controller on our system, in Simulink, in the MATLAB. We gave a step input to the system, and observed the corresponding output. It can be seen that the input is tracked to a very good level.

Figure 3.13: PID implementation in Simulink (step input) Page 30 of 124

SCARA

Chapter 3 : Control of SCARA

Figure 3.14: Step response for PID implementation in Simulink Then we also checked it for ramp and sinusoidal input. The following diagrams illustrate the results:

Figure 3.15: PID implementation in Simulink (ramp input)

Page 31 of 124

SCARA

Chapter 3 : Control of SCARA

Figure 3.16: Ramp response for PID implementation in Simulink

Figure 3.17: PID implementation in Simulink (sinusoidal input)

Page 32 of 124

SCARA

Chapter 3 : Control of SCARA

Figure 3.18: Sinusoid response for PID implementation in Simulink

3.5

Software Simulations, Circuit Diagrams and PCB Layouts


Apart from the three H-bridges, we designed and fabricated four other boards for

the microcontrollers, and serial communication between PC and the controllers. First we fabricated a board for normal H-bridges which were available in the market. But since they did not fulfill our requirements, we had to discard that board. Then we fabricated two other boards of a similar design for the microcontrollers. At the same time, we designed and fabricated a board for the serial communication. This board has been discussed in detail in the serial communication portion of this report, so we will not discuss it here. The PCB layouts of the first board that we had to discard later, as well as of the boards that we used are given on the next page.

Page 33 of 124

SCARA

Chapter 3 : Control of SCARA

Figure 3.19: PCB layout of the first board Since we had to discard this design, so we will not discuss it in detail here. The PCB layout of the other two boards that we used is:

Figure 3.20: PCB layout of the second board Page 34 of 124

SCARA

Chapter 3 : Control of SCARA

We fabricated two boards of this design, each for holding one of the microcontrollers. We also simulated it on Proteus first. The Proteus simulation diagram is shown below:

Figure 3.21: Proteus simulation of the first board And the code that we wrote for this simulation is given below:
LIST P=18F452 #include <P18F452.INC> CONFIG WDT=OFF; angle EQU 0x22 STOP EQU 0x22 MVALUE EQU 0x23 COMVALUE EQU 0x24 LCD_DATA EQU PORTD LCD_CTRL EQU PORTA RS EQU RA3 RW EQU RA2 EN EQU RA1 org 0x00 clrf PCLATH goto Main org 0x008 btfss INTCON,INT0IF to RB0 ;checking whether interrupt was due ;LCD data port ;LCD control port ;data/ instruction ;read/write ;enable of LCD

Page 35 of 124

SCARA
retfie goto INT0_ISR org 0x0100 Main st bsf TRISB,RB0 configuration bsf INTCON,INT0IE bsf INTCON,GIE call LCD_INITIAL call LCD_MOTOR_STOP condition) bcf TRISB,RB3 bcf TRISC,CCP1 for DC1B1:B0 bcf TRISB,RB2 bcf PORTB,2 BCF PORTB,3 BCF PORTC,2 BRA st input1 ;SPEED CONTROL ;INPUT2 FOR MOTOR

Chapter 3 : Control of SCARA

;INT0 external interrup ;INT0 interrupt enable ;global interrupt enable ;LCD initialization ;displaying data (for stop

;configuring as output for PWM,11

;-------------------------------------------------------------------org 0x400 INT0_ISR call LCD_INITIAL call LCD_MOTOR_ON MOVLW d'1410' MOVWF angle MOVF angle,W MULLW d'4' CALL TIMER1_COUNTER BCF PORTC,2 BSF PORTB,3 MOVF PRODH,W BACK CPFSEQ TMR1H BRA BACK MOVF PRODL,W BACK2 CPFSEQ TMR1L BRA BACK2 BCF PORTB,3 ; moving 4 cm ;LCD initialization ;displaying data (for ON condition) ; pulses for 1 cm approx

Page 36 of 124

SCARA
BCF PORTC,2

Chapter 3 : Control of SCARA

;*********************END OF FORWARD DIRECTION******** MOVLW d'1410' MOVWF angle MOVF angle,W MULLW d'4' CALL TIMER1_COUNTER BSF PORTC,2 BCF PORTB,3 MOVF PRODH,W BACK3 CPFSEQ TMR1H BRA BACK3 MOVF PRODL,W BACK4 CPFSEQ TMR1L BRA BACK4 BCF PORTB,3 BCF PORTC,2 CALL SERIAL_TRANSMIT bcf INTCON,INT0IF retfie ;----------------------------------------------------------------------delay_2_sec ;internal clock movlw 0x04 movwf T0CON bcf INTCON,TMR0IF movlw 0x0B movwf TMR0H movlw 0xDC movwf TMR0L bsf T0CON,TMR0ON tmr btfss INTCON,TMR0IF bra tmr bcf T0CON,TMR0ON bcf INTCON,TMR0IF RETURN ;creating 2 seconds delay using timer 0,no prescalar, ;CHANGE DIRECTION

Page 37 of 124

SCARA

Chapter 3 : Control of SCARA

;--------------------------------------------------------------------TIMER1_COUNTER MOVLW 0x02 MOVWF T1CON MOVLW 0x00 MOVWF TMR1L MOVLW 0X00 MOVWF TMR1H BSF T1CON,TMR1ON RETURN ;************************************************************** ;*****************SERIAL TRANSMIT****************** SERIAL_TRANSMIT MOVLW B'00100000' MOVWF TXSTA MOVLW D'12' MOVWF SPBRG BCF TRISC,TX BSF RCSTA,SPEN r2 MOVLW A'S' r1 BTFSS PIR1,TXIF BRA r1 MOVWF TXREG RETURN ;*********************************************************************** *** ;EL Cee Dee Ka Kam LCD_INITIAL MOVLW MOVWF ;port pins CLRF TRISA CLRF TRISD BCF PORTA,1 CALL LDELAY MOVLW 0X38 CALL COMD_WRT CALL DELAYLCD MOVLW 0X01 ;CLEAR DISPLAY ;INITIALIZE 2 LINES OF LCD, 5X7 MATRIX ;making output ;making output ;making enable low b'00001110' ADCON1 ;configuring ADCON1 for LCD operation to digitize ;4800 baud rate ;enable receive and serial port

Page 38 of 124

SCARA
CALL COMD_WRT CALL DELAYLCD MOVLW 0X0C CALL COMD_WRT CALL DELAYLCD MOVLW 0X80 CALL COMD_WRT CALL DELAYLCD return ;DISPLAY CURSOR

Chapter 3 : Control of SCARA

;BRING CURSOR TO BEGINNING OF LINE 1

;-----------------------------------------------------COMD_WRT MOVWF LCD_DATA BCF LCD_CTRL,RS BCF LCD_CTRL,RW BSF LCD_CTRL,EN CALL DELAYLCD BCF LCD_CTRL,EN RETURN DATA_WRT MOVWF LCD_DATA BSF LCD_CTRL,RS BCF LCD_CTRL,RW BSF LCD_CTRL,EN CALL DELAYLCD BCF LCD_CTRL,EN MOVLW 06H CALL COMD_WRT CALL DELAYLCD RETURN LDELAY MOVLW D'255' CALL DELAY2 CALL DELAY2 CALL DELAY2 CALL DELAY2 CALL DELAY2 CALL DELAY2 CALL DELAY2 CALL DELAY2 ;DISPLAYING DATA ON THE LCD ;GIVING COMMANDS TO THE LCD

Page 39 of 124

SCARA
CALL DELAY2 CALL DELAY2 RETURN DELAYLCD MOVLW D'10' CALL DELAY2 RETURN ;DELAY OF 0.5 MS DELAY MOVLW D'165' MOVWF STOP LOOP DECFSZ STOP,F GOTO LOOP RETURN ;DELAY = MULTIPLE OF 0.5 MS DELAY2 MOVWF MVALUE LOOP2 CALL DELAY DECFSZ MVALUE,F GOTO LOOP2 RETURN ;-----------------------------------------------;displaying "STOP" when MOTOR is stationary LCD_MOTOR_STOP movlw A'S' call DATA_WRT movlw A'T' call DATA_WRT movlw A'O' call DATA_WRT movlw A'P' call DATA_WRT return ;********************************************** ;displaying "DRILLING" when MOTOR is ON LCD_MOTOR_ON movlw A'D'

Chapter 3 : Control of SCARA

;GENERATING A DELAY OF 10ms FOR ISSUING NEW CHARACTERS

Page 40 of 124

SCARA
call DATA_WRT movlw A'R' call DATA_WRT movlw A'I' call DATA_WRT movlw A'L' call DATA_WRT movlw A'L' call DATA_WRT movlw A'I' call DATA_WRT movlw A'N' call DATA_WRT movlw A'G' call DATA_WRT return END

Chapter 3 : Control of SCARA

After simulating and testing this design, we also simulated the combined working of both the microcontrollers in Proteus. The simulation diagram is given below:

Figure 3.22: Combined simulation of first and second board

Page 41 of 124

SCARA

Chapter 4 : Automation of SCARA

Chapter 4: AUTOMATION OF SCARA

4.1

Interactive GUI
In the process of automating the SCARA Robot, we developed an interactive,

user-friendly Graphical User Interface using MATLAB. It has five push buttons: Open File - Opens the browser for user to select and open a Gerber File, or an image file containing the PCB layout Find Coordinates - Runs the image

Figure 4.1: GUI layout

Page 42 of 124

SCARA

Chapter 4 : Automation of SCARA

Figure 4.2: Completed GUI User can select and open any desired file from his/her hard drive. It can accept either a Gerber File, which is generated by the PCB designing software being used, or it can accept any type of image file (.jpg, .png, .bmp etc.) containing the PCB layout. In both these cases, the coordinates of the holes to be drilled in the PCB are calculated using image processing techniques.

Figure 4.3: Selecting a file from the hard drive Page 43 of 124

SCARA

Chapter 4 : Automation of SCARA

(a)

(b)

Figure 4.4: Finding coordinates (a) from an image file (b) from a gerber file After that, it finds the angles to be transmitted, using inverse kinematics technique, and then transmits those angles to the controller through serial communication.

Figure 4.5: Finding the angles

Page 44 of 124

SCARA

Chapter 4 : Automation of SCARA

Figure 4.6: Transmitting angles to the controller We can also select any specific point from the scatter plot and view its respective coordinates, and angles.

Figure 4.7: Viewing coordinates and angles for a specific point

Page 45 of 124

SCARA The MATLAB code for this GUI is given below:


function varargout = testing(varargin) % TESTING M-file for testing.fig % % % % % % % % % % the % % % % % % one % % % See also: GUIDE, GUIDATA, GUIHANDLES instance to run (singleton)". *See GUI Options on GUIDE's Tools menu. existing singleton*.

Chapter 4 : Automation of SCARA

TESTING, by itself, creates a new TESTING or raises the existing singleton*. H = TESTING returns the handle to a new TESTING or the handle to the existing singleton*. TESTING('CALLBACK',hObject,eventData,handles,...) calls the local function named CALLBACK in TESTING.M with the given input

arguments. TESTING('Property','Value',...) creates a new TESTING or raises Starting from the left, property value An

pairs are applied to the GUI before testing_OpeningFcn gets called. unrecognized property name or invalid value makes property stop. All inputs are passed to testing_OpeningFcn via varargin. Choose "GUI allows only

application

% Edit the above text to modify the response to help testing

% Last Modified by GUIDE v2.5 29-May-2011 18:26:21

% Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', 'gui_Singleton', 'gui_OutputFcn', 'gui_LayoutFcn', 'gui_Callback', mfilename, ... gui_Singleton, ... @testing_OutputFcn, ... [] , ... []);

'gui_OpeningFcn', @testing_OpeningFcn, ...

Page 46 of 124

SCARA
if nargin && ischar(varargin{1})

Chapter 4 : Automation of SCARA

gui_State.gui_Callback = str2func(varargin{1}); end

if nargout [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:}); else gui_mainfcn(gui_State, varargin{:}); end % End initialization code - DO NOT EDIT

% --- Executes just before testing is made visible. function testing_OpeningFcn(hObject, eventdata, handles, varargin) clc; guidata(hObject,handles); handles.err = wavread ('error.wav'); handles.tada = wavread ('tada.wav'); handles.first = 0; handles.gerber_chk = 0; filename = 'new.jpg'; %str = strcat(PathName,FileName); I = imread (filename);

guidata(hObject,handles); axes (handles.axes1) imshow(I); % This function has no output args, see OutputFcn. % hObject % eventdata % handles % varargin handle to figure reserved - to be defined in a future version of MATLAB structure with handles and user data (see GUIDATA) command line arguments to testing (see VARARGIN)

% Choose default command line output for testing handles.output = hObject;

% Update handles structure guidata(hObject, handles);

% UIWAIT makes testing wait for user response (see UIRESUME) % uiwait(handles.figure1);

Page 47 of 124

SCARA

Chapter 4 : Automation of SCARA

% --- Outputs from this function are returned to the command line. function varargout = testing_OutputFcn(hObject, eventdata, handles) % varargout % hObject % eventdata % handles cell array for returning output args (see VARARGOUT); handle to figure reserved - to be defined in a future version of MATLAB structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure varargout{1} = handles.output;

% --- Executes on button press in pushbutton1. function pushbutton1_Callback(hObject, eventdata, handles) guidata(hObject,handles); handles.check=0; [FileName,PathName] = uigetfile({'*.*'},'Select File'); handles.str = strcat(PathName,FileName); filename_length = length (FileName); if ( (FileName(filename_length) == 't') || (FileName(filename_length) == 'T') ) handles.gerber_chk = 1; guidata(hObject,handles); set (handles.edit5,'String','---------'); axes (handles.axes2) imshow('gerber.jpg');

else if ( (FileName(filename_length)) == 'g' || (FileName(filename_length) == 'p') || (FileName(filename_length) == 'P') || (FileName(filename_length) == 'G') ) handles.gerber_chk = 0; handles.I = imread (handles.str); guidata(hObject,handles); set (handles.edit5,'String','PCB Layout'); axes (handles.axes2) imshow(handles.I); end end set (handles.edit7,'ForegroundColor',[0.078 0.169 0.549]); set (handles.edit7,'String',' Ready for next operation'); set (handles.listbox1,'String','');

Page 48 of 124

SCARA
set (handles.listbox2,'String',''); if (handles.first==1) guidata(hObject,handles); axes(handles.axes3); scatter(1,1,1,[0.859 0.933 0.957]); set (handles.axes3,'Visible','off'); set (handles.edit6,'String',''); handles.first = 0; end guidata(hObject,handles); set(handles.pushbutton2,'Enable','on') set(handles.pushbutton3,'Enable','off') set(handles.pushbutton4,'Enable','off') set(handles.pushbutton5,'Enable','off')

Chapter 4 : Automation of SCARA

% hObject % eventdata % handles

handle to pushbutton1 (see GCBO) reserved - to be defined in a future version of MATLAB structure with handles and user data (see GUIDATA)

% --- Executes on button press in pushbutton2. function pushbutton2_Callback(hObject, eventdata, handles) guidata(hObject,handles); handles.first = 1; if (handles.gerber_chk == 1) text = textread(handles.str, '%c'); ll = length(text); x=[]; y=[]; n=1; for i = 1:ll if (text(i)=='X') sign_x = text(i+1); x(n) = str2num(text(i+7))+(str2num(text(i+6)))*10+(str2num(text(i+5)))*100+(str 2num(text(i+4)))*1000+(str2num(text(i+3)))*10000+(str2num(text(i+2)))*10 0000; if (sign_x == '-') x(n)=x(n)*(-1); end n=n+1; end

Page 49 of 124

SCARA
end

Chapter 4 : Automation of SCARA

n=1; for i = 1:ll if (text(i)=='Y') sign_y = text(i+1); y(n) = str2num(text(i+7))+(str2num(text(i+6)))*10+(str2num(text(i+5)))*100+(str 2num(text(i+4)))*1000+(str2num(text(i+3)))*10000+(str2num(text(i+2)))*10 0000; if (sign_y == '-') y(n)=y(n)*(-1); end n=n+1; end end axes (handles.axes3); scatter (x,y);

else

set (handles.edit7,'ForegroundColor',[0.847 0.161 0]); set (handles.edit7,'String',' Busy pause(0.00001); th = 0.625; im = im2bw(handles.I,th); imsize = size(im); imh = imsize(1); imw = imsize(2); (Please Wait)');

im1 = padarray(im, [3 3], 1);

h = [0 1 0; 1 1 1; 0 1 0];

im2p = zeros(imh+6, imw+6); im2 = im2p; im2(1, 1) = 1; tt=0; bb=-1; while(sum(sum(im2p - im2)) ~= 0)

Page 50 of 124

SCARA
im2p = im2; im2 = imdilate(im2, h); im2 = im1 & im2; if (rem(tt,65)==0) if (bb==-1) set (handles.edit7,'String',' Busy pause(0.00001); else if (bb==0) set (handles.edit7,'String',' Busy. pause(0.00001); else if (bb==1)

Chapter 4 : Automation of SCARA

(Please Wait)');

(Please Wait)');

set (handles.edit7,'String',' Busy.. Wait)'); pause(0.00001); else if (bb==2) set (handles.edit7,'String',' Busy... Wait)'); pause(0.00001); bb=-2; end end end end bb=bb+1; end tt=tt+1; end; im3 = xor(im1,im2);

(Please

(Please

bwl = bwlabel(im3); areas = regionprops(bwl,'Area'); center_points = regionprops(bwl,'Centroid'); no_of_holes = size(areas); aa=[];

for rr=1:no_of_holes(1) aa (rr)=areas(rr).Area; if (aa(rr)<2) pixel=find(bwl==rr); im3(pixel)=0; end

Page 51 of 124

SCARA
if (aa(rr)>25) pixel=find(bwl==rr); im3(pixel)=0; end end

Chapter 4 : Automation of SCARA

bwl = bwlabel(im3); center_points = regionprops(bwl,'Centroid');

handles.new=[]; s2=size(center_points); for ii=1:s2(1) handles.new(ii,:) = center_points(ii).Centroid; end handles.i = ii; handles.new(:,2)=imh-handles.new(:,2);

handles.new(:,3)=(1/43.2)*handles.new(:,1); handles.new(:,4)=(1/43.2)*handles.new(:,2); handles.new(:,5)=handles.new(:,3)+40; handles.new(:,6)=handles.new(:,4);

guidata(hObject,handles); axes (handles.axes3) scatter(handles.new(:,5),handles.new(:,6));

end

set (handles.edit6,'String','Scatter Plot of the Coordinates');

set (handles.edit7,'ForegroundColor',[0.078 0.169 0.549]); set (handles.edit7,'String',' Ready for next operation'); set(handles.pushbutton3,'Enable','on') set(handles.pushbutton5,'Enable','on')

% hObject % eventdata % handles

handle to pushbutton2 (see GCBO) reserved - to be defined in a future version of MATLAB structure with handles and user data (see GUIDATA)

Page 52 of 124

SCARA
% --- Executes on button press in pushbutton3.

Chapter 4 : Automation of SCARA

function pushbutton3_Callback(hObject, eventdata, handles) guidata(hObject,handles); handles.check=1; set (handles.edit7,'ForegroundColor',[0.847 0.161 0]); set (handles.edit7,'String',' Busy pause(0.001); (Please Wait)');

l1=52; l2=31; for vr=1:handles.i handles.new(vr,8)=acos((handles.new(vr,5)^2+handles.new(vr,6)^2l1^2-l2^2)/(2*l1*l2)); handles.new(vr,10)=round(handles.new(vr,8)*(180/pi)); handles.new(vr,7)=atan(handles.new(vr,6)/handles.new(vr,5))atan((l2*sin(handles.new(vr,8)))/(l1+l2*cos(handles.new(vr,8)))); handles.new(vr,9)=round(handles.new(vr,7)*(180/pi)); end

guidata(hObject,handles); set (handles.listbox1,'String',num2str(handles.new(:,9))); set (handles.listbox2,'String',num2str(handles.new(:,10))); set (handles.edit7,'ForegroundColor',[0.078 0.169 0.549]); set (handles.edit7,'String',' Ready for next operation'); set(handles.pushbutton4,'Enable','on') % hObject % eventdata % handles handle to pushbutton3 (see GCBO) reserved - to be defined in a future version of MATLAB structure with handles and user data (see GUIDATA)

% --- Executes on button press in pushbutton4. function pushbutton4_Callback(hObject, eventdata, handles) guidata(hObject,handles); set(handles.pushbutton1,'Enable','off') set(handles.pushbutton2,'Enable','off') set(handles.pushbutton3,'Enable','off') set(handles.pushbutton4,'Enable','off') set(handles.pushbutton5,'Enable','off') set (handles.edit7,'ForegroundColor',[0.847 0.161 0]); % serial_obj = serial('COM3'); % set(serial_obj,'BaudRate',9600);

Page 53 of 124

SCARA
% set(serial_obj,'FlowControl','none'); % set(serial_obj,'Parity','none'); % fopen(serial_obj); % fprintf(serial_obj,'%d',30); % fclose(serial_obj); for nt=1:3 guidata(hObject,handles);

Chapter 4 : Automation of SCARA

set (handles.edit7,'String',' Sending angles to the controller (Please Wait)'); pause(0.67); set (handles.edit7,'String',' Sending angles to the controller. (Please Wait)'); pause(0.67); set (handles.edit7,'String',' Sending angles to the controller.. (Please Wait)'); pause(0.67); set (handles.edit7,'String',' Sending angles to the controller... (Please Wait)'); pause(0.67); end set (handles.edit7,'ForegroundColor',[0.078 0.169 0.549]); set (handles.edit7,'String',' All angles have been sent !'); set(handles.pushbutton1,'Enable','on') set(handles.pushbutton2,'Enable','on') set(handles.pushbutton3,'Enable','on') set(handles.pushbutton4,'Enable','on') set(handles.pushbutton5,'Enable','on') pause(0.000001); wavplay(handles.tada,44100); % hObject % eventdata % handles handle to pushbutton4 (see GCBO) reserved - to be defined in a future version of MATLAB structure with handles and user data (see GUIDATA)

% --- Executes on button press in pushbutton5. function pushbutton5_Callback(hObject, eventdata, handles) guidata(hObject,handles); set(handles.pushbutton5,'Enable','inactive') set(handles.pushbutton5,'String','Return') set(handles.pushbutton1,'Enable','off') set(handles.pushbutton2,'Enable','off') set(handles.pushbutton3,'Enable','off')

Page 54 of 124

SCARA
set(handles.pushbutton4,'Enable','off')

Chapter 4 : Automation of SCARA

set (handles.edit7,'ForegroundColor',[0.847 0.161 0]); set (handles.edit7,'String',' Click on a point to select it'); pause(0.00001); set(handles.figure1,'CurrentAxes',handles.axes3); while (1) [x,y]=ginput(1); if ( (x>36.5 && x<186) && (y>489.5 && y<529.4) ) break; end xclosest = 0.2; yclosest = 0.2; for tt=1:handles.i if ( ((abs(x-handles.new(tt,5)))<xclosest) && ((abs(yhandles.new(tt,6)))<yclosest) ) xclosest = abs(x-handles.new(tt,5)); xplot = handles.new(tt,5); if (handles.check==1) anglel1 = handles.new(tt,9); end yclosest = abs(y-handles.new(tt,6)); yplot = handles.new(tt,6); if (handles.check==1) anglel2 = handles.new(tt,10); end end end if ((xclosest<0.2) && (yclosest<0.2)) guidata(hObject,handles); axes (handles.axes3); scatter(handles.new(:,5),handles.new(:,6)); hold on; scatter(xplot,yplot,'filled','CData',[1 0 0]); hold off; set (handles.edit1,'String',num2str(xplot)); set (handles.edit2,'String',num2str(yplot)); if (handles.check==1) set (handles.edit3,'String',num2str(anglel1)); set (handles.edit4,'String',num2str(anglel2)); end set (handles.edit7,'ForegroundColor',[0.847 0.161 0]);

Page 55 of 124

SCARA

Chapter 4 : Automation of SCARA


set (handles.edit7,'String',' Click on another point, or click

Return button to return'); pause(0.00001); else guidata(hObject,handles); set (handles.edit7,'ForegroundColor',[0.847 0.161 0]); set (handles.edit7,'String',' INVALID SELECTION ! Click on a point !'); pause(0.00001); wavplay(handles.err,44100); end end guidata(hObject,handles); set(handles.pushbutton5,'Enable','on') set(handles.pushbutton5,'String','Select a Point') set(handles.pushbutton1,'Enable','on') set(handles.pushbutton2,'Enable','on') set(handles.pushbutton3,'Enable','on') if (handles.check==1) set(handles.pushbutton4,'Enable','on') end set (handles.edit7,'ForegroundColor',[0.078 0.169 0.549]); set (handles.edit7,'String',' Ready for next operation'); axes (handles.axes3); scatter(handles.new(:,5),handles.new(:,6)); set (handles.edit1,'String','x'); set (handles.edit2,'String','y'); set (handles.edit3,'String','theta 1'); set (handles.edit4,'String','theta 2');

% hObject % eventdata % handles

handle to pushbutton5 (see GCBO) reserved - to be defined in a future version of MATLAB structure with handles and user data (see GUIDATA)

function edit1_Callback(hObject, eventdata, handles) % hObject % eventdata % handles handle to edit1 (see GCBO) reserved - to be defined in a future version of MATLAB structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of edit1 as text

Page 56 of 124

SCARA
% a double

Chapter 4 : Automation of SCARA


str2double(get(hObject,'String')) returns contents of edit1 as

% --- Executes during object creation, after setting all properties. function edit1_CreateFcn(hObject, eventdata, handles) % hObject % eventdata % handles called handle to edit1 (see GCBO) reserved - to be defined in a future version of MATLAB empty - handles not created until after all CreateFcns

% Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end

% --- Executes on selection change in listbox1. function listbox1_Callback(hObject, eventdata, handles) % hObject % eventdata % handles handle to listbox1 (see GCBO) reserved - to be defined in a future version of MATLAB structure with handles and user data (see GUIDATA)

% Hints: contents = get(hObject,'String') returns listbox1 contents as cell array % listbox1 contents{get(hObject,'Value')} returns selected item from

% --- Executes during object creation, after setting all properties. function listbox1_CreateFcn(hObject, eventdata, handles) % hObject % eventdata % handles called handle to listbox1 (see GCBO) reserved - to be defined in a future version of MATLAB empty - handles not created until after all CreateFcns

% Hint: listbox controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white');

Page 57 of 124

SCARA
end

Chapter 4 : Automation of SCARA

% --- Executes on selection change in listbox2. function listbox2_Callback(hObject, eventdata, handles) % hObject % eventdata % handles handle to listbox2 (see GCBO) reserved - to be defined in a future version of MATLAB structure with handles and user data (see GUIDATA)

% Hints: contents = get(hObject,'String') returns listbox2 contents as cell array % listbox2 contents{get(hObject,'Value')} returns selected item from

% --- Executes during object creation, after setting all properties. function listbox2_CreateFcn(hObject, eventdata, handles) % hObject % eventdata % handles called handle to listbox2 (see GCBO) reserved - to be defined in a future version of MATLAB empty - handles not created until after all CreateFcns

% Hint: listbox controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end

% --- If Enable == 'on', executes on mouse press in 5 pixel border. % --- Otherwise, executes on mouse press in 5 pixel border or over edit1. function edit1_ButtonDownFcn(hObject, eventdata, handles) % hObject % eventdata % handles handle to edit1 (see GCBO) reserved - to be defined in a future version of MATLAB structure with handles and user data (see GUIDATA)

function edit3_Callback(hObject, eventdata, handles) % hObject % eventdata % handles handle to edit3 (see GCBO) reserved - to be defined in a future version of MATLAB structure with handles and user data (see GUIDATA)

Page 58 of 124

SCARA

Chapter 4 : Automation of SCARA

% Hints: get(hObject,'String') returns contents of edit3 as text % a double str2double(get(hObject,'String')) returns contents of edit3 as

% --- Executes during object creation, after setting all properties. function edit3_CreateFcn(hObject, eventdata, handles) % hObject % eventdata % handles called handle to edit3 (see GCBO) reserved - to be defined in a future version of MATLAB empty - handles not created until after all CreateFcns

% Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end

function edit2_Callback(hObject, eventdata, handles) % hObject % eventdata % handles handle to edit2 (see GCBO) reserved - to be defined in a future version of MATLAB structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of edit2 as text % a double str2double(get(hObject,'String')) returns contents of edit2 as

% --- Executes during object creation, after setting all properties. function edit2_CreateFcn(hObject, eventdata, handles) % hObject % eventdata % handles called handle to edit2 (see GCBO) reserved - to be defined in a future version of MATLAB empty - handles not created until after all CreateFcns

% Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end

Page 59 of 124

SCARA

Chapter 4 : Automation of SCARA

function edit4_Callback(hObject, eventdata, handles) % hObject % eventdata % handles handle to edit4 (see GCBO) reserved - to be defined in a future version of MATLAB structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of edit4 as text % a double str2double(get(hObject,'String')) returns contents of edit4 as

% --- Executes during object creation, after setting all properties. function edit4_CreateFcn(hObject, eventdata, handles) % hObject % eventdata % handles called handle to edit4 (see GCBO) reserved - to be defined in a future version of MATLAB empty - handles not created until after all CreateFcns

% Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end

function edit7_Callback(hObject, eventdata, handles) % hObject % eventdata % handles handle to edit7 (see GCBO) reserved - to be defined in a future version of MATLAB structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of edit7 as text % a double str2double(get(hObject,'String')) returns contents of edit7 as

% --- Executes during object creation, after setting all properties. function edit7_CreateFcn(hObject, eventdata, handles) % hObject % eventdata % handles called handle to edit7 (see GCBO) reserved - to be defined in a future version of MATLAB empty - handles not created until after all CreateFcns

Page 60 of 124

SCARA

Chapter 4 : Automation of SCARA

% Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end

function edit5_Callback(hObject, eventdata, handles) % hObject % eventdata % handles handle to edit5 (see GCBO) reserved - to be defined in a future version of MATLAB structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of edit5 as text % a double str2double(get(hObject,'String')) returns contents of edit5 as

% --- Executes during object creation, after setting all properties. function edit5_CreateFcn(hObject, eventdata, handles) % hObject % eventdata % handles called handle to edit5 (see GCBO) reserved - to be defined in a future version of MATLAB empty - handles not created until after all CreateFcns

% Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end

function edit6_Callback(hObject, eventdata, handles) % hObject % eventdata % handles handle to edit6 (see GCBO) reserved - to be defined in a future version of MATLAB structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of edit6 as text % a double str2double(get(hObject,'String')) returns contents of edit6 as

Page 61 of 124

SCARA

Chapter 4 : Automation of SCARA

% --- Executes during object creation, after setting all properties. function edit6_CreateFcn(hObject, eventdata, handles) % hObject % eventdata % handles called handle to edit6 (see GCBO) reserved - to be defined in a future version of MATLAB empty - handles not created until after all CreateFcns

% Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end

% --- Executes during object creation, after setting all properties. function axes2_CreateFcn(hObject, eventdata, handles) % hObject % eventdata % handles called handle to axes2 (see GCBO) reserved - to be defined in a future version of MATLAB empty - handles not created until after all CreateFcns

% Hint: place code in OpeningFcn to populate axes2

% --- Executes during object deletion, before destroying properties. function axes2_DeleteFcn(hObject, eventdata, handles) % hObject % eventdata % handles handle to axes2 (see GCBO) reserved - to be defined in a future version of MATLAB structure with handles and user data (see GUIDATA)

% --- Executes on mouse press over axes background. function axes2_ButtonDownFcn(hObject, eventdata, handles) % hObject % eventdata % handles handle to axes2 (see GCBO) reserved - to be defined in a future version of MATLAB structure with handles and user data (see GUIDATA)

function edit10_Callback(hObject, eventdata, handles) % hObject % eventdata % handles handle to edit10 (see GCBO) reserved - to be defined in a future version of MATLAB structure with handles and user data (see GUIDATA)

Page 62 of 124

SCARA

Chapter 4 : Automation of SCARA

% Hints: get(hObject,'String') returns contents of edit10 as text % a double str2double(get(hObject,'String')) returns contents of edit10 as

% --- Executes during object creation, after setting all properties. function edit10_CreateFcn(hObject, eventdata, handles) % hObject % eventdata % handles called handle to edit10 (see GCBO) reserved - to be defined in a future version of MATLAB empty - handles not created until after all CreateFcns

% Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end

function edit11_Callback(hObject, eventdata, handles) % hObject % eventdata % handles handle to edit11 (see GCBO) reserved - to be defined in a future version of MATLAB structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of edit11 as text % a double str2double(get(hObject,'String')) returns contents of edit11 as

% --- Executes during object creation, after setting all properties. function edit11_CreateFcn(hObject, eventdata, handles) % hObject % eventdata % handles called handle to edit11 (see GCBO) reserved - to be defined in a future version of MATLAB empty - handles not created until after all CreateFcns

% Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white');

Page 63 of 124

SCARA
end

Chapter 4 : Automation of SCARA

function edit12_Callback(hObject, eventdata, handles) % hObject % eventdata % handles handle to edit12 (see GCBO) reserved - to be defined in a future version of MATLAB structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of edit12 as text % a double str2double(get(hObject,'String')) returns contents of edit12 as

% --- Executes during object creation, after setting all properties. function edit12_CreateFcn(hObject, eventdata, handles) % hObject % eventdata % handles called handle to edit12 (see GCBO) reserved - to be defined in a future version of MATLAB empty - handles not created until after all CreateFcns

% Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end

function edit13_Callback(hObject, eventdata, handles) % hObject % eventdata % handles handle to edit13 (see GCBO) reserved - to be defined in a future version of MATLAB structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of edit13 as text % a double str2double(get(hObject,'String')) returns contents of edit13 as

% --- Executes during object creation, after setting all properties. function edit13_CreateFcn(hObject, eventdata, handles) % hObject % eventdata % handles called handle to edit13 (see GCBO) reserved - to be defined in a future version of MATLAB empty - handles not created until after all CreateFcns

Page 64 of 124

SCARA

Chapter 4 : Automation of SCARA

% Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end

function edit14_Callback(hObject, eventdata, handles) % hObject % eventdata % handles handle to edit14 (see GCBO) reserved - to be defined in a future version of MATLAB structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of edit14 as text % a double str2double(get(hObject,'String')) returns contents of edit14 as

% --- Executes during object creation, after setting all properties. function edit14_CreateFcn(hObject, eventdata, handles) % hObject % e ventdata % handles called handle to edit14 (see GCBO) reserved - to be defined in a future version of MATLAB empty - handles not created until after all CreateFcns

% Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end

function edit15_Callback(hObject, eventdata, handles) % hObject % eventdata % handles handle to edit15 (see GCBO) reserved - to be defined in a future version of MATLAB structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of edit15 as text % a double str2double(get(hObject,'String')) returns contents of edit15 as

Page 65 of 124

SCARA

Chapter 4 : Automation of SCARA

% --- Executes during object creation, after setting all properties. function edit15_CreateFcn(hObject, eventdata, handles) % hObject % eventdata % handles called handle to edit15 (see GCBO) reserved - to be defined in a future version of MATLAB empty - handles not created until after all CreateFcns

% Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end

function edit16_Callback(hObject, eventdata, handles) % hObject % eventdata % handles handle to edit16 (see GCBO) reserved - to be defined in a future version of MATLAB structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of edit16 as text % a double str2double(get(hObject,'String')) returns contents of edit16 as

% --- Executes during object creation, after setting all properties. function edit16_CreateFcn(hObject, eventdata, handles) % hObject % eventdata % handles called handle to edit16 (see GCBO) reserved - to be defined in a future version of MATLAB empty - handles not created until after all CreateFcns

% Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end

function edit17_Callback(hObject, eventdata, handles) % hObject handle to edit17 (see GCBO)

Page 66 of 124

SCARA
% eventdata % handles

Chapter 4 : Automation of SCARA


reserved - to be defined in a future version of MATLAB structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of edit17 as text % a double str2double(get(hObject,'String')) returns contents of edit17 as

% --- Executes during object creation, after setting all properties. function edit17_CreateFcn(hObject, eventdata, handles) % hObject % eventdata % handles called handle to edit17 (see GCBO) reserved - to be defined in a future version of MATLAB empty - handles not created until after all CreateFcns

% Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end

function edit18_Callback(hObject, eventdata, handles) % hObject % eventdata % handles handle to edit18 (see GCBO) reserved - to be defined in a future version of MATLAB structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of edit18 as text % a double str2double(get(hObject,'String')) returns contents of edit18 as

% --- Executes during object creation, after setting all properties. function edit18_CreateFcn(hObject, eventdata, handles) % hObject % eventdata % handles called handle to edit18 (see GCBO) reserved - to be defined in a future version of MATLAB empty - handles not created until after all CreateFcns

% Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER.

Page 67 of 124

SCARA

Chapter 4 : Automation of SCARA

if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end

function edit19_Callback(hObject, eventdata, handles) % hObject % eventdata % handles handle to edit19 (see GCBO) reserved - to be defined in a future version of MATLAB structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of edit19 as text % a % double str2double(get(hObject,'String')) returns contents of edit19 as

% --- Executes during object creation, after setting all properties. function edit19_CreateFcn(hObject, eventdata, handles) % hObject % eventdata % handles called handle to edit19 (see GCBO) reserved - to be defined in a future version of MATLAB empty - handles not created until after all CreateFcns

% Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end

4.2

Gerber File Processing


Every PCB designing software has an option for generating a Gerber File, which

contains the complete information about the holes, layers, wires etc. of the PCB layout. We used Proteus v7.6 for designing our PCBs. It generates different gerber files for different attributes of the layout, all in .txt format. The file named as xxxxx - CADCAM Drill.txt contains the information about the holes of the PCB to be drilled, where xxxxx is the name of the file. We simply read this file using MATLAB, and found the coordinates using it. The MATLAB code for doing so is given on the next page. Page 68 of 124

SCARA MATLAB Code:

Chapter 4 : Automation of SCARA

text = textread('Board 2 - CADCAM Drill.TXT', '%c'); size = length(text); x=[]; y=[]; n=1; for i = 1:size if (text(i)=='X') sign_x = text(i+1); x(n) = str2num(text(i+7)) + (str2num(text(i+6)))*10 + (str2num(text(i+5)))*100 + (str2num(text(i+4)))*1000 + (str2num(text(i+3)))*10000 + (str2num(text(i+2)))*100000; if (sign_x == '-') x(n)=x(n)*(-1); end n=n+1; end end

n=1; for i = 1:size if (text(i)=='Y') sign_y = text(i+1); y(n) = str2num(text(i+7)) + (str2num(text(i+6)))*10 + (str2num(text(i+5)))*100 + (str2num(text(i+4)))*1000 + (str2num(text(i+3)))*10000 + (str2num(text(i+2)))*100000; if (sign_y == '-') y(n)=y(n)*(-1); end n=n+1; end end figure; scatter (x,y);

Page 69 of 124

SCARA

Chapter 4 : Automation of SCARA

4.3

Image Processing
As mentioned before, the GUI can also take an image file as input. It then applies

image processing on it to get the coordinates of the holes to be drilled. The steps we followed in image processing are as under: 1. Read an image file from the hard drive.

Figure 4.8: PCB Layout 2. Convert it into a black and white binary image using threshold of 0.625 3. Put a white border around that image. Store it separately for further use.

Figure 4.9: PCB Layout with a white border around it Page 70 of 124

SCARA

Chapter 4 : Automation of SCARA

4. Now make another completely black image of exactly the same size and make its topmost left pixel white 5. Now dilate this image using the following sectioning element [1 1 1 1] 1

and then take its AND with the image obtained in step 3 6. Repeat step 5 in a loop until the whole image has been dilated.

Figure 4.10: Dilated image 7. Observe that the image obtained after dilation is similar to the one in figure 4.9, only difference is that the holes in this one have been blacked out. Take its XOR with the image in figure 4.9. The resulting image will have white pixels for holes and the rest of the area will be all black, as shown on the next page.

Page 71 of 124

SCARA

Chapter 4 : Automation of SCARA

Figure 4.11: Image obtained after XORing 8. Apply bwlabel command on it. It will divide all the white areas into separate regions. 9. Using regionprops command, the centroid property will give us the coordinates of all the holes.
350

300

250

200

150

100

50

0 50

100

150

200

250

300

350

400

450

500

550

Figure 4.12: Scatter plot of the coordinates Page 72 of 124

SCARA

Chapter 4 : Automation of SCARA

10. We can also observe the area of each hole, using the area property. We made use of this property to remove single pixel noise, and also to remove any unwanted areas that were part of the PCB layout. The MATLAB code for image processing is given below:
close all; clear all; clc; %threshold th = 0.625; %name of image file filename = 'PIC Board 2.jpg'; %read image I=imread(filename); im = im2bw(I,th); figure; %get size imsize = size(im); imh = imsize(1); imw = imsize(2); %put white border around image im1 = padarray(im, [3 3], 1); subplot(2,2,1); imshow(im1); %make sectioning element h = [0 1 0; 1 1 1; 0 1 0]; %make images containing unwanted white area im2p = zeros(imh+6, imw+6); im2 = im2p; im2(1, 1) = 1; while(sum(sum(im2p - im2)) ~= 0) im2p = im2; im2 = imdilate(im2, h); im2 = im1 & im2; end;

subplot(2,2,2); imshow(im2); %put unwanted white area to black

Page 73 of 124

SCARA
im3 = xor(im1,im2); %remove single pixel noise bwl = bwlabel(im3); areas = regionprops(bwl,'Area'); center_points = regionprops(bwl,'Centroid'); no_of_holes = size(areas); aa=[];

Chapter 4 : Automation of SCARA

for rr=1:no_of_holes(1) aa (rr)=areas(rr).Area; if (aa(rr)<2) pixel=find(bwl==rr); im3(pixel)=0; end if (aa(rr)>25) pixel=find(bwl==rr); im3(pixel)=0; end end

subplot(2,2,3) imshow(im3); subplot(2,2,4) imshow(im3);

bwl = bwlabel(im3); center_points = regionprops(bwl,'Centroid');

new=[]; s2=size(center_points); for i=1:s2(1) point = center_points(i).Centroid; new(i,:) = center_points(i).Centroid; rectangle('Position',[fix(point(1))-3,fix(point(2))-3,6 ,6], 'FaceColor','r') end new(:,2)=imh-new(:,2); figure; scatter(new(:,1),new(:,2))

Page 74 of 124

SCARA

Chapter 4 : Automation of SCARA

4.4

Scaling
After image processing, we found the relationship between the no. of pixels of the

image and the distance in centimeters on the PCB. An example is shown below:

Figure 4.13: Relation between the no. of pixels and distance in cms This gives us the relation, 2.5cm = 108 pixels => In MATLAB,
% SCALING

1cm = 43.2 pixels

% 1cm = 43.2pixels % or % 1pixel = 0.02314814815 % size of the image

new(:,3)=(1/43.2)*new(:,1); new(:,4)=(1/43.2)*new(:,2); figure; scatter(new(:,3),new(:,4));

Page 75 of 124

SCARA

Chapter 4 : Automation of SCARA

4.5

Transformation
Now we cannot place the PCB right at the base of SCARA, because the end

effector cannot reach there. So we placed it at some distance and also correspondingly transformed our plane. In MATLAB,
% TRANSFORMATION new(:,5)=new(:,3)+40; new(:,6)=new(:,4); figure; scatter(new(:,5),new(:,6))

After scaling and transformation, the scatter plot of the coordinates came out to be the one shown below:
8

1 40

42

44

46

48

50

52

54

Figure 4.14: Scatter plot of the coordinates after scaling and transformation

Page 76 of 124

SCARA

Chapter 4 : Automation of SCARA

4.6

Inverse Kinematics
First, we studied the studied the forward kinematics of the SCARA Robot. Below

is given a diagram showing the top view of SCARA.

Figure 4.15: Top view of SCARA

Figure 4.16: Top view of SCARA showing the dimensions Lets suppose that the length of the first arm (link - 2) of SCARA is L1, length of the second arm (link - 3) is L2, the angle between the first arm and the x-axes is 1, and the angle between the second arm and the first arm is 2. Now we know that the transformation matrix for the transformation from frame (i-1) to frame i is given by the one shown on the next page. Page 77 of 124

SCARA s s [ s s s s s s s s s s

Chapter 4 : Automation of SCARA

s s 1

The 3x3 matrix formed by the intersection of first three rows and the first three columns of this matrix is the rotation matrix which shows the 3-D rotation in the x, y and z directions. The last row is always [ 1] as shown above. And the first three entries

of the last column constitute the translation matrix. The three entries show the translation in the x, y and z-directions respectively. Now for transformation from frame-0 to frame-1, we only need to rotate the frame of reference by and this rotation is only in the xy-plane. Furthermore, no translation is

required so the translation matrix will be 0. Hence the transformation matrix will be s [ s s s 1 1 ]

For transformation from frame-1 to frame-2, we first need to translate it by L1 along the x-axis, and then we have to rotate it by plane. Hence the transformation matrix will be s [ s s s 1 1 ] and this rotation is only in the xy-

For transformation from frame-2 to frame-3, we only need to translate it by L2 along the x-axis. No rotation is required, so the rotation matrix will be identity matrix. Hence the transformation matrix will be 1 [ 1 1 1 ]

The net transformation matrix for the transformation from frame-0 to frame-3 will be equivalent to the product of these three matrices.

Page 78 of 124

SCARA

Chapter 4 : Automation of SCARA

This transformation matrix will bring us from the origin (base of the SCARA) to the edge of the second arm (link-3). In order to reach the tip of the drill, we will have to translate it further by multiplying it with the P matrix

Where P matrix is the translation matrix [ ] Now in order to study the inverse kinematics of SCARA, consider the top view of SCARA once again.

Figure 4.17: Top view of SCARA showing the dimensions On the next page, are given the detailed dimensions of this top view

Page 79 of 124

SCARA

Chapter 4 : Automation of SCARA

( x,y )

L2 sin(1+2)

1 L1 cos1

L1 sin1

L2 cos(1+2)

Figure 4.18: Detailed dimensions of the top view The point (x,y) is given to us and we have to find the angles 1 and 2. It can be seen from the figure that, x = L1 cos1 + L2 cos(1+2) y = L1 sin1 + L2 sin(1+2) Squaring and adding these two equations, we get, x2 + y2 = L12cos21 + L22cos2(1+2) + 2L1L2cos1cos(1+2) + L12 sin21 + L22 sin2(1+2) + 2L1L2sin1sin(1+2) x2 + y2 = L12 [cos21+sin21] + L22 [cos2(1+2)+sin2(1+2)] + 2L1L2[cos1cos(1+2)+sin1sin(1+2)] x2 + y2 = L12 + L22 + 2L1L2{ cos[1-(1+2)] } cos(-2) = (x2 + y2 - L12 + L22) / (2L1L2) 2 = cos-1 [(x2 + y2 - L12 + L22) / (2L1L2)] Consider the figure 4.18 shown below. A right triangle has been marked in bold, it will help us in finding other angle.

Page 80 of 124

SCARA

Chapter 4 : Automation of SCARA

( x,y )

Figure 4.19: Detailed dimensions of top view with bold right triangle It can be seen that = 1 + or 1 = = tan-1 (y/x) = tan-1 [L2sin2/(L1+L2cos2)] putting these values in equation (B), we get 1 = tan-1 (y/x) tan-1 [L2sin2/(L1+L2cos2)] .(B) by simple geometric formulae,

4.7

Serial Communication
Serial Communication was performed with MATLAB. RS-232 was employed as

standard for communication, since it is the most known serial port used in transmitting the data in communication and interface. Even though serial port is harder to program than the parallel port, this is the most effective method in which the data transmission requires less wires that yields to the less cost. The RS232 is the communication line which enables the data transmission by only using three wire links. The three links provides transmit, receive and common ground. The transmit and receive line on this connecter send and receive data between the computers. As the name indicates, the data is transmitted serially. The two pins are TXD & RXD. There are other lines on this port as RTS, CTS, DSR, DTR, and RTS, RI.

Page 81 of 124

SCARA

Chapter 4 : Automation of SCARA

The 1 and 0 are the data which defines a voltage level of 3V to 25V and -3V to -25V respectively. The electrical characteristics of the serial port as per the EIA (Electronics Industry Association) RS232C Standard specifies a maximum baud rate of 20,000bps, which is slow compared to todays standard speed. For this reason, we have chosen the new RS232D standard, which was recently released. The RS-232D has existed in two types. i.e., D-TYPE 25 pin connector and DTYPE 9 pin connector. We have used the D-TYPE 9 pin connector. The pin outs and pin configurations of DB9 are shown below:

Figure 4.20: DB9 male and female connectors Table 4.1: Pin outs and pin functions of DB9 Pin no. 1 Pin outs DCD Function Data Carrier Detect (This line is active when modem detects a carrier) 2 3 4 5 6 7 TD RD DTR SG DSR RTS Transmit Data (Serial data output) Receive Data (Serial data input) Data Terminal Ready Signal Ground Data Ready State (UART establishes a link) Request To Send (acknowledge to modem that UART is ready to exchange data) 8 9 CTS RI Clear To Send (i.e., modem is ready to exchange data) Ring Indicator (becomes active when modem detects ringing signal from PSTN)

Page 82 of 124

SCARA

Chapter 4 : Automation of SCARA

The IC that we used for voltage level transition from RS-232 to TTL level is MAX-232. Below is shown the schematic diagram and the transition table. All the capacitors in the diagram are of 22uF.

Figure 4.21: Schematic diagram of MAX-232 Table 4.2: Transition table of RS-232 voltages and MAX-232 voltages RS-232 Line Type & Logic Level RS-232 Voltage Data Transmission (Rx/Tx) Logic 0 Data Transmission (Rx/Tx) Logic 1 Control Signals (RTS/CTS/DTR/DSR) Logic 0 Control Signals (RTS/CTS/DTR/DSR) Logic 1 Since Serial ports are not available with new PCs and laptops, we used a USB to serial converter and installed its driver. +3V to +15V 0V +3V to +15V -3V to -15V -3V to -15V 0V 5V 5V TTL Voltage to/from MAX-232

Page 83 of 124

SCARA

Chapter 4 : Automation of SCARA

Figure 4.22: USB to serial converter with its cable The values of the parameters used for serial communication are as under: Table 4.3: Parameter values of serial communication Parameter 1. 2. 3. 4. 5. 6. 7. 8. 9. Baud Rate Timeout Parity Flow Control Data Bits Stop Bits Handshaking Buffer Size Terminator Value 4800 2 sec None None 8 1 None 512 bytes LF

The PIC coding for transmitting the data is given below:


LIST P=18F452 #include <P18F452.INC> org 0x00 clrf PCLATH goto Main org 0x200 Main MOVLW B'00100000' MOVWF TXSTA MOVLW D'12' MOVWF SPBRG BCF TRISC,TX BSF RCSTA,SPEN ;4800 baud rate ;enable receive and serial port

Page 84 of 124

SCARA
r2 MOVLW A'G' r1 BTFSS PIR1,TXIF BRA r1 MOVWF TXREG BRA r2 END

Chapter 4 : Automation of SCARA

And for receiving the data is:


LIST P=18F452 #include <P18F452.INC> org 0x00 clrf PCLATH goto Main org 0x200 Main MOVLW B'10010000' MOVWF RCSTA MOVLW D'12' MOVWF SPBRG BSF TRISC,RX CLRF TRISB MOVLW 0x00 MOVWF PORTB r1 BTFSS PIR1,RCIF BRA r1 MOVFF RCREG,PORTB BRA r1 END ;4800 baud rate ;enable receive and serial port

The MATLAB code that we wrote for transmitting the angles is:
%serial communication to send angles s_obj=serial('com3'); set(s_obj,'BaudRate',4800); set(s_obj,'timeout',2); fopen(s_obj); fprintf(s_obj,'%s',out_1(1)); pause(1) if(out_1(1)>0) fprintf(s_obj,'%s',80); pause(1)

Page 85 of 124

SCARA
else fprintf(s_obj,'%s',78); pause(1) end fprintf(s_obj,'%s',out_2(1)); pause(1) if(out_2(1)>0) fprintf(s_obj,'%s',80); pause(1) else fprintf(s_obj,'%s',78); pause(1) end ang=2; while(1) sent=0; ss=fscanf(s_obj,'%s'); if(ss=='S') display('ok') sent=1;

Chapter 4 : Automation of SCARA

final_out_1=out_1(ang)-out_1(ang-1); fprintf(s_obj,'%s',final_out_1); pause(1) if(final_out_1>0) fprintf(s_obj,'%s',80); %pause(1) else fprintf(s_obj,'%s',78); %pause(1) end final_out_2=out_2(ang)-out_2(ang-1); fprintf(s_obj,'%s',final_out_2); pause(1) if(final_out_2>0) fprintf(s_obj,'%s',80); %pause(1) else fprintf(s_obj,'%s',78); %pause(1) end ang=ang+1;

Page 86 of 124

SCARA
else display('S not received') end if(ang>size(out_1,2)) break; end end fclose(s_obj); delete(s_obj);

Chapter 4 : Automation of SCARA

Before implementing it on hardware, we simulated the serial communication in Proteus, and it worked perfectly. Then we designed and fabricated the PCB for serial communication in Proteus. It also worked perfectly on hardware.

Figure 4.23: Proteus simulation of serial communication with PIC18F452

Page 87 of 124

SCARA

Chapter 4 : Automation of SCARA

Figure 4.24: PCB layout of serial communication board

Figure 4.25: Fully fabricated serial communication board

4.8

Remote access over the internet


Internet has become a necessity now-a-days. One can access anything half way

across the globe using the internet. It has reduced the world to a global village. Keeping this trend in mind, we have also added an interactive feature in our project. We developed a website and interfaced it with SCARA, via MATLAB. Through this website, one can send the input to SCARA even if he is sitting thousands of miles away.

Page 88 of 124

SCARA

Chapter 4 : Automation of SCARA

Figure 4.26: Website All one has to do is to enter his name, location, email address and his PayPal account no. for the deduction of charges. Then he can upload any desired file from his hard drive for drilling. The file may be a Gerber file, or an image file containing the PCB layout.

Figure 4.27: Entering data in the website Page 89 of 124

SCARA

Chapter 4 : Automation of SCARA

The software we used for developing the website is Adobe Dream Weaver. The codes we wrote for developing and formatting the site, and for uploading a file are both given below:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta name="keywords" content="" /> <meta name="description" content="" /> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>Diminishing /> </head> <body> <div id="wrapper"> <!-- end #menu --> <div id="header"> <div id="logo"> <h1>SCARA</h1> </div> </div> <div id="splash">&nbsp;</div> <!-- end #header --> <div id="page"> <div id="page-bgtop"> <div id="page-bgbtm"> <div id="content"> <div class="post"> <h2 class="title">Welcome to Automated Drilling </h2> <div class="entry"> <div class="formm"> <form action="upload.php" method="post" enctype="multipart/form-data"> <p><br/> Name: <p> <input type="text" name ="name"tabindex="1" class="inp-text"/> <br/> <br/> by Free CSS Templates</title> <link href="style.css" rel="stylesheet" type="text/css" media="screen"

Page 90 of 124

SCARA
<p > Location:</p>

Chapter 4 : Automation of SCARA

<input type="text" name ="location"tabindex="2" class="inp-text"/> </p> <p> Email:</p> <p> <input type="text" name ="email"tabindex="3" class="inp-text"/> <br/> </p> <p>PayPal Account No.:</p> <p> <input type="text" name ="paypal"tabindex="4" class="inp-text"/><br/> </p> <p> <label for="file" class="float">Select File:</label> </p> <p>&nbsp;</p> <p> <input type="file" name="file" id="file" "tabindex="5" class="inp-text"/> </p> <p>&nbsp;</p> <p>&nbsp;</p> <p><br /> <input </p> </form> </div> </div> </div> <div class="post"> </div> <div style="clear: both;">&nbsp;</div> </div> <!-- end #content --> <div id="sidebar"> type="submit" name="submit" value="Submit" style="margin-left:230px"/> <br/>

Page 91 of 124

SCARA
<ul> <li>

Chapter 4 : Automation of SCARA

<h2>Introduction</h2> <p>We have designed this website in the wake of commercializing our project. Please upload a layout image file from ARES.</p> </li> <li> <h2>Group Members</h2> <ul> <li><a >Syed Muhammad Zohaib Abbas</a></li> <li><a >Syed Muhammad Danial Haider</a></li> <li><a >Muhammad Zain</a></li> <li><a>Ahmad Hassan Syan</a></li> </ul> </li> <li> <h2>Project Supervisor</h2> <ul> <li><a >Dr. Fahad Mumtaaz</a></li> </ul> </li> </ul> </div> <!-- end #sidebar --> <div style="clear: both;">&nbsp;</div> </div> </div> </div> <!-- end #page --> </div> </div> </body> </html>

<html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta name="keywords" content="" /> <meta name="description" content="" />

Page 92 of 124

SCARA

Chapter 4 : Automation of SCARA

<meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>Diminishing /> </head> <body> <div id="wrapper"> <!-- end #menu --> <div id="header"> <div id="logo"> <h1>SCARA</h1> </div> </div> <div id="splash">&nbsp;</div> <!-- end #header --> <div id="page"> <div id="page-bgtop"> <div id="page-bgbtm"> <div id="content"> <div class="post"> <h2 class="title">Welcome to Automated Drilling </h2> <div class="entry"> <?php if ($_FILES["file"]["error"] > 0) { echo "Error: " . $_FILES["file"]["error"] . "<br />"; } else { } ?> <?php if ((($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/pjpeg")) && ($_FILES["file"]["size"] < 20000000)) { if ($_FILES["file"]["error"] > 0) { echo "Error: " . $_FILES["file"]["error"] . "<br />"; } by Free CSS Templates</title> <link href="style.css" rel="stylesheet" type="text/css" media="screen"

Page 93 of 124

SCARA
else { } } else { echo "invalid file"; } ?> <?php if ((($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/pjpeg")) && ($_FILES["file"]["size"] < 20000000)) { if ($_FILES["file"]["error"] > 0) {

Chapter 4 : Automation of SCARA

echo "Return Code: " . $_FILES["file"]["error"] . "<br />"; } else { echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />"; if (file_exists("upload/" . $_FILES["file"]["name"])) { echo $_FILES["file"]["name"] . " already exists. "; } else { echo "file Uploaded sucessfully"; move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]); echo "Stored in: " . "upload/" . $_FILES["file"]["name"]; } } } else { echo "b"; } ?> <br /><br /><br /><br /><br /> <a href="index.html">Back </a> </div>

Page 94 of 124

SCARA
</div> <div class="post"> </div>

Chapter 4 : Automation of SCARA

<div style="clear: both;">&nbsp;</div> </div> <!-- end #content --> <div id="sidebar"> <ul> <li> <h2>Introduction</h2> <p>We have designed this website in the wake of commercializing our project. Please upload a layout image file from ARES.</p> </li> <li> <h2>Group Members</h2> <ul> <li><a >Syed Muhammad Zohaib Abbas</a></li> <li><a >Syed Muhammad Danial Haider</a></li> <li><a >Muhammad Zain</a></li> <li><a>Ahmad Hassan Syan</a></li> </ul> </li> <li> <h2>Project Supervisor</h2> <ul> <li><a >Sir Fahad Mumtaaz</a></li> </ul> </li> </ul> </div> <!-- end #sidebar --> <div style="clear: both;">&nbsp;</div> </div> </div> </div> <!-- end #page --> </div> </div> </body> </html>

Page 95 of 124

SCARA

Chapter 5 : Summary and Limitations

Chapter 5: SUMMARY AND LIMITATIONS

5.1

Summary
We successfully accomplished all the objectives of our project. By the end of the

semester, we were able to fully control the revolute movement of both the arms, as well as the prismatic movement of the end effector. The movement was also very refine due to the implementation of PID. We also successfully automated our project. Image processing, gerber file processing, inverse kinematics, serial communication and remote access, all were successfully implemented.

5.2

Limitations
We faced many problems and limitations during the course of making this project.

Some of the problems that faced are: No information about the motors and encoders was given to us. The datasheets of the motors were not available, not even on the internet. So we had to manually check and find all the connections and determine the transfer functions of the motors. We did not design the mechanical structure ourselves. It was designed by our seniors. It was a bit old-fashioned and we could not make any changes in it.

Page 96 of 124

SCARA

Chapter 6 : Recommendations for future work

Chapter 6: RECOMMENDATIONS FOR FUTURE WORK


Control and automation are two huge fields. A lot of research is being done in these areas all around the world, and there is still a large area waiting to be explored. Even in the particular case of our project, a lot of research can be done, and a lot of improvements can be made in it. If someone wants to pursue and carry on this project, we would to recommend that: Improvements can be made in the web-SCARA interface. SCARA has many several industrial applications, as discussed in the first chapter. We, however specifically automated our project for automated drilling of PCBs. Its end effector can be changed to serve other industrial applications. And for automation, programming would have to be done accordingly. Improvements can also be made in the mechanical structure. It bulky size and weight can be reduced to make it more practical. Mechanical brakes can also be installed and used for more accuracy.

Page 97 of 124

SCARA

Appendix

APPENDIX

PIC18F452 Features utilized:

Page 98 of 124

SCARA

Appendix

Page 99 of 124

SCARA

Appendix

Page 100 of 124

SCARA

Appendix

Page 101 of 124

SCARA

Appendix

Page 102 of 124

SCARA

Appendix

Page 103 of 124

SCARA

Appendix

Page 104 of 124

SCARA

Appendix

Page 105 of 124

SCARA

Appendix

Serial Communication in MATLAB:


Associate Professor Joel M. Esposito esposito@usna.edu Systems Engineering Department United States Naval Academy, Annapolis, MD 21402 http://www.usna.edu/Users/weapsys/esposito/ Basic Concepts Serial Message: You litterally send or recive data over this cable on a single pin as a series of bytes (1 byte = 8 bits or 0 255). o Example: [0] [12] [27] [42] [112] Terminators: Just as we use a period in English to dentote the end of a sentence, we use a "terminator" to indicate the end of a series of bytes that constitute a message. o The terminator can be anything the sender and receiver agree on but a "carrage return" (\r) is a common choice. Page 106 of 124

SCARA

Appendix

Buffer: If you don't understand how a buffer works, you will never understand serial communication. Say a sensor is streaming back data to your program, more frequently than your program reads it. On your computer this data gets stored in something called a buffer, until you decide to read it. Think of a buffer as a list. o As new data values come in they get added to the bottom of the list (most recent data). o If your program reads a value from the buffer, it starts at the top of the list (oldest data). Once you read a byte of data, it is no longer in the buffer; and the data in the second position on the list moves up to the top position, etc. o The buffer has a finite length (you set it). This means there is a limit to how long the list can get. Once the buffer is totally full, what happens when the sensor tries to send new data to the buffer? The oldest data (top of the list) gets discarded forever, and all the entries move up, to make room on the bottom of the list for new data. o If you'rer smart about using the buffer, you can make sure you never miss any data. If your not smart about it, it is easy to loose data or use old data.

What You Need to Know Before You Continue Go the computer you will use, your device, and all the documentation that came with it. Find the Serial Port on the PC. If there is none, use a USB-to-Serial Converter. You may have to install drivers for it. Connect the device to the PC. COM Port Number: Each serial port on the PC is labeled COM1, COM2, etc. You need to figure out which one you're attached to. o If there is a serial port at the back of the computer, chances are it's COM1. However, even if there is only 1 serial port visible in the back, its possible its COM2, or COM3 especially if there is a modem. o If you use a converter or blue tooth the port number gets assigned in software and may change each time you disconnect or reconnect the device. On Windows XP (or vista classic view), go to Control Panel/System/Hardware/DeviceManager/Ports/Comm Ports and verify which port your device was assigned Device Settings: Go to the documentation that came with your device and identify the Communication settings. We'll need this for the next section. Here is an example: o Baud Rate o Timeout. o Buffer size etc.

Setting up Serial port objects Basic Concepts Matlab uses a special variable type to keep track of serial connections the Serial Object. Unlike nornal variables which have a single value, objects have many "attributes" or parameters that can be set. (ex. port number, baud rate, buffersize, etc) One of those attributes is the port number. A label that cooresponds to which port your device is connected to.

Page 107 of 124

SCARA In order to actually send or recieve data through the serial port object it must be open. When not in use it can be closed (not the same as deleting it) You can have many different serial objects in memory. They can all send and receive data at the same time as long as they are each on a different port. There can even be several objects associated with the same physical port. However, only one of those objects associated with a given port can actually be open (sending or receiving data) at any time.

Appendix

Creating a Serial Port Object Here is an example of how to do this. the only piece of information you must supply is which com port to use. The rest of the attributes are set to some default values: serialPort = serial('com1') Setting the Parameters set(serialPort, 'BaudRate', 19200) get(serialPort, 'BaudRate') This method is cumbersome if you have a lot of things you want to change. A better way to to set them when you create the Serial Object. serialPort_new = serial('com1', 'baudrate', 19200, 'terminator', 'CR') The Parameters To see a list of parameters and their current values get(serialPort) ByteOrder = littleEndian BytesAvailable = 0 BytesAvailableFcn = BytesAvailableFcnCount = 48 BytesAvailableFcnMode = terminator BytesToOutput = 0 ErrorFcn = InputBufferSize = 512 Name = Serial-COM1 ObjectVisibility = on OutputBufferSize = 512 OutputEmptyFcn = RecordDetail = compact

Page 108 of 124

SCARA RecordMode = overwrite RecordName = record.txt RecordStatus = off Status = closed Tag = GarminGPS Timeout = 0 TimerFcn = TimerPeriod = 1 TransferStatus = idle Type = serial UserData = [] ValuesReceived = 0 ValuesSent = 0 SERIAL specific properties: BaudRate = 19200 BreakInterruptFcn = DataBits = 8 DataTerminalReady = on FlowControl = none Parity = none PinStatus = [1x1 struct] PinStatusFcn = Port = COM1 ReadAsyncMode = continuous RequestToSend = on StopBits = 1 Terminator = LF Page 109 of 124

Appendix

SCARA

Appendix

Good Idea To Set Your device will work without setting these but you can set these to make your life easy later. Tag: The tag is like giving the serial port object a nickname. If have a few different serial ports open this a good way to keep track of them. Example, serialPort is configured to talk with a garmin GPS. set(serialPort, 'tag', 'GarminGPS') TimeOut: If you try to read data from the serial port and there is no data in the buffer matlab will keep trying to read for "Timeout" seconds (default 10 sec): get(serialPort, 'Timeout') ans = 10 This might really slow down your code. There are ways around this, but if there is no data there you probably don't want to sit there for 10 seconds, so consider making it smaller. On the other hand, it does take some time for messages to pass over the wire, so setting it to zero means you will probably miss a lot of messages. InputBufferSize: This specifies how long the buffer is. The default is 512 bytes. That might not be long enough for your messages. Especially if you think the sensor will be streaming data back more frequently than you plan on reading the buffer. Remember if the sensor tries to send data and the buffer is full it will discard some old data and it will be gone forever. On the otherhand, having an unessecarliy large buffer can be cumbersome.

Closing Serial Port Objects Concepts When you are done with a serial port object it doesn't go away. Also, closing it, deleting it from memory and clearing it from the workspace are three separate actions.

Example Code For technical reasons you have to use this syntax to properly get rid of it: delete(serialPort_new) clear serialPort_new Writing To The Serial Port Before you can write to your serial port, you need to open it: fopen(serGPS)

Page 110 of 124

SCARA Now you need to figure out two things from the Serial Command Interface (SCI) that came with your device:

Appendix

1. Will you send binary data (bytes) or text (ascii)? 2. What will you send to it? If your SCIs messages look like a list of numbers (ex: [4][253][1][1])), its probably the first choice. Note that even though what you send is actually binary, the documentation might list it as numbers between 0 and 255, or hexidecimal numbers. If your SCIs messages look like a mix of text and numbers (ex: 'MOVE 31'), its probably the second choice. Writing Binary Data Use the command fwrite to send four bytes of binary data fwrite(serGPS, [0, 12, 117, 251]); Writing ASCI Commands Use the command fprintf to send asci data. You can use a mix of text in single quotes and variables values. moveNum = 98; pauseTime = 2; % just some example data fprintf(serGPS, 'MOVE %d, PAUSE %d', [moveNum, pauseTime] ) ; % note Its important to understand that a number, (ex. 98) is not sent as a number. Its actually the asci code for the characters '9' and '8'. Reading From The Serial Port Streaming vs Polling: Flushing the Buffer If you are going to poll the device (send it a request each time you want to get data) you don't want to read any old data that might be left over in the buffer. This is a useful and quick way to clean it out N = serRoomba.BytesAvailable(); while(N~=0) fread(serRoomba,N); N = serRoomba.BytesAvailable(); end

Page 111 of 124

SCARA

Appendix

H-Bridge L298n datasheet:

Page 112 of 124

SCARA

Appendix

Page 113 of 124

SCARA

Appendix

Page 114 of 124

SCARA

Appendix

TIP127 datasheet:

Page 115 of 124

SCARA

Appendix

Page 116 of 124

SCARA

Appendix

Page 117 of 124

SCARA

Appendix

Page 118 of 124

SCARA

Appendix

Page 119 of 124

SCARA

Appendix

TIP122 datasheet:

Page 120 of 124

SCARA

Appendix

Page 121 of 124

SCARA

Appendix

Page 122 of 124

SCARA

Appendix

Page 123 of 124

SCARA

Appendix

Page 124 of 124

Anda mungkin juga menyukai