You are on page 1of 63

CHAPTER 1 PROJECT INTRODUCTION

INTRODUCTION Nowadays robot has been widely used in various fields like industries, academic, research and development, militaries and others. This chapter defines the robot, the project on intelligent spy robot. There are objective and scope of project those give the direction to successfully complete this project. The project is to build an intelligent spy robot that has capability to display the movement live on LCD, to detect if any obstacle on its path and stops there, to detect chunks of metal and is equipped with laser which is replica for a gun .

1.1 Robots Robots have increasingly being used in industries, especially in manufacturing and assembling in major industrialized countries. There are some advantages of using robot, they are: Reduce labour cost. Improved the work quality. Elimination of dangerous or undesirable jobs. Controlled and faster inventory. Increase precision. Robot that are capable to perform complicated motion and have external sensor such as vision, tactile or force sensing are required for a more complicated applications such as welding, painting, grinding and assembly. This is because these operations resulted in the increase of interaction between the robot and its surrounding. A robot by definition is a machine that looks like a human being and performs various complex acts, walking and talking of a human being. It is also defined as fictional machine whose lack of capacity for human emotions is often emphasized. By general convention a robot is a programmable machine that imitates the actions or appearance of an intelligent creature such as human. From the Robot Institute of America, robot is defined: A robot is a programmable multifunctional manipulator designed to move material, part, tools or specialized device through variable programmed motion for the performance of a variety of tasks. British Robot Association (BRA) defines robot as: A programmable device with a minimum of four degrees of freedom designed to both manipulate and transport parts, tools or specialized manufacturing implements through variable programmed motion for the performance of the specific manufacturing task (Al Salameh, 2000)

Robotics is the branch of technology that deals with the design, construction, operation, structural disposition, manufacture and application of robots. Robotics is related to software, engineering, electronics and mechanics. Need of Robots Often, robots are used to do jobs that could be done by humans. However, there are many reasons why robots may be better than humans in performing certain tasks. Speed Robots may be used because they are FASTER than people at carrying out tasks. This is because a robot is really a mechanism which is controlled by a computer - and we know that computers can do calculations and process data very quickly. Hazardous Environment

Robots may be used because they can work in places where a human would be in danger. For example, robots can be designed to withstand greater amounts of heat radiation, chemical fumes than humans could. Repetitive Tasks Sometimes robots are not really much faster than humans, but they are good at simply doing the same job over and over again. This is easy for a robot, because once the robot has been programmed to do a job once, the same program can be run many times to carry out the job many times. And the robot will not get bored as a human would. Efficiency Efficiency is all about carrying out tasks without waste. This could mean not wasting time not wasting materials not wasting energy Accuracy Accuracy is all about carrying out tasks very precisely. In a factory manufacturing items, each item has to be made identically. When items are being assembled, a robot can position parts within fractions of a millimetre. Adaptability Adaptability is where a certain robot can be used to carry out more than one task. A simple example is a robot being used to weld car bodies. If a different car body is to be manufactured, the program which controls the robot can be changed. The robot will then carry out a different series of movements to weld the new car body.

1.2 Purpose of the Project Intelligent spy robot project has been designed for the spying purpose. There are many spy or surveillances camera widely used for home or organization security system. Some of the design able to control via computer by using XBEE that have the wide range of transmit and receive data. With this device the human will able to control and see the wireless visual system via computer from other location. In military, the wireless camera has been used as their first line force to survey the enemy location from their base. By using this robot, they can save their soldier live because before they move to enemy location they already know the enemy situation and percentage to they win in the war will be increase. The main objective behind making this robot is to provide little or small help to our police department and army. It can be used for SPYING PURPOSES to get the confidential details of anybody from remote area without making our life in danger. The camera which would be installed can provide the live streaming of the places where a human cannot reach (especially during natural calamities like earthquakes). To accomplish this task we have installed a robot with a camera which can help the purpose of spying. Along with the camera we have installed other devices metal detector, obstacle sensor and a laser (used as replica for gun).

1.3 Objective There are four main objectives in this project. The first objective of this project is the wireless visual system which is used to human monitor the robot vision via mobile. To build the wireless visual system, the wireless camera will be applied on the robot and the wireless camera will transmit the visual around the robot to the receiver on the LCD. The second objective is to build the obstacle sensor that the robot capable to stop moving when there are obstacles detected. To build a robot with ability to detect obstacle, the obstacle sensor is needed. There are many type of obstacle avoider sensor. The regular obstacle avoider sensor used is Infra Red sensor (IR) because it is easy to use and cheap. The IR sensor operation is when there are object detected, the light on IR will shoot to the object and deflect the light to IR receiver so that the voltage from drop from deflection will be analyzed by the microcontroller to response. The third objective is to build the metal detector that the robot is capable to detect chunks of metal on its path and a buzzer alarm is initiated which detects the presence of chunks of metal. The last objective is to install a laser on the robot which can be used as a replica of gun to fire on the enemy whenever an enemy is seen on the LCD screen.

1.4 Literature Review Conducting the literature review is done prior to undertaking the project. This will critically provide as much information as needed on the technology available and methodologies used by other research counterparts around the world on the topic. This chapter provides the summary of literature reviews on topics related to spy robot or robot that has capability to survey the environment via wireless vision system including robot with obstacle sensor and metal detector. Mobile Operated Robot Conventionally, Wireless-controlled robots use rf circuits, which have the drawbacks of limited working range, limited frequency range and the limited control. Use of a mobile phone for robotic control can overcome these limitations. It provides the advantage of robust control, working range as large as the coverage area of the service provider, Although the appearance and the capabilities of robots vary vastly, all robots share the feature of a mechanical, movable structure under some form of control. The Control of robot involves three distinct phases: perception, processing and action. Generally, the preceptors are sensors mounted on the robot, processing is done by the on-board microcontroller or processor, and the task is performed using motors or with some other actuators.

The robot, is controlled by a mobile phone that makes call to the mobile phone attached to the robot in the course of the call, if any button is pressed control corresponding to the button pressed is heard at the other end of the call. This tone is called dual tone multi frequency tome (DTMF) robot receives this DTMF tone with the help of phone stacked in the robot The received tone is processed by the atmega16 microcontroller with the help of DTMF decoder MT8870 the decoder decodes the DTMF tone in to its equivalent binary digit and this binary number is send to the microcontroller, the microcontroller is pre-programmed to take a decision for any give input and outputs its decision to motor drivers in order to drive the motors for forward or backward motion or a turn. The mobile that makes a call to the mobile phone stacked in the robot acts as a remote. So

this simple robotic project does not require the construction of receiver and transmitter units. DTMF signalling is used for telephone signalling over the line in the voice frequency band to the call switching centre. The version of DTMF used for telephone dialling is known as touch tone. DTMF assigns a specific frequency (consisting of two separate tones) to each key s that it can easily be identified by the electronic circuit. The signal generated by the DTMF encoder is the direct algebraic submission, in real time of the amplitudes of two sine (cosine) waves of different frequencies, i.e., pressing 5 will send a tone made by adding 1336hz and 770hz to the other end of the mobile. Obstacle Sensing Robot Such robots include sensors that require no physical contact with the object being detected. They allow a robot to see an obstacle without actually having to come into contact with it. This can prevent possible entanglement, allow for better obstacle avoidance (over touchfeedback methods), and possibly allow software to distinguish between obstacles of different shapes and sizes. There are several methods used to allow a sensor to detect obstacles from a distance. Infrared Light Based Sensor Another very popular method uses projected light waves, usually infrared, to detect obstacles. This system projects a pulse of light and looks for the reflection. Properties of the reflected light are analyzed to determine characteristics about the object detected. Light has the advantages of travelling extremely fast, allowing for fast sensor response time, high resolution, and less error to account for. Light from this type of sensor is often formed into a narrow beam or many times a laser is used. This provides good resolution over large distances.

IR Proximity Sensor with two emitters

IR Ranging Sensor

Hardware Camera: Omni vision OV9655 1.3 megapixel 160x128 to 1280x102 resolution Range: 100m indoors, 1000m line-of-site Sensors: IR Light based sensors, metal sensors. Drive: Tank-style treads with differential drive via four precision DC gearmotors (100:1 gear reduction) Speed: 20cm - 40cm per second (approx 1 foot/sec or .5 mile/hour) Chassis: Machined Aluminium

Dimensions: 120mm long x 100mm wide x 80mm tall (5" x 4" x 3") Power: 7.2V 2AH Li-poly battery pack - 4+ hours per charge Tools: Drill machine, Mallet, screw driver, sniper, Iron, solder wire, soldering paste(flux), glue gun, Software Keil micro vision for writing C- code for the robot. SPI-PGM software for transferring the hex files to Microcontroller Spy robot is the robot that has ability to spy and to survey the environment or situation at certain place using wireless camera. The visual gathering from the spy robot can be recorded and viewed by human directly. This project will build a spy robot that has ability to detect obstacle and stop moving. Others this project will build a robot with wireless visual system that the user can observe and control the situation via computer and mobile. For the conclusion to build an intelligent spy robot and to obtain the objective of this project the following component needed: i. ii. iii. iv. Wireless camera to the human able to monitor surrounding using computer IR sensor to robot able to detect obstacle. DC Motor for the robot to move. Metal Detector to detect chunks of metal.

CHAPTER 2 PROJECT METHODOLOGY Methodology A proper planning is needed to ensure this project is completed on time and follow the objective. The developing process of The Intelligent Spy Robot involves in design of the main controller circuit includes the electronics and motorization, hardware and simulations and etc. Therefore, this chapter discusses the methods and materials employed in the design and fabrication of the project, as well as its manner of operation. Basically, this project is an interdisciplinary field that ranges in scope from the design of mechanical, electrical components and software development 2.1.0 Mechanical Part To build the intelligent spy robot, several specifications need to apply, for the robot has the capability as the spy robot. The intelligent spy robot must have the wheel for the robot to move and twin motor needed to move the wheel. The obstacle sensor need to place in front of the robot to the robot has capability to detect obstacle beside it. This project using the metal detector to the robot stop moving when there is metal detected. The metal detector must be place at the place that easily to detect metal like at the top of the robot. The last mechanical part is the wireless visual system or wireless camera. The wireless camera needs to be placed at the top of the robot and there are need mechanism for the camera to has capability to turn up and down for the robot able to survey the surrounding environment.

2.2

FUNDAMENTAL OF ROBOTICS

2.2.1 Base: - For base we use chassis, chassis can be of wood or steel. All components are fitted on these chassis. Different types of chassis are:->Micro robot chassis ->4WD chassis ->Pololu chassis ->Battle kit chassis 2.2.2 Actuator:- Actuators allow movement and convert commands into actions. There are 3 main types of actuators: electric, hydraulic and pneumatic. Electric Actuators Electric actuators are simply electro-mechanical devices which allow movement through the use of electrically controlled systems of gears. Some common types are stepper motors, solenoids and an electric motor. Electric motors are the most common form of actuator.

Hydraulic Actuators Hydraulic actuators allow a robot to move by the use of fluids moving under pressure through a series of valves by the use of pumps. The hydraulic fluids bussed would normally consist of oils which are reasonably non-compressible. They are used where a lot of power is needed to move things. These would commonly be industrial robots possibly used on a car assembly line.

Pneumatic Actuators Pneumatic actuators use compressed gas to force the movement of pistons through the use of pumps and valves and so allow movement of the robotic part. Pneumatic actuators work on

10

the same principles as hydraulic actuators using a series of valves, pumps and pistons to generate movement in the robot. Grippers usually use compressed gas because electrics are too dangerous and hydraulics can become too messy if they were to leak.

2.2.3 Motor :- We require 6v to 12 v DC motor for driving the spy robot.


Wheels The wheels connected to geared motors are shown below.

The basic purpose of wheels connected to geared motors is to convert the rotational torque of shaft (which moves due to the rotation of gears), to linear motion for the robot. Positioning and alignment of wheels is necessary for the smooth motion of robot. Also, they are to be fixed on the shaft in such a manner that they rotate only on the movement of shaft and unlike caster are not free to rotate as such. Wheels are the most important part for any robot for its linear motion and so knowledge about their proper use is necessary for any person related to the field. Gear Mechanism in Motors A gear is a component within a transmission device that transmits rotational torque by applying a force to the teeth of another gear or device. A gear is different from a pulley in that a gear is a round wheel that has linkages ("teeth" or "cogs") that mesh with other gear teeth, allowing force to be fully transferred without slippage. Depending on their construction and arrangement, geared devices can transmit forces at different speeds, torques, or in a different direction, from the power source. The most common situation is for a gear to mesh with another gear, but a gear can mesh with any device having compatible teeth, such as linear moving racks.

11

The gear's most important feature is that gears of unequal sizes (diameters) can be combined to produce a mechanical advantage, so that the rotational speed and torque of the second gear are different from those of the first. In the context of a particular machine, the term "gear" also refers to one particular arrangement of gears among other arrangements (such as "first gear"). Such arrangements are often given as a ratio, using the number of teeth or gear diameter as units. Mechanical advantage:

Intermeshing gears in motion The interlocking of the teeth in a pair of meshing gears means that their circumferences necessarily move at the same rate of linear motion (e.g. meters per second, or feet per minute). Since rotational speed (e.g. measured in revolutions per second, revolutions per minute, or radians per second) is proportional to a wheel's circumferential speed divided by its radius, we see that the larger the radius of a gear, the slower will be its rotational speed, when meshed with a gear of given size and speed. The same conclusion can also be reached by a different analytical process: counting teeth. Since the teeth of two meshing gears are locked in a one to one correspondence, when all of the teeth of the smaller gear have passed the point where the gears meet i.e., when the smaller gear has made one revolution -- not all of the teeth of the larger gear will have passed that point -- the larger gear will have made less than one revolution. The smaller gear makes more revolutions in a given period of time; it turns faster. The speed ratio is simply the reciprocal ratio of the numbers of teeth on the two gears. (Speed A * Number of teeth A) = (Speed B * Number of teeth B) This ratio is known as the gear ratio. The torque ratio can be determined by considering the force that a tooth of one gear exerts on a tooth of the other gear. Consider two teeth in contact at a point on the line joining the shaft axes of the two gears. In general, the force will have both a radial and a tangential component. The radial component can be ignored: it merely causes a sideways push on the shaft and does not contribute to turning. The tangential component causes turning. The torque is equal to the tangential component of the force into radius. Thus we see that the larger gear experiences greater torque; the smaller gear less. The torque ratio is equal to the ratio of the radii. This is exactly the inverse of the case with the velocity ratio. Higher torque implies lower velocity and vice versa. The fact that the torque ratio is the inverse of the velocity ratio could also be inferred from the law of conservation of energy. Here we have been neglecting the effect of friction on the torque ratio. The velocity ratio is truly given by the tooth or size ratio, but friction will cause the torque ratio to be actually somewhat less than the inverse of the velocity ratio.

12

DC MOTORSThese motors run on DC. Here, in our case, the motors used are brushed DC electric motor. A brushed DC motor is an internally commutated electric motor designed to be run from a DC power source. Simple two-pole DC motorDC Motor Rotation

When the coil is powered, a The armature continues to magnetic field is generated rotate. around the armature. The left side of the armature is pushed away from the left magnet and drawn toward the right, causing rotation.

When the armature becomes horizontally aligned, the commutator reverses the direction of current through the coil, reversing the magnetic field. The process then repeats.

2.2.4 Driving cicuit:-Physical motion of some form helps differentiate a robot from a computer. It would be nice if a motor could be attached directly to a chip that controlled the movement. But, most chips can't pass enough current or voltage to spin a motor. Also, motors tend to be electrically noisy (spikes) and can slam power back into the control lines when the motor direction or speed is changed. Specialized circuits (motor drivers) have been developed to supply motors with power and to isolate the other ICs from electrical problems. These circuits can be designed such that they can be completely separate boards, reusable from project to project. A very popular circuit for driving DC motors (ordinary or gearhead) is called an H-bridge. It's called that because it looks like the capital letter 'H' when viewed on a discrete schematic. The great ability of an H-bridge circuit is that the motor can be driven forward or backward at any speed, optionally using a completely independent power source. An H-bridge design can be really simple for prototyping or really extravagant for added protection and isolation. An H-bridge can be implemented with various kinds of components (common bipolar transistors, FET transistors, MOSFET transistors, power MOSFETs, or even chips). 2.2.5 Interfacing circuit:- We have use two interfacing circuits for spy robot, camera interfacing circuit and DTMF interfacing cicuit .

13

14

CHAPTER 3 DTMF (Dual Tone Multiple Frequency) 3.1 DTMF Is Dual Tone Multi-Frequency Tones These are the tones that you hear when you press keys on a telephone keypad. The reason for using this standard is that you can buy a single, very accurate IC (usually used in answering machines and the like) that takes care of all the filtering, amplifying and interpreting necessary to determine which key was pressed. And because it's just an analog audio signal that is being exchanged, it can use a number of ordinary, low-cost transmitter/receiver pairs for sending that audio signal. The design of the circuit for decoding DTMF tones is pretty straightforward. The CM8870 IC interprets the tones as a 4-bit digital signal. Then microcontroller checks for the decoded digital signal and compare it with the program installed it. After decoding it will make motors operational through H-BRIDGE (controls clockwise and anticlockwise motion of motor shaft) DTMF (dual-tone multi-frequency) signals 13361336 2 5 8 0 2 5 8 0 1477 1477 3 6 3 6 1633 1633 A A B B CCC D D

FREQUENCFREQUENCIES 1209 1209 (HZ) 697 697 1 1 770 770 4 852 852 7 941 941 * 4 7 *

99 9 # #

When all put together, It will send the DTMF tones over an old 900MHz cordless phone, providing a range of several hundred feet. Because of the modular nature of this system, in the future I could swap out the cordless phone for a newer one, or a pair of FRS radios, or some other transmitter/receiver pair. It doesn't really matter. So then based on which key is pressed, the robot will be able to interpret the tone such to turn on motors and move about.

15

3.2 Theory of Operation So what are these tones? In DTMF there are 16 distinct tones. Each tone is the sum of two frequencies: one from a low and one from a high frequency group.There are four different frequencies in each group. Your phone only uses 12 of the possible 16 tones. If you look at your phone, there are only 4 rows (R1, R2, R3 and R4) and 3 columns (C1, C2 and C3). The rows and columns select frequencies from the low and high frequency group respectively. The exact value of the frequencies are listed in Table 3 below: TABLE 3: DTMF Row/Column FrequenciesLOW-FREQUENCIES ROW # FREQUENCY (HZ) R1: ROW 0 697 R2: ROW 1 770 R3: ROW 2 852 R4: ROW 3 941 HIGH-FREQUENCIES COL # FREQUENCY (HZ) C1: COL 0 1209 C2: COL 1 1336 C3: COL 2 1477 C4: COL 3 1633 C4 not used in phones Thus to decipher what tone frequency is associated with a particular key, look at your phone again. Each key is specified by its row and column locations. For example the "2" key is row 0 (R1) and column 1 (C2). Thus using the above table, "2" has a frequency of 770 + 1336 = 2106 Hz The "9" is row 2 (R3) and column 2 (C3) and has a frequency of 852 + 1477 = 2329 Hz. The following graph is a captured screen from an oscilloscope. It is a plot of the tone

frequency for the "1" key:

16

You can see that the DTMF generated signal is very distinct and clear. The horizontal axis is in samples. The frequency of the tone is about 1900 Hz - close to the 1906 Hz predicted by Table 3 (697+1209).

3.3 DTMF Components: NAME OF COMPONENTS LED

QUANTITY 6

RESISTORS

7-1K,3-11K,1-10K=11

DTMF DECODER IC 8870

CRYSTAL OSCILATOR

CERAMIC CAPACITOR

5 PIN CONNECTOR

2 PIN CONNECTOR

3.4 DTMF Decoder The M-8870 is a full DTMF Receiver that integrates both bandsplit filter and decoder functions into a single 18-pin DIP or SOIC package. Manufactured using CMOS process technology, the M-8870 offers low power consumption (35 mW max) and precise data 17

handling. Its filter section uses switched capacitor technology for both the high and low group filters and for dial tone rejection. Its decoder uses digital counting techniques to detect and decode all 16 DTMF tone pairs into a 4-bit code. External component count is minimized by provision of an on-chip differential input amplifier, clock generator, and latched tri-state interface bus. Minimal external components required include a low-cost 3.579545 MHz colour burst crystal, a timing resistor, and a timing capacitor. The M-8870-02 provides a power-down option which, when enabled, drops consumption to less than 0.5 mW. The M-8870-02 can also inhibit the decoding of fourth column digits

18

3.5

Pin Diagram of MT8870

19

CHAPTER 4 H Bridge DC Motor Driver 4.1 Circuit Diagram

20

4.2

How do we make a motor turn?

You take a battery; hook the positive side to one side of your DC motor. Then you connect the negative side of the battery to the other motor lead. The motor spins forward. If you swap the battery leads the motor spins in reverse. Ok, that's basic. Now lets say you want a Micro Controller Unit (MCU) to control the motor, how would you do it? Well, for starters you get a device that would act like a solid state switch, a transistor, and hook it up the motor. NOTE: If you connect up these relay circuits, remember to put a diode across the coil of the relay. This will keep the spike voltage (back EMF), coming out of the coil of the relay, from getting into the MCU and damaging it. The anode, which is the arrow side of the diode, should connect to ground. The bar, which is the Cathode side of the diode, should connect to the coil where the MCU connects to the relay

If you connect this circuit to a small hobby motor you can control the motor with a processor (MCU, etc.) Applying a logical one, (+12 Volts in our example) to point A causes the motor to turn forward. Applying a logical zero, (ground) causes the motor to stop turning (to coast and stop).

Hook the motor up in this fashion and the circuit turns the motor in reverse when you apply a logical one (+12Volts) to point B. Apply a logical zero, which is usually a ground, causes the motor to stop spinning. If you hook up these circuits you can only get the motor to stop or turn in one direction, forward for the first circuit or reverse for the second circuit. 4.3 Motor Speed You can also pulse the motor control line, (A or B) on and off. This powers the motor in short burst and gets varying degrees of torque, which usually translates into variable motor speed. But if you want to be able to control the motor in both forward and reverse with a processor, you will need more circuitry. You will need an H-Bridge. Notice the "H"-looking configuration in the next graphic. Relays configured in this fashion make an H-Bridge. The "high side drivers" are the relays that control the positive voltage to the motor. This is called sourcing current. The "low side drivers" are the relays that control the negative voltage to sink current to the motor. "Sinking current" is the term for connecting the circuit to the negative side of the 21

power supply, which is usually ground.

So, you turn on the upper left and lower right circuits, and power flows through the motor forward, i.e.: 1 to A, 0 to B, 0 to C, and 1 to D. Then for reverse you turn on the upper right and lower left circuits and power flows through the motor in reverse, i.e.: 0 to A, 1 to B, 1 to C, and 0 to D.

22

4.4 Semiconductor H-Bridges We can better control our motor by using transistors or Field Effect Transistors (FETs). Most of what we have discussed about the relays H-Bridge is true of these circuits. You don't need diodes that were across the relay coils now. You should use diodes across your transistors though. See the following diagram showing how they are connected. These solid state circuits provide power and ground connections to the motor, as did the relay circuits. The high side drivers need to be current "sources" which is what PNP transistors and P-channel FETs are good at. The low side drivers need to be current "sinks" which is what

NPN transistors and N-channel FETs are good at. If you turn on the two upper circuits, the motor resists turning, so you effectively have a breaking mechanism. The same is true if you turn on both of the lower circuits. This is because the motor is a generator and when it turns it generates a voltage. If the terminals of the motor are connected (shorted), then the voltage generated counteracts the motors freedom to turn. It is as if you are applying a similar but opposite voltage to the one generated by the motor being turned. Vis--vis, it acts like a brake. To be nice to your transistors, you should add diodes to catch the back voltage that is generated by the motor's coil when the power is switched on and off. This fly back voltage can be many times higher than the supply voltage.

Transistors, being a semiconductor device, will have some resistance, which causes them to get hot when conducting much current. This is called not being able to sink or source very much power, i.e.: Not able to provide much current from ground or from plus voltage.

23

Mosfets are much more efficient, they can provide much more current and not get as hot. They usually have the flyback diodes built in so you don't need the diodes anymore. This helps guard against flyback voltage frying your MCU. To use Mosfets in an H-Bridge, you need P-Channel Mosfets on top because they can "source" power, and N-Channel Mosfets on the bottom because then can "sink" power. NChannel Mosfets are much cheaper than P-Channel Mosfets, but N-Channel Mosfets used to source power require about 7 volts more than the supply voltage, to turn on. As a result, some people manage to use N-Channel Mosfets, on top of the H-Bridge, by using cleaver circuits to overcome the breakdown voltage. It is important that the four quadrants of the H-Bridgecircuits be turned on and off properly. When there is a path between the positive and ground side of the H-Bridge, other than through the motor, a condition exists called "shoot through". This is basically a direct short of the power supply and can cause semiconductors to become ballistic, in circuits with large currents flowing. There are H-bridge chips available that are much easier, and safer, to use than designing your own H-Bridge circuit.

24

4.5 1.

Functions of individual Parts PC 817 Opto-couplerIts function is isolation of the voltage levels of the DC motor and the micro-controller. The micro-controller works on 5 volts but the DC motor works on 12 volts. As these two are different voltage levels, there is a need of isolation and the four-legged PC 817 device is used here.

2.

BC 557 TransistorsThe function of BC 557 transistors is to perform the EX-OR operation in the module. This leads to the fact that the DC motor will work either on 10 or 01 logic levels coming from the micro-controller to the input signal position in the H-Bridge module. So, the DC motor is saved from damage. This is because if 00 or 11 are supplied to the motors, they will be shorted as explained i the theory about H-Bridges.

3.

TIP 112 and TIP 127There are 8 transistors connected in the H-Bridge module other than BC 557. Of them, 4 are TIP 112 and 4 are TIP 127. The former are NPN transistors and the latter are PNP transistors. They make up in total 4 Darlington Pairs. A Darlington Pair is a circuit consisting of transistors which is responsible for current amplification. Eventually, this current is supplied to the DC motors to make them run.

4.

DiodesThere are 8 diodes used here. Their number is 1N4007 and of 1 ampere current rating. They are used to prevent back e.m.f. This back e.m.f can cause damage to the DC motor.

25

4.6 Assembly And Testing: 1. The individual components were taken as written in the previous pages. 2. Firstly, the octo-couplers were soldered o to the P.C.B. 3. Next, in the spaces above them, the connectors for connections to the Micro-controller unit module were soldered. These were two five-pin connectors. 4. Then came the turn of resistors and next the diodes. These were done before the transistors else it would be difficult for the small legs to be soldered in a congested place. 5. With the soldering of transistors BC557, TIP 112 and TIP 127, this module was complete and ready to be used for the robot.

26

CHAPTER 5 SENSOR Sensor is a device that when exposed to a physical phenomenon (temperature, displacement, force and others) produces a proportional output signal (electrical, mechanical, magnetic and others). The term transducer is often used synonymously with sensors. Ideally, a sensor is a device that response to a change in the physical phenomenon. On other hand, a transducer is a device that converts one form of energy into another form of energy. Sensors are transducer when they sense one form of energy input and output in the different form of energy. For example, a thermocouple response to a temperature changes (thermal energy) and outputs a proportional change in electromotive force (electrical energy). This project uses IR sensors that function as an obstacle avoider when there are obstacles detected.

27

5.1

IR SENSOR

Infra-red (IR) sensor use the concept of reflection of light to function. It consists of two devices, which called as receiver (Rx) and transmitter (Tx). Transmitter transmits the IR packet to an object while receiver receives the packet sent after the light reflected from the object.

We used 556 IC for generating a baudrate as the receiver which is being used in this project is a photo transistor not a photo diode . Photo diode has a feature to work on a frequency of 38 khz or we can say that it only receives the signal of 38 khz.

28

5.2

Metal Sensor

METAL SENSOR use the concept of reflection of magnetic pulses to function. It consists of two devices, which called as receiver (Rx) and transmitter (Tx). Transmitter transmits the magnetic pulses to an object while receiver receives the magnetic pulses sent after the pulses reflected from the object. If the receiver receives the pulses then buzzer get activated. Here transmitter and receiver both are solenoids of 6v and 12v . 6v is transmitter and 12 v receiver.

29

CHAPTER 6 MICROCONTROLLER 6.1 AT89S52 Microcontroller: 6.1.1 Description:

The AT89S52 is a low-power, high-performance CMOS 8-bit microcontroller with 8K bytes of in-system programmable Flash memory. The device is manufactured using Atmels highdensity non-volatile memory technology and is compatible with the industry-standard 80C51 instruction set and pin-out. The on-chip Flash allows the program memory to be reprogrammed in-system or by a conventional non-volatile memory programmer. By combining a versatile 8-bit CPU with in-system programmable Flash on a monolithic chip, the Atmel AT89S52 is a powerful microcontroller which provides a highly-flexible and costeffective solution to many embedded control applications. The AT89S52 provides the following standard features: 8K bytes of Flash, 256 bytes of RAM, 32 I/O lines, Watchdog timer, two data pointers, three 16-bit timer/counters, a six-vector two-level interrupt architecture, a full duplex serial port, on-chip oscillator, and clock circuitry. In addition, the AT89S52 is designed with static logic for operation down to zero frequency and supports two software selectable power saving modes. The Idle Mode stops the CPU while allowing the RAM, timer/counters, serial port, and interrupt system to continue functioning. The Powerdown mode saves the RAM con-tents but freezes the oscillator, disabling all other chip functions until the next interrupt or hardware reset.

30

6.1.2 Pin Configuration:

AT M EL 89 S5 2

31

6.1.3 Circuit Diagram Of AT89S52

32

6.1.4 Pin Description

1) 2) 3)

VCC - Supply voltage.

GND - Ground.

Port 0 - Port 0 is an 8-bit open drain bidirectional I/O port. As an output port, each pin can sink eight TTL inputs. When 1s are written to port 0 pins, the pins can be used as high-impedance inputs. Port 0 can also be configured to be the multiplexed low-order address/data bus during accesses to external program and data memory. In this mode, P0 has internal pull-ups. Port 0 also receives the code bytes during Flash programming and outputs the code bytes during program verification. External pull-ups are required during program verification.

4)

Port 1 - Port 1 is an 8-bit bidirectional I/O port with internal pull-ups. The Port 1 output buffers can sink/source four TTL inputs. When 1s are written to Port 1 pins, they are pulled high by the internal pull-ups and can be used as inputs. As inputs, Port 1 pins that are externally being pulled low will source current (IIL) because of the internal pull-ups. In addition, P1.0 and P1.1 can be configured to be the timer/counter 2 external count input (P1.0/T2) and the timer/counter 2 trigger input (P1.1/T2EX), respectively, as shown in the following table. Port 1 also receives the low-order address bytes during Flash programming and verification.

5)

Port 2 - Port 2 is an 8-bit bidirectional I/O port with internal pullups. The Port 2 output buffers can sink/source four TTL inputs. When 1s are written to Port 2 pins, they are pulled high by the internal pull-ups and can be used as inputs. As inputs, Port 2 pins that are externally being pulled low will source current (IIL) because of the internal pull-ups. Port 2 emits the high-order address byte during fetches from external program memory and during accesses to external data memory that uses 16-bit addresses (MOVX @ DPTR). In this application, Port 2 uses strong internal pull-ups when emitting 1s. During accesses to external data memory that use 8-bit addresses (MOVX @ RI), Port 2 emits the contents of the P2 Special Function Register. Port 2 also receives the high-order address bits and some control signals during Flash programming and verification.

33

6)

Port 3 - This does not need any pull-up resistors since it already has pull-up resistors internally. Although port 3 is configured as an output port upon reset, this is not the way it is most commonly used. Port 3 has the additional function of providing signals.This can be seen from the next table.

34

PORT 3 Table of functions

7) RST - Reset input. A high on this pin for two machine cycles while the oscillator is running resets the device. This pin drives high for 98 oscillator periods after the Watchdog times out. The DISRTO bit in SFR AUXR (address 8EH) can be used to disable this feature. In the default state of bit DISRTO, the RESET HIGH out feature is enabled. 8) ALE/PROG - Address Latch Enable (ALE) is an output pulse for latching the low byte of the address during accesses to external memory. This pin is also the program pulse input (PROG) during Flash programming. In normal operation, ALE is emitted at a constant rate of 1/6 the oscillator frequency and may be used for external timing or clocking purposes. Note, however, that one ALE pulse is skipped during each access to external data memory. If desired, ALE operation can be disabled by setting bit 0 of SFR location 8EH. With the bit set, ALE is active only during a MOVX or MOVC instruction. Otherwise, the pin is weakly pulled high. Setting the ALE-disable bit has no effect if the microcontroller is in external execution mode. 9) PSEN - Program Store Enable (PSEN) is the read strobe to external program memory. When the AT89S52 is executing code from external program memory, PSEN is activated twice each machine cycle, except that two PSEN activations are skipped during each access to external data memory. EA/VPP - External Access Enable. EA must be strapped to GND in order to enable the device to fetch code from external program memory locations starting at 0000H up to FFFFH. Note, however, that if lock bit 1 is programmed, EA will be internally latched on reset. EA should be strapped to VCC for internal program executions. This pin also receives the 12-volt programming enable voltage (VPP) during Flash programming. XTAL1 - Input to the inverting oscillator amplifier and input to the internal clock operating circuit. XTAL2 - Output from the inverting oscillator amplifier.

10)

11)

12)

Function of other parts: 1.7805 Voltage Regulator IC As clear from its name, the function of voltage regulator 7805 is , basically to regulate the voltage. By this, we mean to ensure a constant supply at a level of 5 volts compared to ground. This is essential as the Micro-controller works on voltage levels 5V and ground. 2. Capacitors (10 F) The capacitor (10 F) connected at the left side is for reset of the circuit and the one at the right side is to smoothen the output load.

35

3. Electrolytic Capacitors (1000 F) and Diodes These form the bridge rectifier circuit for the micro-controller unit module. This circuit is responsible for fact that the robot will run on both ac and dc. In case of dc, the rectifier circuit will not come into account but in case of ac, the circuit will convert the ac into dc. This is essential as the micro-controller runs on dc. 4.10 k sip This 10 k sip is a register network. Its function is to give active-low on Port P0. So, what happens is that all the 8 pins of P0 have 5 volts on them and so are disabled. Only when they are made 0 do the pins become enabled. 5. Crystal (11.0592 MHz) This is a Quartz crystal. Its function is to provide for the pins XTAL1 and XTAL2. The crystal provides for the internal operating clock and also is the input to the inverting oscillating amplifiers in the internal structure of the AT89S52 micro-controller.

36

6.2

Assembly and Testing:The P.C.B and the individual components were taken. The micro-controller casing was fixed first. This is necessary, as if the microcontroller is directly soldered, its functioning will be hampered and it would be difficult to solder the very small pieces of the micro-controller chip.

i) ii)

iii)

Then the 1000F Electrolytic Capacitor was soldered along with the diodes to make the Bridge Rectifier circuit.

iv) v) vi) vii)

The IC 7805 voltage regulator is then soldered on to the P.C.B. After that, the 10F capacitors are soldered on to the P.C.B. Then the crystal and other remaining components followed. The Micro-controller unit module was prepared and ready to use.

37

CHAPTER 7 PROGRAMMING AND FLOW CHART

7.1 KEIL SOFTWARE The version of the C programming language used for the microcontroller environment is not very different than standard C when working on mathematical operations, or organizing your code. The main difference is all about the limitations of the processor of the 89S52 microcontroller as compared to modern computers. From the C program to the machine language The C source code is very high level language, meaning that it is far from being at the base level of the machine language that can be executed by a processor. This machine language is basically just zero's and one's and is written in Hexadecimal format, that why they are called HEX files. There are several types of HEX files; we are going to produce machine code in the INTEL HEX-80 format, since this is the output of the KEIL IDE that we are going to use. Figure 2.1.A shows that to convert a C program to machine language, it takes several steps depending on the tool you are using, however, the main idea is to produce a HEX file at the end. This HEX file will be then used by the 'burner' to write every byte of data at the appropriate place in the EEPROM of the 89S52. Variables and constants Variables One of the most basic concepts of programming is to handle variables. knowing the exact type and size of a variable is a very important issue for microcontroller programmers, because the RAM is usually limited is size. There are two main design considerations to be taken in account when choosing the variables types: the occupied space in ram and the processing speed. Logically, a variable that occupies a big number of registers in RAM will be more slowly processed than a small variable that fits on a single register. figure 2.1.A

38

For you to chose the right variable type for each one of your applications, you will have to refer to the following table: Data Type Bits Bit 1 signed char 8 unsigned 8 char signed int 16 unsigned int 16 signed long 32 unsigned 32 long float 32 Bytes -1 1 2 2 4 4 4 Value Range 0 to 1 -128 to +127 0 to 255 -32768 to +32767 0 to 65535 -2147483648 to 2147483647 0 to 4294967295 1.175494E-38 to 3.402823E+38

This table shows the number of bits and bytes occupied by each types of variables, noting that each byte will fit into a register. You will notice that most variables can be either 'signed' or unsigned 'unsigned', and the major difference between the tow types is the range, but both will occupy the same exact space in memory. The names of the variables shown in the table are the same that are going to be used in the program for variables declarations. Note that in C programming language, any variable have to be declared to be used. Declaring a variable, will attribute a specific location in the RAM or FLASH memory to that variable. The size of that location will depend on the type of the variable that have been declared. To understand the difference between those types, consider the following example source code where we start by declaring three 'unsigned char' variables, and one 'signed char' and then perform some simple operations: unsigned char a,b,c; signed char d; a = 100; b = 200; c = a - b; d = a - b;

In that program the values of 'c' will be equal to '155'! and not '-100' as you though, because the variable 'c' is an unsigned type, and when a the value to be stored in a variable is bigger than the maximum value range of this variable, it overflows and rolls back to the other limit. Back to our example, the program is trying to store '-100' in 'c', but since 'c' is unsigned, its range of values is from '0 to 255' so, trying to store a value below zero, will cause the the variable to overflow, and the compiler will subtract the '-100' from the other limit plus 1, from '255 + 1' giving '156'. We add 1 to the range because the overflow and roll back operation from 0 to 255 counts for the subtraction of one bit. On the other hand, the value of 'd' will be equal to '-100' as expected, because it is a 'signed' variable. Generally, we try to avoid storing value that are out of range, because sometime, even if the compiler doesn't halt on that error, the results can be sometimes totally un-expected. Note that in the C programming language, any code line is ended with a semicolon ';', except

39

for the lines ending with brackets '{' '}'. Like in any programming language, the concept of a variables 'array' can also be used for microcontrollers programming. an array is like a table or a group of variables of the same type, each one can be called by a specific number, for example an array can be declared this way: char display[10]; this will create a group of 10 variables. Each one of them is accessible by its number, example: display[0] = 100; display[3] = 60; display[1] = display[0] - display[3]; where 'display[1]' will be equal to '40'. Note that 'display' contains 10 different variables, numbered from 0 to 9. In that previous example, according to the variable declaration, there is not such variable location as 'display[10]', and using it will cause an error in the compiler. Constants Sometimes, you want to store a very large amount of constant values, that wouldn't fit in the RAM or simply would take too much space. you can store this DATA in the FLASH memory reserved for the code, but it wont be editable, once the program is burned on your chip. The advantage of this technique is that it can be used to store a huge amount of variables, noting that the FLASH memory of the 89S52 is 8K bytes, 32 times bigger than the RAM memory. It is, however, your responsibility to distribute this memory between your program and your DATA. To specify that a variable is to be stored in the FLASH memory, we use exactly the same variable types names but we add the prefix 'code' before it. Example: code unsigned char message[500]; This line would cause this huge array to be stored in the FLASH memory. This can be interesting for displaying messages on an LCD screen. To access the pins and the ports through programming, there are a number of pre-defined variables (defined in the header file, as you shall see later) that dramatically simplifies that task. There are 4 ports, Port 0 to Port 3, each one of them can be accessed using the char variables P0, P1, P2 and P3 respectively. In those char types variables, each one of the 8 bits represents a pin on the port. Additionally, you can access a single pin of a port using the bit type variables PX_0 to PX_7, where X takes a value between 0 and 3, depending on the port being accessed. For example P1_3 is the pin number 3 of port 1. You can also define your own names, using the '#define' directive. Note that this is compiler directive, meaning that the compiler will use this directive to read and understand the code, but it is not a statement or command that can be translated to machine language. For example, you could define the following: #define LED1 P1_0

40

With the definition above, the compiler will replace every occurrence of LED1 by P1_0. This makes your code much more easier to read, especially when the new names you give make more sense. You could also define a numeric constant value like this: #define led_on_time 184 Then, each time you write led on time, it will be replaced by 184. Note that this is not a variable and accordingly, you cannot write something like: led_on_time = 100; //That's wrong, you cannot change a constant's value in code. The utility of using defined constants, appears when you want to adjust some delays in your code, or some constant variables that are re-used many times within the code: With a predefined constant, you only change it's value once, and it's applied to the whole code. that's for sure apart from the fact that a word like led on time is much more comprehensive than simply '184'! Along this tutorial you will see how port names, and special function registers are used exactly as variables, to control input/output operations and other features of the microcontroller like timers, counters and interrupts. Mathematical & logic operations Now that you know how to declare variables, it is time to know how to handle them in your program using mathematical and logic operations. Mathematical operations: The most basic concept about mathematical operations in programming languages, is the '=' operator which is used to store the content of the expression at its right, into the variable at its left. For example the following code will store the value of 'b' into 'a' : a = b; And subsequently, the following expression in totally invalid: 5 = b; Since 5 in a constant, trying to store the content of 'b' in it will cause an error. You can then perform all kind of mathematical operations, using the operators '+','-','*' and '/'. You can also use brackets '( )' when needed. Example: a =(5*b)+((a/b)*(a+b)); If you include 'math.h' header file, you will be able to use more advanced functions in your equations like Sin, Cos and Tan trigonometric functions, absolute values and logarithmic calculations like in the following example: a =(c*cos(b))+sin(b);

41

To be able to successfully use those functions in your programs, you have to know the type of variables that those functions take as parameter and return as a result. For example a Cosine function takes an angle in radians whose value is a float number between -65535 and 65535 and it will return a float value as a result. You can usually know those data types from the 'math.h' file itself, for example, the cosine function, like all the others is declared in the top of the math header file, and you can read the line: extern float cos (float val); from this line you can deduce that the 'cos' function returns a float data type, and takes as a parameter a float too. (the parameter is always between brackets.). Using the same technique, you can easily know how to deal with the rest of the functions of the math header file. the following table shows a short description of those functions:

Function Description char cabs (char val); Return an the absolute value of a char variable. int abs (int val); Return an the absolute value of a int variable. long labs (long val); Return an the absolute value of a long variable. float fabs (float val); Return an the absolute value of a float variable. float sqrt (float val); Returns the square root of a float variable. float exp (float val); Returns the value of the Euler number 'e' to the power of val float log (float val); Returns the natural logarithm of val float log10 (float val); Returns the common logarithm of val float sin (float val); A set of standard trigonometric functions. They all take angles float cos (float val); measured in radians whose value have to be between -65535 and float tan (float val); 65535. float asin (float val); float acos (float val); float atan (float val); float sinh (float val); float cosh (float val); float tanh (float val); float atan2 (float y, float This function calculates the arc tan of the ratio y / x, using the signs x); of both x and y to determine the quadrant of the angle and return a number ranging from -pi to pi. float ceil (float val); Calculates the smallest integer that is bigger than val. Example: ceil(4.3) = 5. float floor (float val); Calculates the largest integer that is smaller than val. Example: ceil(4.8) = 4. float fmod (float x, float Returns the remainder of x / y. For example: fmod(15.0,4.0) = 3. y); float pow (float x, float Returns x to the power y. y); Logical operations: You can also perform logic operations with variables, like AND, OR and NOT operations, using the following operators: Operator Description ! NOT (bit level) Example: P1_0 = !P1_0; ~ NOT (byte level) Example: P1 = ~P1;

42

& |

AND OR

Note that those logic operation are performed on the bit level of the registers. To understand the effect of such operation on registers, it's easier to look at the bits of a variable (which is composed of one or more register). For example, a NOT operation will invert all the bit of a register. Those logic operators can be used in many ways to merge different bits of different registers together. For example, consider the variable 'P1', which is of type 'char', and hence stored in an 8-bit register. Actually P1 is an SFR, whose 8 bits represents the 8 I/O pins of Port 1. It is required in that example to clear the 4 lower bits of that register without changing the state of the 4 other which may be used by other equipment. This can be done using logical operators according to the following code: P1 = P1 & 0xF0; (Adding '0x' before a number indicates that it is a hexadecimal one) Here, the value of P1 is ANDed with the variable 0xF0, which in the binary base is '11110000'. Recalling the two following relations: 1 AND X = X 0 AND X = 0 (where 'X' can be any binary value) You can deduce that the 4 higher bits of P1 will remain unchanged, while the 4 lower bits will be cleared to 0. By the way, note that you could also perform the same operation using a decimal variable instead of a hexadecimal one, for example, the following code will have exactly the same effect than the previous one (because 240 = F0 in HEX): P1 = P1 & 240; A similar types of operations that can be performed on a port, is to to set some of its bits to 1 without affecting the others. For example, to set the first and last bit of P1, without affecting the other, the following source code can be used: P1 = P1 | 0x81; Here, P1 is ORed with the value 0x81, which is '10000001' in binary. Recalling the two following relations: 1 OR X = 1 0 OR X = X (where 'X' can be any binary value) You can deduce that the first and last pins of P1 will be turned on, without affecting the state of the other pins of port 1. Those are just a few example of the manipulations that can be done to registers using logical operators. Logic operators can also be used to define very specific conditions, as you shall see in the next section. The last types of logic operation studied in this tutorial is the shifting. It can be useful the

43

shift the bit of a register the right or to the left in various situations. this can be done using the following two operators: Operator Description >> Shift to the right << Shift to the left The syntax is is quite intuitive, for example: P1 = 0x01; // After that operation, in binary, P1 = 0000 0001 P1 = (P1 << 8) // After that operation, in binary P1 = 1000 0000 You can clearly notice that the content of P1 have been shifted 8 steps to the left. Conditions and loops In most programs, it is required at a certain time, to differentiate between different situations, to make decision according to specific input, or to direct the flow of the code depending on some criteria. All the above situation describe an indispensable aspect of programming: 'conditions'. In other words, this feature allows to execute a block of code only under certain conditions, and otherwise execute another code block or continue with the flow of the program. The most famous way to do that is to use the 'if' statement, according to the following syntax. if (expression) { ... code to be executed ... } It is important to see how the code is organized in this part. The 'expression' is the condition that shall be valid for the 'code block' to be executed. the code block is all delimited by the two brackets '{' and '}'. In other words, all the code between those two brackets will be executed if and only if the expression is valid. The expression can be any combination of mathematical and logical expressions, as you can see in the following example: if ( (P1 == 0) & (a <= 128) ){ ... code to be executed ... } Notice the use of the two equal signs (==) between two variables or constants, In C language, this means that you are asking whether P1 equals 0 or not. writing this expression with only one equal sign, would cause the the compiler to store 0 in P1. This issue is a source of logical error for many beginners in C language, this error wont generate any alert from the compiler and is very hard to identify in a big program, so pay attention, it can save you lot of debugging time. Otherwise it is clear that in that previous example, the code block is only executed if both the two expressions are true. Here is a list of all the operators you can use to write an expression describing a certain condition: Operator Description

44

== <, > <=, >= !=

Equal to Smaller than, bigger than. Smaller than or equal to, bigger than or equal to. Not equal to

The 'If' code block can get a little more sophisticated by introducing the 'else' and 'else if' statement. Observe the following example source code: if (expression_1) { ... code block 1 ... }else if(expression_2) { ... code block 2 ... }else if(expression_3) { ... code block 3 ... }else{ ... code block 4 ... } Here, There are four different code blocks, only one shall be executed if and only if the corresponding condition is true. The last code block will only be executed if none of the previous expression is valid. Note that you can have as many 'else if' blocks as you need, each one with its corresponding condition, BUT you can only have one 'else' block, which is completely logical. However you can chose not to have and 'else' block at all if you want. There are some other alternatives to the 'if...else' code block, that can provide faster execution speeds, but also have some limitations and restrictions like the 'Select...case' code block. For now, it is enough to understand the 'if...else' code block, whose performance is quite fair and have a wide range of applications. Another very important tool in the programming languages is the loop. In C language like in many others, loops are usually restricted to certain number of loops like in the 'for' code block or restricted to a certain condition like the 'while' block. Let's start with the 'for' code block, which is a highly controllable and configurable loop. consider the following example source code: for(i=0;i<10;i++){ P0 = i; } Here the code between the the two brackets '{' '}' will be be executed a certain number of times, each time with the counting variable 'i' increasing by 1 according to the statement 'i++'.

45

The code will keep looping as long as the condition 'i<10' is true. Usually the counting value 'i' is reused in the body of the loop, which makes the particularity of this loop. The 'for' loop functioning can be recapitulated by the following syntax: for(start;condition;step){ ... code block ... } Where start represents the start value assigned to the count value before the loop begins. The condition is the expression that is is to remain true for the loop to continue; as long as this conditions is satisfied, the code will keep looping. Finally, step is the increase or decrease of the counting variable, it can be any statement that changes its value, whether by an addition or subtraction. The second type of loop that we are going to study is the 'while' loop. the syntax of this one is simpler than the previous one, as you can observe in the following example source code, that is equivalent to the previous method: while(i < 10){ P0 = i; i = i +1; } Here there is only one parameter to be defined, which is the condition to keep this loop alive, which is 'i < 10' in our example. Then, it is the responsibility of the programmer to design the software carefully to provide an exit for that loop, or to make it an infinite loop. Both techniques are commonly used in microcontroller programs, as you shall see later on along this tutorial. Functions Functions are way of organizing your code, reducing its size, and increasing its overall performance, by grouping relatively small parts of code to be reused many times in the same program. A new function can be created according to the following syntax: Function_name(parameter_1, Parameter_2, Parameter_3){ ... function body ... return value (optional) ... } This is the general form of a function. The number of parameters of the function can be more than the three parameters of the examples above, as it can be zero, all depends on the type and use of the function. The function's body is usually a sub program that implies the parameters to produce the required result. some functions will also generate an output, like the cos() function, through the 'return' command, which will output the value next to it. Usually the 'return' command is used at the end of the function.

46

A very common use of functions without return value is to create delays in a software, consider the following function: delay(unsigned int y){ unsigned int i; for(i=0;i<y;i++){ ; } } In this last piece of code a function named 'delay' is created, with an unsigned integer 'y' as a parameter, and implying a locally defined unsigned int 'i'. the function will repeat a loop for a couple hundreds or thousand of times to generate precise delays in a program. A function like this can be called from anywhere in the program according to the following syntax: delay(30000); this line of code would cause the program to pause for approximately one second on a 12 MHz clock on a 8051 microcontroller. A common example of a function with a return value, is a function that will calculate the angle in radian of a given angle in degrees, as all the trigonometric functions that are included by default take angles in radians. This function can be as the following: deg_to_rad(float deg){ float rad; rad = (deg * 3.14)/180; retrun rad; } This function named 'deg_to_rad' will take as a parameter an angle in degrees and output an angle in radians. It can be called in your program according to this syntax: angle = deg_to_rad(102,18); where angle should be already defined as a float, and where will be stored the value returned by the function, which is the angle in radians equivalent to 102.18 Another important note about functions in the 'main' function. Any C program must contain a function named 'main' which is the place where the program's execution will start. more precisely, for microcontrollers, it were the execution will start after a reset operation, or when a microcontroller circuit is turned ON. The 'main' function has no parameters, and is written like this: main(){ ... code of the main functions ... } Organization of a C program

47

All C programs have this common organization scheme, sometimes it's followed, sometimes it's not, however, it is imperative for this category of programming that this organization scheme be followed in order to be able to develop your applications successfully. Any application can be divided into the following parts, noting that is should be written in this order: a. Headers Includes and constants definitions In this part, header files (.h) are included into your source code. those headers files can be system headers to declare the name of SFRs, to define new constants, or to include mathematical functions like trigonometric functions, root square calculations or numbers approximations. Header files can also contain your own functions that would be shared by various programs. b. Variables declarations More precisely, this part is dedicated to 'Global Variables' declarations. Variables declared in this place can be used anywhere in the code. Usually in microcontroller programs, variables are declared as global variables instead of local variables, unless your are running short of RAM memory and want to save some space, so we use local variables, whose values will be lost each time you switch from a function to another. To summarize, global variables as easier to use and implement than local variables, but they consume more memory space. c. functions' body Here you group all your functions. Those functions can be simple ones that can be called from another place in your program, as they can be called from an 'interrupt vector'. In other words, the sub-programs to be executed when an interrupt occurs is also written in this place. d. Initialization The particularity of this part is that it is executed only one time when the microcontroller was just subjected to a 'RESET' or when power is just switched ON, then the processor continue executing the rest of the program but never executes this part again. This particularity makes it the perfect place in a program to initialize the values of some constants, or to define the mode of operation of the timers, counters, interrupts, and other features of the microcontroller. e. Infinite loop An infinite loop in a microcontroller program is what is going to keep it alive, because a processor have to be allays running for the system to function, exactly like a heart have to be always beating for a person to live. Usually this part is the core of any program, and its from here that all the other functions are called and executed. Simple C program for 89S52 Here is a very simple but complete example program to blink a LED. Actually it is the source code of the example project that we are going to construct in the next part of the tutorial, but for now it is important to concentrate on the programming to summarize the notions discussed above. #include <REGX52.h> #include <math.h> delay(unsigned int y){

48

unsigned int i; for(i=0;i<y;i++){;} } main(){ while(1){ delay(30000); P1_0 = 0; delay(30000); P1_0 = 1; } } After including basic headers for the SFR definitions of the 8952 microcontroller (REGX52.h) and for mathematical functions (math.h), a function named 'delay' is created, which is simple a function to create a delay controlled via the parameter 'y'. Then comes the main function, with an infinite loop (the condition for that loop to remain will always be satisfied as it is '1'). Inside that loop, the pin number 0 of port 1 is constantly turned ON and OFF with a delay of approximately one second. As you will see in the next part, A simple circuit can be constructed and a LED can be connected to the pin P1_0 to see how software and hardware adjustments can affect the behavior of you circuits. Using the KEIL environment KEIL uVision is the name of a software dedicated to the development and testing of a family of microcontrollers based on 8051 technology, like the 89S52 which we are going to use along this tutorial. You can can download an evaluation version of KEIL at their website: http://www.keil.com/c51/. Most versions share merely the same interface, this tutorial uses KEIL C51 uVision 3 with the C51 compiler v8.05a. To create a project, write and test the previous example source code, follow the following steps: Open Keil and start a new project:

49

You will prompted to chose a name for your new project, Create a separate folder where all the files of your project will be stored, chose a name and click save. The following window will appear, where you will be asked to select a device for Target 'Target 1':

50

From the list at the left, seek for the brand name ATMEL, then under ATMEL, select AT89S52. You will notice that a brief description of the device appears on the right. Leave the two upper check boxes unchecked and click OK. The AT89S52 will be called your 'Target device', which is the final destination of your source code. You will be asked whether to 'copy standard 8051 startup code' click No. click File, New, and something similar to the following window should appear. The box named 'Text1' is where your code should be written later.

51

Now you have to click 'File, Save as' and chose a file name for your source code ending with the letter '.c'. You can name is 'code.c' for example, and click save. Then you have to add this file to your project work space at the left as shown in the following screen shot:

52

After right-clicking on 'source group 1', click on 'Add files to group...', then you will be prompted to browse the file to add to 'source group 1', chose the file that you just saved, eventually 'code.c' and add it to the source group. You will notice that the file is added to the project tree at the left. In some versions of this software you have to turn ON manually the option to generate HEX files. make sure it is turned ON, by right-clicking on target 1, Options for target 'target 1', then under the 'output' tab, by checking the box 'generate HEX file'. This step is very important as the HEX file is the compiled output of your project that is going to be transferred to the microcontroller. You can then start to write the source code in the window titled 'code.c' then before testing your source code, you have to compile your source code, and correct eventual syntax errors. In KEIL IDE, this step is called 'rebuild all targets' and has this icon: .

53

You can use the output window to track eventual syntax errors, but also to check the FLASH memory occupied by the program (code = 49) as well as the registers occupied in the RAM (data = 9). If after rebuilding the targets, the 'output window' shows that there is 0 error, then you are ready to test the performance of your code. In keil, like in most development environment, this step is called Debugging, and has this icon:. After clicking on the debug icon, you will notice that some part of the user interface will change, some new icons will appear, like the run icon circled in the following figure: Figure: 2.8.f

54

You can click on the 'Run' icon and the execution of the program will start. In our example, you can see the behavior of the pin 0 or port one, but clicking on 'peripherals, I/O ports, Port 1'. You can always stop the execution of the program by clicking on the stop button () and you can simulate a reset by clicking on the 'reset' button . You can also control the execution of the program using the following icons: which allows you to follow the execution step by step. Then, when you're finished with the debugging, you can always return to the programming interface by clicking again on the debug button (). There are many other features to discover in the KEIL IDE. You will easily discover them in first couple hours of practice, and the more important of them will be presented along the rest of this tutorial.

7.2 Project Programming

55

MOTOR CONTROL LOGIC CONTROL LOGIC

TERMINALS MOTION P3.0 Forward Reverse Left Right Stop 0 1 1 0 1 P3.1 1 0 0 1 1 P3.2 0 1 0 1 1 P3.3 1 0 1 0 1

56

7.3

SPI-PGM

SPIPGM is a interfacing software between microcontroller programmer and pc. How to install the software

57

1. Open the contents of the CD. The following window will appear in front of you.

. Double click on SpiPgm37. 3. Extract all the files to the desired location (say c:\). Preferably make a shortcut icon on the desktop for SpiPgm 1. The installation should be complete if all the instructions were followed correctly.

How to burn the Microcontroller

1. Double click on the icon for SpiPgm. And the following window will appear in front of you. 2. Now select the device AT89S52. 3. Now click on Erase to erase the contents of microcontroller. 4. Now click on Open File and select the desired program.

5. Now click on Program to burn the microcontroller.

6. Your program should now run if all steps were followed correctly and your program is also correct.

58

CHAPTER 8 CAMERA INTERFACING In this project, wireless camera was applied to survey the surrounding. The wireless camera has transmitter and receiver that able it to transmit image and sound data wirelessly.

CAMERA

RECEIVER

USB VIDEO GRABBER Above figure show the USB video grabber that use to view image by using computer. This device has build in driver and Ulead VideoStudio SE DVD software that useful to view the image and table below show the wireless camera specification. Image Pickup Device TV System Scan Frequency Definition Min Illumination Output Power Transmitter Range Power Supply 1/3 1/4 Inch CMOS PAL/CCIR NTSC/EIA PAL/CCIR: 50Hz NTSC/EIA: 60Hz 380 TV Lines 3LUX 50mW 200mW 100M DC +9~12V

59

CHAPTER 9 FINAL ASSEMBLING AND TROUBLE SHOOTING 1. The micro-controller unit module was fixed on the body using screws and nuts. 2. The H-Bridge module was fixed on to the topof the body using screws and nuts. 3. The motors extra edges were cut away and holes were drilled on its one arm to be attached to body. 4. Using screws and hexagonal nuts, the motors were attached to the body in proper alignment. 5. The sensor were attached at the front side and when any obstacle comes infront of it , robot stops . 6. Wheels were fixed on to the shafts of motors using glue and Caster was attached in the front using its nut. 8. The micro-controller AT89S52 was taken and program was burned in it using SPI-PGM37 software. 9. The Metal sensor is attached at the front side. The signal which receiver were getting was of low voltage, so to increase the voltage we use the integrator . 10. During the fixing of motors, gears of one motor were damaged due to which the robots movement was being hampered. This motor had to be replaced. 11. Also, the sensors position was difficult to adjust as it was touching the ground so we placed it on the wooden sheet. 12. The robot was successfully assembled and made operational. The procedure took about 10 weeks.

60

CHAPTER 10 RESULT AND DISCUSSION The SPY Robot was successfully assembled and after burning the program in the AT89S52, all components were working properly and we could see live video on laptop and movement of robot could be controlled by mobile. The result is based on the objective of the project. They are to build the robot that able to sense obstacle when the robot detect the obstacle in front of it and to build a robot that able to stop moving when there is metal a detected.

DISCUSSION This robot is intelligent spy robot that in this robot there are many circuit attach to each other like motor driver, IR sensor, metal detector and PIC main board. All board have its connection to show that it related to each other for example IR sensor use to detect object in front of it and after the object detected, it send signal to comparator to convert the signal to digital. Then the digital signal logic 1 at 3-5 Volts will receive by main board that consist PIC to execute the signal. After the signal is executed, the signal is send to motor driver where motor driver will receive the signal of DC motor direction and DC motor speed. DC motor is like execute device where when the sensor sense object , it will send to PIC and PIC send the signal to those motors to operate. Speed control is most important part in programming to control motor because speed control will cause the robot to avoid collision into the object because there are inertia when the robot moving. The robot will not able to stop on time if the speed is high

CHAPTER 11 FUTURE PROSPECTS 61

1 . To reduce the size of unit we can use smd. 2. Replacement of transmitter with low power transmitter & receiver with highly sensitive receiver to reduce the power consumption 3 . The range can be increased. Additional modules can be added to this application any time. It can be modified in future to add more features. Provisions have been made to upgrade the software. As all the resources used to develop this application were easily available, this application has a cost benefit ratio of more than one. This makes this application of great use in future.

62

REFRENCES 1. 8051 book written by MAZIDI 2. http://en.wikipedia.org/wiki/acuator 3. http://en.wikipedia.org/wiki/Brushed_DC_electric_motor 4. www.DatasheetCatalog.com 5. MicroElectronika. C Compiler for Microchip PIC Microcontrollers .Micro C users manual. 6. . http://www.surveyor.com/SRV_info.html. Last Updated -27 April 2009 15:15 GMT 7. http://www.microdigitaled.com/8051/Software/keil_tutorial.pdf

63

You might also like