This document provides instructions for assembling a small automatic robot called Robo-11 and downloading a program to its 68HC11 microcontroller board to control its operation. It lists the various components included in the robot kit, such as tracks, wheels, joiners and a microcontroller board. It then provides step-by-step directions to physically assemble the robot and connect the microcontroller board. Finally, it explains how to use an Interactive C software to download a firmware program onto the microcontroller board to enable basic control and testing of the robot.
This document provides instructions for assembling a small automatic robot called Robo-11 and downloading a program to its 68HC11 microcontroller board to control its operation. It lists the various components included in the robot kit, such as tracks, wheels, joiners and a microcontroller board. It then provides step-by-step directions to physically assemble the robot and connect the microcontroller board. Finally, it explains how to use an Interactive C software to download a firmware program onto the microcontroller board to enable basic control and testing of the robot.
This document provides instructions for assembling a small automatic robot called Robo-11 and downloading a program to its 68HC11 microcontroller board to control its operation. It lists the various components included in the robot kit, such as tracks, wheels, joiners and a microcontroller board. It then provides step-by-step directions to physically assemble the robot and connect the microcontroller board. Finally, it explains how to use an Interactive C software to download a firmware program onto the microcontroller board to enable basic control and testing of the robot.
This document provides instructions for assembling a small automatic robot called Robo-11 and downloading a program to its 68HC11 microcontroller board to control its operation. It lists the various components included in the robot kit, such as tracks, wheels, joiners and a microcontroller board. It then provides step-by-step directions to physically assemble the robot and connect the microcontroller board. Finally, it explains how to use an Interactive C software to download a firmware program onto the microcontroller board to enable basic control and testing of the robot.
Components used |n bu||d|ng o smo|| outomot|c robot kobo-11
68HC11 Micro-controller Activity Board It comes with a CX-4 cable to download the program. This board is used to control the operation of the robot. It has a 32KB memory, 21 analog input channels, 9 digital inputs, 9 digital outputs, and it drives 4 DC motors and 6 RC servo motors.
Universal Plate Plate size is 160 x 60 mm. There are 341 3-mm size holes with a distance of 5 mm between each hole. Two plates are provided.
Motor Gearbox Uses a 6-9 V and 180 mA DC motor with a ratio of 48:1; torque 4kgF/cm; Two sets are provided.
Track There are 3 sizes. Four 8-Joint tracks; Four 10-Joint Tracks; and two 30-joint tracks.
Angled Shaft Base Two pieces of each the long base and short base are provided.
Metal Axel 4 mm in diameter and 100 mm in length. Four axels come in the set.
2 Wheels There are four different types which are Main Track Wheel (2 Pieces), Large Track Support Wheel (2 pieces), Small Track Support Wheel (10 pieces), and hubs (12 pieces).
Knobby Plate This is used to attach the AX-11 with the universal plates.
Angled Joiner 20 pieces of varied color joiners made from PVC plastic. They can be connected together or by using screws and 3 mm nuts in installation.
Obtuse Joiner 20 pieces of varied color 135 degree obtuse joiners made from PVC plastic. They can be connected together or by using screws and 3 mm nuts in installation.
Strength Joiner 20 pieces of varied color joiners made from PVC plastic. They can be connected together or by using screws and 3 mm nuts in installation.
Nut and Screw Set There are two 2 mm open-end screws, four 3 x 6 mm screws, thirty 3x10 mm screws, four 3 x 15 mm screws, four 3 x 25 mm screws, and thirty 3 mm nuts.
Switch Input The switch input is used to detect collision at logic "0. Two sets along with the connecting cable are provided.
IR Reflector Used to detect the perimeter, lines, and the wheel code. The results are in voltage. Three sets along with the connecting cable are provided.
IR Ranger Measures distance ranging from 4 to 30 cm using infrared light. The results are in voltage.
3
Start by putting together the two track wheels, which each wheel using one 30-joint track, one 10-joint track, and two 8-joint track. Connect all tracks together to form one track wheel that is suitable for the size of the robot.
1 Attach the motor gearbox sets to the universal plate using a 3 x 6 mm and 3 x 10 mm screw. Position the Motor Gearbox sets as shown in the picture below.
2 BUILDING THE ROBOT
4 Take the long angled shaft base and attach it to the universal plate. In between the plate and the long angled shaft, place the strength joiner. Screw them all in together using a 3 x 10 mm screw and nut, positioning it at the 8 th hole from the side where the motor was attached. The smooth side of the shaft base should be turned outwards as shown in the picture. Tighten the screw and nut.
3 Flat plastic joiner Turn the universal plate over to the side where the motors are attached. Attach the short angled shaft base at the end of the plate as shown in the picture.
4 Use a 3 x 10 mm screw and nut to attach the short angled shaft base t o t he universal plate
5 Turn the plate bottom up and insert the metal axel into the holes of the long angled shaft in the positions of 1, 4, and 7 (Counting from the side with the installed motor).
5 Place the small track support wheels over the metal axel with the front of the wheels turned outwards. Insert the hubs over the wheels and use your fingers to press in tightly. Insert a metal axel into the two short angled shaft bases. Then insert the large track support wheels and hub to it.
6
6 Attach the main track wheels to the motor axels with the 2 mm open-end screws.
7 Attach an angled joiner to the universal plate between the two motor gearboxes with a 3 x 10 mm screw and a 3 mm nut. Then attach two more at the Large track support wheels, which is opposite from the motors as shown in the picture.
8
7 Take 3 more angled joiners and attach them to the other universal plate as shown in the picture. The position of the angled joiners must be the same as the ones attached to the plate with the motor gearboxes in Step 8.
9 Insert a strength joiner into all 3 angled joiners to create a support base for the plate with the motor gearbox sets. Then place the two universal plates together. This will make it easier to remove the robot structure for any internal modifications that may be needed.
10
8 Then take the track wheels that were put together in step 1 and place it over the supporting wheels on both sides of the robot. Make sure that both wheels are aligned with one another.
11 Place the knobby plate with the two-sided glue onto the top of the finished robot. Remove the sticker and place the AX-11 board onto the glue surface. This will make it easier to remove or shift the AX-11 board. Then connect the signal cable of the left motor to exterior terminal M- 0 and the signal cable of the right motor to the interior terminal M-1.
12
9 Preparing to Download the Program Preliminary Preparations in Using Interactive C with the AX-11 board on the Robo-11 robot.
The preparations that we are about to talk about is writing the main control program, or what they call the Firmware, into the memory of the AX-11 board. This will be done only once in the beginning, or if the main program data disappears, or if the AX-11 board is unable to receive data from the operational program written by the programmer.
Turn on the POWER switch on the AX-11 board. If the voltage of the battery on the AX-11 is enough, the green PWR LED will be lit brightly. If not, the LED will be dimly displayed and the red BATT LED will indicate that the voltage level is low, as shown in Figure A1-1. Use the +12V DC Adaptor that came with the AX-11 board as the power supply instead by connecting it to the outlet on the board. Once power is supplied, the yellow CHARGE LED will light, and the red LED will disappear as shown in Figure A1-2.
1
10 Take the AX-11 and connect it to the serial port of the computer as shown in Figure A1-3. The green SER LED will light, indicating that the connection of the AX-11 to the serial port of the computer was successful, and is ready for use. 2
11
Problem Solving if the computer has only one USB port
Use a USB port to analog port RS-232 converter, in which we recommend the UCON-232 board. (www.inex.co.th)
Open the Interactive C program by going into Start Program Interactive C 4.30ax Interactive C for AX-11. A title window will appear for an instant before changing to the Select Controller Type window. Choose AX-11.
3 The Port Selection window will appear for you to choose the serial port of the computer that is to be used to communicate with the AX-11 board. Choose the port you want and click Connect now.
4 Go to the menu Tools Download firmware. A window will appear to choose the serial port of communication again. Once you have chosen, click Download Firmware.
5
12 A figure showing the steps in downloading the firmware to the AX-11 board will appear. Start by connecting the download cable to the serial port and to the AX-11 board. Click Next when done.
6 If the green SER LED is lit and blinking, click Yes, it's blinking.
7 A window will appear telling you to turn off the power switch. Turn off the POWER switch and click Next.
8 A window will then appear for you to press the STOP switch on the AX-11 board. While still holding it down, turn on the power of the AX-11 board as indicated in the picture. Then click Next.
9 A window will appear to display the status of the AX-11, indicating that the PWR and BATT LED should be off. Then click Both Lights Off >
10 If the PWR LED is lit, click PWR light still on! An alert message will appear saying it is unable to enter the download mode of t he program, and to check the download cable again before repeating the steps for download.
If the BATT LED is lit, click BATT light still on! An alert message will appear saying that the voltage supply of the battery is low and needs to be recharged for at least another 30 minutes before using it again.
13 If everything is alright, a window displaying the Firmware download status will appear. Once the download is done, a beep will be heard from the AX-11 board, and the status window of the Interactive C program will display the message Download Successful. The display of the AX-11 will show IC 4.30 on AX-11 Activity Board, ending with a blinking heart. The Interactive C program will then go to the Interaction window, which is used for testing the program.
The Robo-11 is now ready for program coding and operation.
8 Testing the Interactive C Program After downloading the main control program, or the firmware, the next step is to write a basic function to test the operation of the AX-11.
1 Go to the Interaction window, type in the function Printf ("Hello world !\n); Then press Enter.
2 The monitor shows the results from the AX-11, displaying "Hello world! on the top sentence. The display of the Interaction window will display the message
This means that the AX-11 board can now interact with the Interactive C program.
14 Next we will create a simple Interactive C program to use with the AX-11 board.
1 Click New to create a new program folder
2 Type in the program below, and save it as hello.ic
3 Click Download to download the program. A window will appear asking to save the file *.ic first. Here, the file is hello.ic. A window displaying the status of the download will then appear.
4 Run the program by Method 1: Turn off and on the POWER switch once to reset the AX-11 board. Method 2: Run the program by clicking Run Main on the Interactive C window. Then choose the Interaction window, the message below will appear
The message "Hello world!" will appear on the top of the AX-11 display screen.
15 Things to be know when downloading the program to the AX-11
If the AX-11 and Interactive C program is used together continuously without turning off the program, the programmer would be able to download and test the program anytime, even when the POWER switch is turned off. This is because the program is stored in a non-volatile system memory.
If the Interactive C program is closed and reopened again while the AX-11 board is still on, and the firmware still operating, the communication between the AX-11 and the Interactive C program must be reestablished. Choose the serial port used to communicate, and then click Connect Now. A window displaying the status of downloading the Interactive C library to the AX-11 board will appear as seen in the picture. Then we will go to the Interaction window, causing the program that was saved in the memory previously to have disappeared; therefore it must be downloaded again.
This means that every time the Interactive C program is closed and opened again, the user must always download the program he needs into the memory again. This is because the Interactive C program is a program that needs to be connected to the hardware in order to check its status continuously. Therefore, if the communication is lost because it was turned off, the communication must always be reestablished at the beginning by downloading the programs library to the AX-11 board. The AX-11 Power Supply The AX-11 uses 8 serial Nickelmethus-hydride batteries size AA with a voltage of 1.2V 1700mAH or above, therefore resulting in a supply of at least 9.6 1700 mAH. The recommended time in charging the batteries is at least 10 to 15 hours. Low current is used to charge the batteries in order to extend the battery life. If the AX-11 board is fully charged, it can be used continuously for 2-4 hours, depending on the number of peripherals connected and the amount of voltage they use.
16 Changing the Batteries The batteries that come with the AX-11 board are rechargeable nickelmethus-hydride, and can used for approximately 1 year. Therefore, for highest efficiency, the batteries should be changed every year using the following steps: 1 Prepare the new battery set and attach foam tape to the top of it.
2 Turn off the POWER switch and removed the adapter cable. Use a screwdriver to remove the 4 screws at the corners of the AX-11.
3 Use a flat-head screw driver (or a four-edged screwdri ver depending on the type of screws in the terminal block). Loosen the screws at the terminal block with the cables of the original battery set. Remove each cable and use a pincher to cut the ends off. This is to prevent the occurrence of a short ci rcuit.
4 Replace the original batteries with the new set, turning the side with the foam tape upwards. Then peel about 5 mm of the batterys red cable (positive) off and connect it to the + of the terminal block. Use the screwdri ver to tighten the screws at the terminal block that hold the cable. Do the same for the black cable (negative) of the battery. This step is very important. It needs to be done one cable at a time to prevent short-circuit of the battery or with other parts of the AX-11 boards.
5 Then place the board back to i ts original place. Use the screwdriver to screw the 4 screws at the corner of the AX-11 board back to the box. Connect the adapter to the AX-11 board to charge the battery. This should take 10 to 12 hours to charge the batteries for the first time. The AX-11 board should be ready for use after this.
17 /* Example for Robot basic movement Hardware configuration - Motor left connected to DC Motor chanel M-0 - Motor right connected to DC Motor chanel M-1 */ #define pow 50 /* Configuration power drive motor */
void main() { ao(); // All off motor every channel printf("Press Start! \n); // Display message on LCD start_press(); // Wait until Press start key while(1) // Infinite loop { run_fd(2.0); // Robot forward 2 sec run_bk(2.0); // Robot backward 2 sec } } void turn_left(float spin_time) { motor(0,-pow); // Motor0 backward for pow define value motor(1,pow); // Motor1 forward for pow define value sleep(spin_time); // Delay set by parameter spin_time } void turn_right (float spin_time) { motor(0,pow); // Motor0 forward for pow define value motor(1,-pow); // Motor1 backward for pow define value sleep(spin_time); // Delay set by parameter spin_time } void run_fd(float delay) { motor(0,pow); // Motor0 forward for pow define value motor(1,pow); // Motor1 forward for pow define value sleep(delay); // Delay set by parameter delay } void run_bk(float delay) { motor(0,-pow); // Motor0 backward for pow define value motor(1,-pow); // Motor1 backward for pow define value sleep(delay); // Delay set by parameter delay }
ROBO-11 Testing After the Robo-11 has been put together, we will next write a program to test the functioning of the motor to see whether it is working together properly and if it is ready for its future operations or not. A simple program will be downloaded for the robot to move forward 2 seconds, move backwards 2 seconds, and continue to repeat these steps.
Type in the following program code and download it to the Robo-11
18 /* Example for Robot movement, program to near square movement Hardware configuration - Motor left connected to DC Motor chanel M-0 - Motor right connected to DC Motor chanel M-1 */ #define pow 40 /*Configuration power drive motor*/
void main() { ao(); // All off motor every channel printf("Press Start!\n); // Display message on LCD start_press(); // Wait until Press start key while(1) // Infinite loop { run_fd(2.0); // Robot forward 2 sec turn_left (1.0); // Robot backward 1 sec } }
Testing It
Place the Robo-11 on the floor and then turn on the POWER switch. The LCD screen displays the message Press Start. Press START on the AX-11.
The robot will move forward for 2 seconds, using only 50% of its power. Observe the motor LED on the AX-11 board. Both must be green. Then the robot will move backwards for 2 seconds. Observe the motor LED on the AX-11 that shows the functionality of the motors. Both will turn to red.
If you don't get these results, switch the motor cables terminal charge on the AX-11 unt il you get the correct results. Use this motor connection for future operat ions.
Robo-11 Test (2)
From Test (1), the next step would be to include additional conditions for the robot so that the robot can move in the direction or way desired. In this test, the Robo-11 is told to move in a square-like shape.
Type in the following program code and download it to the Robo-11
19 void turn_left(float spin_time) { motor(0,-pow); // Motor0 backward for pow define value motor(1,pow); // Motor1 forward for pow define value sleep(spin_time); // Delay set by parameter spin_time } void turn_right (float spin_time) { motor(0,pow); // Motor0 forward for pow define value motor(1,-pow); // Motor1 backward for pow define value sleep(spin_time); // Delay set by parameter spin_time } void run_fd(float delay) { motor(0,pow); // Motor0 forward for pow define value motor(1,pow); // Motor1 forward for pow define value sleep(delay); // Delay set by parameter delay } void run_bk(float delay) { motor(0,-pow); // Motor0 backward for pow define value motor(1,-pow); // Motor1 backward for pow define value sleep(delay); // Delay set by parameter delay }
Testing It
Place the Robo-11 on the floor and then turn on the POWER switch. The LCD screen displays the message Press Start. Press START on the AX-11. The robot will move forward for 2 seconds, using only 50% of its power. Then the robot will turn left for 2 seconds and continue doing so. It can be observed that the robot is moving in a square-like movement.
How much the Robo-11 Standard is able to move in a perfect square depends on many factors, such as the current battery level, the current supplied to the motor, movement time, and the friction at the wheels of the robot.
20
1. If the downloaded program does not work.
Solve by Check the download cable by checking if the SER LED is green. Check the power supply by checking if the BATT LED is red. If it is lighted bright it means that the battery is low. Use the external power from the DC adapter +12V 500 mA Download the firmware again.
2. If the AX-11 cannot communicate with the Interactive C program.
Solve by Check the power supplied to the AX-11 by checking if the PWR LED is green. Check the download cable by checking if the SER LED is green. Check the power supply by checking if the BATT LED is red. If it is lighted bright it means that the battery is low. Use the external power from the DC adapter +12V 500 mA If everything is ok, download the firmware again.
3. If the firmware can not be downloaded
Solve by Check the power supplied to the AX-11 by checking if the PWR LED is green. Check the download cable by checking if the SER LED is green. Check the power supply by checking if the BATT LED is red. If it is lighted bright it means that the battery is low. Use the external power from the DC adapter +12V 500 mA If it is still not working, send the robot back to the manufacturer or distributor to check its functionality
Basic Problem Solving
21
IC 4 Frogrommers Monuo|
Intr oduct| on lnIerccIive C {lC fcr :hcrI) i: c C |cngucge ccn:i:Iing cf c ccmpi | er {wiIh i nIerccIive ccmmcnc-| ine ccmpi| cIi cn cnc ceLugging) cnc c run-Iime mcchine |cngucge mccu|e. lC imp| emenI : c :uL:eI cf C i nc|ucing ccnI rc| :IrucIure: {fcr, whi| e, i f, e| :e), | ccc| cnc g|cLc| vcricL|e:, crrcy:, pcinIer:, :IrucI ure:, 1-LiI cnc 32-LiI i nI eger:, cnc 32-LiI f| ccIing pci nI numLer:. lC wcrk: Ly ccmpi |ing inI c p:eucc-ccce fcr c cu:Icm :Icck mcchine, rcIher I hcn ccmpi |i ng ci recI|y inIc ncI ive ccce fcr c pcrIi cu|cr prcce::cr. Ihi : p:eucc- ccce {cr p- ccce) i: Ihen inI erpreI ec Ly Ihe run-Iime mcchine | cngucge prcgrcm. Ihi : unu:uc| cpprccch Ic ccmpi |er ce:ign c|| cw: lC I c cffer I he fc|| cwing ce:i gn I rccecff:: Inter preted execut| on I hcI c|| cw: run-Iime errcr checki ng. Fcr excmp|e, lC cce: crrcy Lcunc: checking cI run- Iime Ic prcIecI cgcin:I :cme prcgrcmming errcr:. Eose o| des| gn. WriIi ng c ccmpi | er fcr c :Icck mcchine i : :i gni fi ccnI|y ec:i er Ihcn wriIing cne fcr c Iypicc| prcce::cr. Si nce lC': p-ccce i : mcchine- incepencenI, pcrIing lC Ic cncI her prcce::cr enIci |: rewri Iing Ihe p- ccce inIerpreIer, rcIher Ihcn chcnging Ihe ccmpi| er. Smo|| obj ect code. SIcck mcchi ne ccce I enc: Ic Le :mc|| er I hcn c ncIive ccce repre:enIcIicn. Mu|t|-tosk|ng. 8eccu:e Ihe p:eucc- ccce i : fu|| y :Icck-Lc:ec, c prcce::' : :IcI e i : cefi nec :c|e|y Ly iI : :Icck cnc iI : prcgrcm ccunIer. lI i : Ihu: ec:y I c Ic:k- :wiIch :imp| y Ly | cccing c new :Icck pcinIer cnc prcgrcm ccunI er. Ihi: Ic:k- :wiIching i: hcnc|ec Ly Ihe run-Iime mccu|e, ncI Ly Ihe ccmpi |er. Since lC' : u|Ii mcI e perfcrmcnce i: |imiIec Ly Ihe fccI IhcI iI: cuIpuI p-ccce i : inI erpreI ec, Ihe:e ccvcnIcge: cre Icken cI Ihe expen:e cf rcw execuIi cn :peec. |C 4 wc: w|| tt en cy Fcncy Sc|gent c| tne K|SS | n:t |tut e |c| F|cct| cc| Fccct | c:. Fcncy wc: c::|:t ec cy /c|k Sne|ncn. Fc|t| cn: c| t ne ccce cnc t ne ||c|c|| e: c|e cc:ec cn t ne puc|| c c| :t|| cut | cn c| |C 2.8 w|| tt en cy Fcncy Sc| gent . Anne W|| gnt cnc F|ec /c|t|n.
22
bs|ng IC When lC i: runni ng cnc hc: c ccnnecI i cn I c c ccmpcI iL| e prcce::cr Lccrc :uch c: Ihe Hcncy 8ccrc cr FCX, C expre::i cn:, funcI icn cc|| :, cnc lC ccmmcnc: mcy Le Iypec in Ihe ccmmcnc enIry pcrIi cn cf I he i nIerccIicn winccw. Fcr excmp|e, Ic evc|ucIe Ihe criIhmeIi c expre::i cn 1 + 2, Iype in I he fc|| cwing: 1 + 2: When Ihi: expre::i cn i : enIerec frcm I he inI erccIi cn winccw, iI i: ccmpi| ec Ly Ihe ccn:c| e ccmpuIer cnc I hen ccwn|cccec Ic I he cIIcchec :y:Iem fcr evc|ucI icn. Ihe ccnnecIec Lccrc Ihen evc|ucIe: Ihe ccmpi |ec fcrm cnc reIurn: Ihe re:u|I , whi ch i : pri nIec cn Ihe ci:p|cy :ecIicn cf ccn:c| e inI erccI icn winccw. Ic evc|ucI e c :eri e: cf expre::i cn:, crecIe c C L| cck Ly Leginning wiIh cn cpen cur| y Lrcce { cnc encing wiIh c c| c:e cur| y Lrcce }. Ihe fc|| cwing excmp|e crecI e: c | ccc| vcricL|e i cnc prinI : 10 {I he :um cf i + 7) I c I he Lccrc' : LCD :creen: {inI i=3: pri nI f{7c, i +7):}
23
IC Inter|oce 8cIh new {un:cvec) cnc :cvec fi | e: ccn Le cpenec fcr eciI ing in lC. / rcw cf IcL: | i:I : Ihe fi |e: IhcI hcve Leen cpenec. C|i cki ng c fi|e' : IcL ccIivcIe: iI fcr eciIing. Ihe fir:I IcL fcr Ihe inIerfcce i : c|wcy: Ihe inI erccI i cn winccw. Ihe F||e LuII cn hc: :I cnccrc enIri e: fcr New, Open, C| ose, Sove, Sove As, Fr|nt, cnc Ex|t. Uncer F||e - Sove As, i f nc fi | e ncme exIen:i cn i: :upp|i ec, lC cuI cmcI icc|| y :cve: wiIh Ihe .|c exI en:icn. Ic ccwn|ccc Ihe ccIive fi |e, :imp| y c|i ck Ihe ccwn| ccc LuIIcn. Ihe ccI ive fi| e wi|| c|:c Le :cvec, un| e:: iI i : new, in which cc:e Ihe u:er i : prcmpIec fcr c :cve c: fi| e ncme. Femcrk: c preprcce::cr ccmmcnc u:e hc: Leen cccec I c lC Ic :pecify cny cIher :cvec fi|e: {per:cnc| |iLrcri e:) IhcI neec I c Le ccwn|cccec c| cng wiIh Ihe ccIive fi| e |NcI e: u:e i : uiI e cifferenI frcm Ihe inc|uce preprecce::cr ccmmcnc cf :I cnccrc C envircnmenI:. inc|uce i : ncI imp| emenI ec fcr rec:cn: given | cIer i n Ihe :ecIi cn ce:criLi ng Ihe lC- preprcce::cr.] lf c ccwn|cccec prcgrcm cce: ncI cc whcI i: inIencec, iI mcy ccrrupI Ihe p-ccce inIerpreIer, pcrIi cu|cr|y i f pci nI er: cre Leing emp|cyec. Ihe i nIerfcce prcvice: cn cpIicn uncer Ihe Sett|ngs LuII cn fcr ccwn|cccing Ihe fi rmwcre I c reiniIic|ize Ihe Lccrc. When I here i: c ccnnecIi cn I c c Lccrc cnc Ihe ccwn|cccec prcgrcm: inc|uce mcin, Ihen mcin ccn Le execuIec u:ing Ihe kun Mo|n LuII cn. Ihe Stop LuII cn wi|| hc|I execuI i cn cf I he cIIcchec :y:Iem. Uncer Ihe Ioo|s LuIIcn, cmcng cI her cpI icn:, cre cne: fcr |i:Ii ng ccwn| cccec fi | e:, g| cLc| vcricL|e:, cnc funcIicn: {i nc|ucing |i Lrcry funcIi cn:). Ihe i nIerfcce prcvice: ccciI icnc| ccpcLi|iIi e: fcr prcgrcm enI ry/eciI , mincr ccju:ImenI Ic Ihe ci :p|cy, cnc fcr :eIIing up Ihe :eric| inIerfcce I c c Lccrc. C prcgrcm: cre cuI cmcIi cc|| y fcrmcII ec cnc incenIec. Keywcrc:, | iLrcry funcI i cn:, ccmmenI :, cnc IexI :I ri ng: cre high-| i ghI ec wiIh cc|cr un| e:: Ihi: fecI ure i: Iurnec cff. lC cce: pcrenI he:i :-Lc|cnce-hi gh| i ghI ing when Ihe cur:cr i : p|ccec Ic Ihe ri ghI cf cny ri ghI pcrenIhe:i :, LrcckeI, cr Lrcce.
24
Ihe mo| n[} Funct| on /fI er funcIicn: hcve Leen ccwn|cccec I c c Lccrc, Ihey ccn Le invckec frcm lC :c | cng c: I he Lccrc i: ccnnecIec. l f cne cf Ihe funcIi cn: i: ncmec mcin{), iI ccn Le run cirecI| y frcm Ihe inI erfcce c: ncIec ecr|i er, cnc cIherwi:e wi|| Le run cuI cmcI icc|| y when Ihe Lccrc i: re:eI. NcI e: I c re:eI Ihe Hcncy 8ccrc wiIhcuI runni ng I he mcin{) funcIi cn {fcr in:Icnce, when hccki ng Ihe Lccrc Lcck I c Ihe ccmpuIer), hc|c ccwn Ihe Lccrc': Stort LuIIcn whi| e ccIivcIing Ihe Lccrc. Ihe Lccrc wi|| I hen re:eI wiIhcuI runni ng mcin{). IC ver sus Stondord C Ihe lC prcgrcmming |cngucge i: Lc:ec | cc:e| y cn /NSl C. Hcwever, Ihere cre mcjcr cifference:. Mcny cf Ihe:e ci fference: cri:e frcm I he ce:ire I c hcve lC Le :cfer Ihcn :I cnccrc C. Fcr in:I cnce, i n lC, crrcy Lcunc: cre checkec cI run Iime: fcr Ihi: rec:cn, crrcy: ccnncI Le ccnverI ec Ic pcinI er: i n lC. /|:c, in lC, pcinI er criI hmeIi c i: ncI c|| cwec. CIher cifference: cre cue Ic I he ce:i re IhcI Ihe lC runIime Le :mc| | cnc effi ci enI . Fcr in:I cnce, Ihe lC pri nIf funcI i cn cce: ncI uncer:Icnc mcny cf Ihe mcre excI ic fcrmcI Iing cpI icn: :peci fiec Ly /NSl C. YeI cI her ci fference: cre cue I c I he ce:i re IhcI lC Le :imp|er Ihcn :Icnccrc C. Ihi : i: Ihe rec:cn fcr Ihe g| cLc| :ccpe cf c| | cec| crcIi cn:. ln Ihe re:I cf Ihi: cccumenI, when we refer I c C, Ihe :IcIemenI cpp|i e: Ic LcIh lC cnc :Icnccrc C. When we wi:h I c :peci fy cne cr I he cIher, we wi|| refer I c eiIher lC cr :Icnccrc C. When nc :uch uc|i fier: cre pre:enI , ycu :hcu|c c::ume I hcI we cre I c| king cLcuI lC.
25
A Qu|ck C Iutor|o| Mc:I C prcgrcm: ccn:i :I cf funcI i cn cefiniIicn: cnc ccIc :I rucIure:. Here i : c :imp| e C prcgrcm IhcI cefi ne: c :ing| e funcIi cn, cc|| ec mo| n. /* S| np|e excnp|e |C F|cg|cnne|': /cnuc| */ vcic mcin{) { prinIf{He|| c, wcr|cl\n): // Scnetn| ng :|np| e } Ihe expre::i cn /* <t ext > */ fcrm: c nu|t | -||ne cr c|ccket ec ccnnent . ln ccnIrc:I , IexI IhcI :IcrI: wiIh // fcrm: c :| ng| e || ne ccnnent, which ccnIinue: cn|y I c Ihe enc cf Ihe |i ne. CcmmenI: cre i gncrec Ly lC when Ihe prcgrcm i: ccmpi |ec. /|| funcIi cn: mu:I hcve c reIurn Iype. Si nce mo|n cce: ncI reI urn c vc|ue, iI u:e: vcic, Ihe nu|| Iype, c: iI: reIurn Iype. CIher Iype: inc|uce i nI eger: {i nI) cnc f| ccI ing pci nI numLer: {f|ccI). Ihi: |unct | cn cec|c|ct | cn i nfcrmcI i cn mu:I precece ecch funcIicn cefiniIi cn. lmmecicI e|y fc|| cwing Ihe funcI icn cec|crcIicn i : I he funcIi cn' : ncme {in Ihi: cc:e, mo|n). NexI, in pcrenIhe:e:, cre cny crgumenI: {cr inpuI :) I c Ihe funcIi cn. mo|n hc: ncne, LuI cn empIy :eI cf pcrenIhe:e: i : :Ii|| reuirec. /fI er Ihe funcIi cn crgumenI : i : cn cpen cur|y-Lrcce {. Ihi: :i gni fi e: Ihe :IcrI cf Ihe ccIuc| funcIicn ccce. Cur| y-Lrcce: :ignify prcgrcm c| cck:, cr chunk: cf ccce. NexI ccme: c :eri e: cf C :t ct enent:. SIcIemenI: cemcnc IhcI :cme ccIi cn Le Icken. Cur cemcn:I rcIi cn prcgrcm hc: c :ing|e :IcI emenI, c prinIf {fcrmcII ec pri nI). Ihi: wi| | prinI Ihe me::cge "He||o, wor| dI" Ic Ihe LCD ci:p|cy. Ihe \n i nci ccI e: enc-cf-|ine. Ihe prinI f :IcI emenI enc: wiIh c :emi cc| cn {:). A|| C :IcIemenI: mu:I Le encec Ly c :emi cc| cn. 8eginni ng C prcgrcmmer: ccmmcn|y mcke I he errcr cf cmiIIi ng Ihe :emi cc|cn IhcI i : reuirec I c enc ecch :IcIemenI.
26
Ihe mo|n funcIi cn i: encec Ly I he c| c:e cur|y-Lrcce }. LeI ': | cck cI cn cncI her excmp|e Ic | ecrn :cme mcre fecIure: cf C. Ihe fc| |cwing ccce cefi ne: Ihe funcIi cn :quc| e, whi ch reIurn: Ihe mcIhemcIi cc| :ucre cf c numLer. inI :ucre{inI n) { reIurn{n * n): } Ihe funcIi cn i : cec|crec c: Iype inI, which mecn: IhcI iI wi|| reIurn cn inI eger vc|ue. NexI ccme: Ihe funcI icn ncmec squor e, fc|| cwec Ly iI : crgumenI |i :I i n pcrenI he:e:. :ucre hc: cne crgumenI, n, whi ch i: cn inI eger. NcI i ce hcw cec|cri ng Ihe I ype cf Ihe crgumenI i : ccne :imi|cr| y Ic cec| cring I he Iype cf Ihe funcI i cn. When c funcIicn hc: crgumenI : cec|crec, Ihc:e crgumenI vcricL| e: cre vc|ic wiIhin Ihe :ccpe cf Ihe funcIi cn {i .e., I hey cn|y hcve mecning wiIhin I he funcIi cn': cwn ccce). CIher funcIi cn: mcy u:e Ihe :cme vcricL| e ncme: incepencenI|y. Ihe ccce fcr squor e i: ccnIci nec wiIhin Ihe :eI cf cur| y Lrcce:. ln fccI, iI ccn:i :I: cf c :i ng| e :IcI emenI : Ihe reIurn :IcI emenI. Ihe reIurn :IcI emenI exi I: Ihe funcIi cn cnc reIurn: Ihe vc|ue cf Ihe C exp|e::| cn IhcI fc|| cw: iI {i n Ihi: cc:e n * n). ExcepI where grcupec Ly pcrenIhe:e:, expre::i cn: cre evc|ucI ec ccccrcing I c c :eI cf prececence ru| e: c::ccicIec wiIh Ihe vcricu: cpercI icn: wiIhi n Ihe expre::i cn. ln Ihi: cc:e, Ihere i : cn|y cne cpercIi cn {mu|I ip|iccIi cn), :i gni fi ec Ly I he *, :c prececence i: ncI cn i::ue. LeI ': |cck cI cn excmp| e cf c funcIi cn IhcI perfcrm: c funcIi cn cc|| I c Ihe :ucre prcgrcm. f| ccI hypcI enu:e{inI c, inI L) { f|ccI h: h = :rI{{f| ccI){:ucre{c) + :ucre{L))): reIurn{h): }
27
Ihi: ccce cemcn:I rcI e: :everc| mcre fecIure: cf C. Fi r:I, ncIice I hcI Ihe f| ccI ing pci nI vcricL|e h i: cefinec cI Ihe Leginning cf Ihe hypotenuse funcIicn. ln generc|, whenever c new prcgrcm L| cck {i nci ccI ec Ly c :eI cf cur| y Lrcce:) i: Legun, new |ccc| vcricL| e: mcy Le cefi nec. Ihe vc|ue cf h i: :eI Ic I he re:u|I cf c cc| | I c Ihe :rI funcIi cn. lI I urn: cuI IhcI :rI i : c Lui |I-in lC funcIicn IhcI Icke: c f|ccIing pci nI numLer c: iI : crgumenI. We wcnI Ic u:e Ihe squore funcIicn we cefinec ecr|i er, whi ch reIurn: iI: re:u|I c: cn inIeger. 8uI Ihe :rI funcI i cn reuire: c f| ccIi ng pcinI crgumenI. We geI crcunc Ihi : I ype inccmpcIi Li| iIy Ly ccercing Ihe inIeger :um [squore[o} + squor e[b}} i nI c c f| ccI Ly prececing iI wiIh I he ce:irec Iype, in pcrenIhe:e:. Ihu:, Ihe i nI eger :um i: mcce inI c c f| ccI ing pcinI numLer cnc pc::ec c| cng I c :rI . Ihe hypotenuse funcI i cn fini :he: Ly reI urning Ihe vc|ue cf h. Ihi: ccnc|uce: I he Lri ef C IuI cric|. Doto Obj ects VcricL| e: cnc ccn:IcnI: cre Ihe Lc:i c ccIc cLj ecI : in c C prcgrcm. Dec|crcI i cn: |i:I Ihe vcricL|e: I c Le u:ec, :I cIe whcI Iype I hey cre, cnc mcy :eI Iheir iniI ic| vc|ue.
28
Vor| ob|es VcricL| e ncme: cre cc:e- :en:iIive. Ihe uncer:ccre chcrccI er i: c| |cwec cnc i : cfIen u:ec Ic enhcnce Ihe recccLi| iIy cf | cng vcricL| e ncme:. C keywcrc: | i ke i f, whi| e, eI c. mcy ncI Le u:ec c: vcricL| e ncme:. FuncIi cn: cnc g|cLc| vcricL| e: mcy ncI hcve Ihe :cme ncme. ln ccciIi cn, i f c | ccc| vcricL|e i : ncmec Ihe :cme c: c funcIi cn cr c g|cLc| vcricL| e, I he | ccc| u:e Icke: prececence: ie., u:e cf Ihe funcIi cn cr g| cLc| vcricL| e i: prevenIec wiIhin Ihe :ccpe cf Ihe |ccc| vcricL|e. Dec| orot|on ln C, vcricL|e: ccn Le cec|crec cI Ihe I cp |eve| {cuI :ice cf cny cur|y Lrcce:) cr cI Ihe :IcrI cf ecch L|cck {c funcIicnc| uniI cf ccce :urrcuncec Ly cur|y Lrcce:). ln generc| , c vcricL| e cec| crcI i cn i: cf Ihe fcrm: <type> <vc|| cc| e-ncne>: cr <type> <vc|| cc| e-ncne>=<| n| t | c|| zct| cn-cct c>: ln lC, <type> ccn Le inI, |cng, f|ccI, chcr, cr :IrucI <:t |uct -ncne>, cnc ceI ermine: Ihe p|| nc|y t ype cf Ihe vcricL| e cec|crec. Ihi: fcrm chcnge: :cmewhcI when cec|ing wiIh pci nI er cnc crrcy cec|crcIi cn:, which cre exp|cinec in c |cI er :ecIi cn, LuI i n generc| Ihi : i: Ihe wcy ycu cec|cre vcricL|e:. Loco| ond G| obo| Scopes lf c vcri cL| e i: cec|crec wiIhi n c funcIi cn, cr c: cn crgumenI I c c funcI icn, iI: Lincing i: | ccc|, mecning IhcI Ihe vcricL|e hc: exi:I ence cn| y wiIhin IhcI funcIicn cefi niIicn. l f c vcricL| e i: cec|crec cuI:ice cf c funcIi cn, iI i : c g| ccc| vcricL|e. lI i: cefi nec fcr c| | funcIicn:, inc|ucing funcIi cn: which cre cefinec i n fi |e: cI her Ihcn Ihe cne i n which Ihe g| cLc| vcricL|e wc: cec|crec.
29
Vor| ob|e In|t| o||zot| on Lccc| cnc g| cLc| vcricL| e: ccn Le iniIic| izec Ic c vc|ue when Ihey cre cec|crec. lf nc iniIic|izcIi cn vc|ue i : given, I he vcricL| e i : i niI ic| izec Ic zerc. /|| g|cLc| vcricL|e cec|crcI i cn: mu:I Le iniIi c|izec I c ccn:IcnI vc|ue:. Lccc| vcricL| e: mcy Le iniIic| izec Ic Ihe vc|ue cf crLi Ircry expre::i cn: inc|ucing cny g|cLc| vcricL|e:, funcIicn cc| |:, funcIi cn crgumenI :, cr | ccc| vcricL| e: which hcve c| reccy Leen iniI ic|izec. Here i : c :mc| | excmp| e cf hcw iniI ic| izec cec|crcI i cn: cre u:ec. inIi=50: /* cec|c|e | c: g| ccc| | nt ege|. | n| t | c| vc| ue 50 */ |cngj=100L: /* cec|c|e c: g| ccc| |cng. | n| t | c| vc|ue !00 */ inI fcc{) { inIx: /* cec|c| e x c: | ccc| | ntege|. | n| t| c| vc|ue 0 */ | cngy=j : /* cec|c|e y c: | ccc| | nt ege|. | n| t | c| vc|ue */ } Lccc| vcricL|e: cre iniI ic| izec whenever Ihe funcI icn ccnIcini ng Ihem i: execuIec. G|cLc| vcricL|e: cre iniI ic|izec whenever c re:eI ccnciIi cn cccur:. Fe:eI ccnciIi cn: cccur when: 1. Ccce i : ccwn|cccec: 2. Ihe mo|n[} prccecure i : run: 3. Sy:I em hcrcwcre re:eI cccur:.
30
Fers|stent G| obo| Vor| ob|es / :pecic| per:i:IenI fcrm cf g|cLc| vcricL| e, hc: Leen imp| emenIec fcr lC. / per:i:I enI g| cLc| vcricL| e mcy Le i niI ic| izec ju:I |i ke cny cIher g| cLc| vcricL|e, LuI iI : vc|ue i : cn| y i niI ic| izec when Ihe ccce i : ccwn| cccec cnc ncI cn cny cIher re:eI ccnciIi cn:. lf nc iniI ic| izcI icn infcrmcI icn i : inc| ucec fcr c per:i :I enI vcricL|e, iI : vc|ue wi|| Le iniIic|izec I c zerc cn ccwn| ccc, LuI | efI unchcngec cn c|| cIher re:eI ccnciIi cn:. Ic mcke c per:i:I enI g| cLc| vcricL|e, prefix Ihe Iype :peci fier wiIh Ihe keywcrc per:i:I enI. Fcr excmp| e, Ihe :IcI emenI per:i:I enI i nI i =500: crecIe: c g| cLc| inI eger cc|| ec | wiIh Ihe iniIic| vc|ue 500. Fer:i:I enI vcricL| e: keep Ihei r :IcI e when Ihe Lccrc i : Iurnec cff cnc cn, when mo|n i: run, cnc when :y:Iem re:eI cccur:. Fer:i :IenI vcricL| e: wi|| |c:e Iheir :IcI e when ccce i : ccwn|cccec c: c re:u|I cf | cccing cr un|ccci ng c fi|e. Hcwever, iI i : pc::iL| e Ic recc Ihe vc|ue: cf ycur per:i :IenI vcricL|e: in lC if ycu cre :I i|| running Ihe :cme lC :e::i cn frcm which Ihe ccce wc: ccwn|cccec. ln I hi: mcnner ycu ccu|c recc Ihe finc| vc|ue: cf cc| iLrcIicn per:i :I enI vcricL|e:, fcr excmp| e, cnc mcci fy Ihe iniIic| vc|ue: given I c I hc:e per:i:IenI vcricL|e: cpprcpricIe| y. Fer:i:I enI vcricL| e: were crecIec wiIh Iwc cpp|i ccI icn: in mi nc: Cc|iLrcIi cn cnc ccnfi gurcIicn vc|ue: IhcI cc ncI neec I c Le re- cc| cu|cI ec cn every re:eI ccnciIi cn. FcLcI | ecrning c| gcriI hm: IhcI mi ghI cccur cver c peri cc when Ihe rcLcI i : Iurnec cn cnc cff.
31
Constonts Integer Constonts lnIeger: ccn:IcnI: mcy Le cefinec in cecimc| inI eger fcrmcI {e.g., 4053 cr -1), hexcceci mc| fcrmcI u:ing Ihe 0x prefix {e.g., 0x1|||), cnc c ncn- :Icnccrc LuI u:efu| Lincry fcrmcI u:i ng Ihe 0b prefix {e.g., 0b1001001). CcIc| ccn:IcnI : u:ing Ihe zerc prefix cre ncI :uppcrI ec. Long Integer Constonts Lcng inIeger ccn:IcnI : cre crecIec Ly cppencing Ihe :uffix | cr L {upper- cr |cwer- cc:e c|phcLeIi c L) Ic c cecimc| inIeger. Fcr excmp|e, 0L i: Ihe | cng zerc. EiIher Ihe upper cr |cwer- cc:e L mcy Le u:ec, LuI upper- cc:e i: Ihe ccnvenIi cn fcr recccLi|iI y. F|oot|ng Fo|nt Constonts F| ccIing pcinI numLer: mcy u:e expcnenI ic| ncIcIicn {e.g., 10e3 cr 10E3) cr mcy ccnIcin c ceci mc| peri cc. Fcr excmp|e, Ihe f| ccI ing pcinI zerc ccn Le given c: 0., 0.0, cr 0E1, LuI ncI c: ju:I 0. S|nce t ne ccc|c nc: nc || cct | ng pc| nt nc|cwc| e. || cct |ng pc| nt cpe|ct | cn: c|e nucn :| cwe| t ncn | nt ege| cpe|ct | cn:. cnc :ncu| c ce u:ec :pc|| ng| y. Chorocters ond Str|ng Constonts CucIec chcrccI er: reIurn Iheir /SCll vc|ue {e.g., ' x'). ChcrccIer :Iring ccn:IcnI: cre cefinec wiIh ucIcIicn mcrk:, e.g., Ihi : i: c chcrccIer :Iring.. NbLL Ihe :pecic| ccn:IcnI NbLL hc: Ihe vc|ue cf zerc cnc ccn Le c::i gnec I c cnc ccmpcrec I c pcinI er cr crrcy vcricL|e: {which wi| | Le ce:criLec in |cIer :ecIi cn:). ln generc| , ycu ccnncI ccnverI cIher ccn:IcnI: Ic Le cf c pcinIer Iype, :c Ihere cre mcny Iime: when NbLL ccn Le u:efu| . Fcr excmp|e, i n crcer I c check if c pcinI er hc: Leen iniIic|izec ycu ccu|c ccmpcre iI : vc|ue I c NbLL cnc ncI Iry I c ccce:: iI : ccnI enI: if iI wc: NbLL. /| :c, i f ycu hcc c cefi nec c |inkec |i :I Iype ccn:i :Iing cf c vc|ue cnc c pcinIer Ic Ihe nexI e| emenI, ycu ccu| c | cck fcr Ihe enc cf Ihe |i:I Ly ccmpcring I he nexI pci nIer Ic NbLL.
1-LiI inIeger: cre :ignifi ec Ly Ihe Iype inci ccI cr inI. Ihey cre :i gnec inI eger:, cnc mcy Le vc|uec frcm - 32,78 I c +32,77 cecimc|. 32-b|t Integers 32-LiI i nIeger: cre :i gni fi ec Ly Ihe Iype i nci ccI cr | cng. Ihey cre :i gnec inI eger:, cnc mcy Le vc|uec frcm - 2,147,483,48 Ic +2,147,483,47 cecimc| . 32-b|t F| oot|ng Fo|nt Numbers F| ccIing pcinI numLer: cre :ignifi ec Ly I he Iype i nci ccI cr f| ccI . Ihey hcve cpprcximcIe|y :even cecimc| cigiI : cf preci :i cn cnc cre vc|uec frcm cLcuI 10/-38 Ic 10/38. 8-b|t Chor octers ChcrccIer: cre cn 8-LiI numLer :i gni fiec Ly I he I ype inci ccI cr chcr. / chcrccI er' : vc|ue Iypicc|| y repre:enI : c prinIcL| e :ymLc| u:i ng Ihe :Icnccrc /SCll chcrccIer ccce, LuI Ihi: i : ncI nece::cry: chcrccIer: ccn Le u:ec Ic refer I c crLiI rcry 8-LiI numLer:. Fo|nters lC pci nIer: cre 1-LiI numLer: whi ch repre:enI | cccI icn: i n memcry. Vc|ue: in memcry ccn Le mcnipu| cI ec Ly cc| cu|cIing, pc::ing cnc ce| e|e|enc| ng pci nIer: repre:enIi ng Ihe |cccIi cn where Ihe i nfcrmcI icn i: :Icrec. Arroys /rrcy: cre u:ec I c :Icre hcmcgencu: |i:I: cf ccIc {mecni ng IhcI c| | Ihe e| emenI : cf cn crrcy hcve Ihe :cme I ype). Every crrcy hc: c | engIh which i : ceI ermi nec cI Ihe Iime Ihe crrcy i : cec|crec. Ihe ccIc :Icrec in Ihe e| emenI : cf cn crrcy ccn Le :eI cnc reIrievec in I he :cme mcnner c: fcr cIher vcricL| e:.
33
Structur es SIrucIure: cre u:ec Ic :Icre ncn-hcmcgencu: LuI re|cIec :eI: cf ccIc. E|emenI: cf c :IrucIure cre referencec Ly ncme i n:I ecc cf numLer cnc mcy Le cf cny :uppcrIec Iype. SIrucIure: cre u:efu| fcr crgcni zing re|cIec ccIc inI c c ccherenI fcrmcI, recucing Ihe numLer cf crgumenI: pc::ec I c funcIi cn:, i ncrec:ing Ihe effecIive numLer cf vc|ue: which ccn Le reIurnec Ly funcI i cn:, cnc crecIing ccmp| ex ccIc repre:enI cIi cn: :uch c: ci recI ec grcph: cnc |inkec |i :I :. Fo|nters
Ihe cccre:: where c vc|ue i : :I crec i n memcry i : kncwn c: Ihe pci nIer Ic IhcI vc|ue. lI i: cfIen u:efu| I c cec| wiIh pci nIer: I c cLjecI:, LuI grecI ccre mu:I Le I cken I c in:ure IhcI Ihe pci nIer: u:ec cI cny pcinI in ycur ccce rec|| y cc pcinI I c vc|ic cLjecI : in memcry. /II empI: I c refer Ic invc|ic memcry | cccI icn: ccu|c ccrrupI ycur memcry. Mc:I ccmpuIing envircnmenI : IhcI ycu cre prcLcL|y u:ec Ic reIurn he| pfu| me::cge: |ike 'SegmenIcIicn Vic|cI i cn' cr ' 8u: Errcr' cn cII empI: Ic ccce:: i| | egc| memcry. Hcwever, ycu wcn'I hcve Ihi: :cfeIy neI cn Ihe Lccrc ycu cre ccnnecIing I c. lnvc|ic pcinI er cereferencing i: very |i ke| y Ic gc unceI ecIec, cnc wi|| |i ke|y rencer i nvc|ic ycur ccIc, ycur prcgrcm, cr even Ihe pccce inI erpreI er. Fo|nter So|ety ln pc:I ver:i cn: cf lC, ycu ccu|c ncI reIurn pcinI er: frcm funcIi cn: cr hcve crrcy: cf pci nIer:. ln crcer I c fcci |iIcIe Ihe u:e cf :IrucIure:, Ihe:e fecIure: hcve Leen cccec Ic Ihe currenI ver:i cn. WiI h Ihi: chcnge, I he numLer cf cppcrIuniIi e: Ic mi :u:e pci nIer: hcve increc:ec. Hcwever, i f ycu fc| |cw c few :i mp| e preccuIi cn: ycu :hcu|c cc fi ne. Fi r:I, ycu :hcu|c c|wcy: check IhcI Ihe vc|ue cf c pcinI er i: ncI euc| Ic NbLL {c :pecic| zerc pcinIer) Lefcre ycu Iry I c ccce:: iI . VcricL| e: whi ch cre cec|crec Ic Le pci nI er: cre iniI ic|izec I c NbLL, :c mcny uniniI ic| izec vc|ue: ccu|c Le ccughI Ihi : wcy.
34
Seccnc, ycu :hcu| c never u:e c pcinIer I c c |ccc| vcricL|e i n c mcnner which ccu| c ccu:e iI I c Le ccce::ec cfI er I he funcIi cn in whi ch iI wc: cec|crec I ermi ncI e:. When c funcIicn IermincIe: Ihe :pcce where iI : vc|ue: were Lei ng :Icrec i : recyc| ec. Iherefcre ncI cn|y mcy cereferencing :uch pcinI er: reIurn inccrrecI vc|ue:, LuI c::i gning Ic Ihc:e cccre::e: ccu| c | ecc I c :eri cu: ccIc ccrrupIicn. / gccc wcy Ic prevenI Ihi: i: I c never reI urn Ihe cccre:: cf c | ccc| vcricL| e frcm Ihe funcIicn whi ch cec|cre: iI cnc never :I cre I hc:e pci nIer: in cn cLjecI which wi|| |ive |cnger Ihcn Ihe funcIi cn iI:e|f {c g| cLc| pcinIer, crrcy, cr :IrucI). G|cLc| vcricL| e: cnc vcricL|e: |ccc| I c mcin wi|| ncI mcve cnce cec|crec cnc I heir pci nIer: ccn Le ccn:icerec I c Le :ecure. Ihe Iype checking ccne Ly lC wi|| he|p prevenI mcny mi :hcp:, LuI iI wi|| ncI ccIch c|| errcr:, :c Le ccrefu|. Fo|nter Dec| orot|on ond bse / vcricL| e which i : c pci nIer Ic cn cLj ecI cf c given Iype i : cec|crec i n Ihe :cme mcnner c: c regu|cr cLj ecI cf I hcI I ype, LuI wiIh cn exI rc * in frcnI cf I he vcricL|e ncme. Ihe vc|ue :Icrec cI Ihe | cccIi cn Ihe pci nIer refer: I c i: ccce::ec Ly u:ing I he * cpercIcr Lefcre Ihe expre::i cn whi ch cc|cu|cI e: I he pcinIer. Ihi : prcce:: i: kncwn c: cereferenci ng. Ihe cccre:: cf c vcricL| e i: cc| cu|cIec Ly u:ing Ihe & cpercI cr Lefcre IhcI vcricL| e, crrcy e|emenI, cr :IrucIure e|emenI reference. Ihere cre Iwc mcin ci fference: LeIween hcw ycu wcu|c u:e c vcricL|e cf c given Iype cnc c vcricL| e cec|crec c: c pcinI er I c I hcI Iype. Fcr Ihe fc| |cwing exp|cncI i cn, ccn:icer X cnc Xptr c: cefi nec c: fc||cw::
35
| cng X: | cng *XpIr: Spcce /|| cccIi cn -- Dec|cri ng cn cLj ecI cf c given Iype, c: X i: cf Iype | cng, c|| cccI e: Ihe :pcce neecec Ic :I cre IhcI vc|ue. 8eccu:e cn lC |cng Icke: fcur LyIe: cf memcry, fcur LyI e: cre re:ervec fcr Ihe vc|ue cf X Ic cccupy. Hcwever, c pcinIer |i ke Xptr cce: ncI hcve Ihe :cme cmcunI cf :pcce c| | cccI ec fcr iI IhcI i: neecec fcr cn cLjecI cf Ihe Iype iI pcinI: I c. Iherefcre i I ccn cn|y :cfe|y refer I c :pcce which hc: c|reccy Leen c|| cccI ec fcr g| cLc|: {i n c :pecic| :ecIi cn cf memcry re:ervec fcr g|cLc| :) cr | ccc| : {I empcrcry :I crcge cn Ihe :Icck). lniIic| Vc| ue -- lI i: c|wcy: :cfe I c refer I c c ncn-pcinIer Iype, even i f iI hc:n'I Leen iniI ic|izec. Hcwever pcinIer: hcve Ic Le :pecifi cc| |y c::i gnec Ic Ihe cccre:: cf |egc|| y c|| cccI ec :pcce cr Ic Ihe vc|ue cf cn c| reccy iniI ic| izec pcinI er Lefcre Ihey cre :cfe Ic u:e. Sc, fcr excmp| e, ccn:icer whcI wcu|c hcppen i f Ihe fir:I Iwc :IcI emenI: cfI er X cnc Xptr were cec|crec were I he fc|| cwing: X=50L: *XpIr=50L: Ihe fi r:I :IcI emenI i: vc|ic: iI :eI: I he vc|ue cf X I c 50L. Ihe :eccnc :IcI emenI wcu|c Le vc|ic if Xptr hcc Leen prcper|y iniI ic| izec, LuI in Ihi: cc:e iI hc: ncI . Iherefcre, Ihi: :IcI emenI wcu|c ccrrupI memcry. Here i : c :euence cf ccmmcnc: ycu ccu|c I ry which i ||u:I rcI e hcw pcinIer: cnc Ihe * cnc & cpercIcr: cre u:ec. lI c| :c :hcw: IhcI cnce c pcinI er hc: Leen :eI Ic pcinI cI c p|cce in memcry, reference: I c iI ccIuc|| y :hcre I he :cme memcry c: Ihe cLjecI iI pcinI : I c: X=50L: /* :et t ne nenc|y c|| ccctec |c| X tc 50 */ XpIr=&X: /* :et Xpt| t c pc| nt t c nenc|y ccc| e:: c| X */ prinIf{7c ,*XpIr): /* ce| e|e| ence Xpt |. vc|ue ct ccc|e:: | : 50 */ X=100L: /* :et X t c t ne vc|ue !00 */ prinIf{7c ,*XpIr): /* ce| e|e| ence cgc| n. vc|ue | : ncw !00 */ *XpIr=200L: /* :et vc| ue ct ccc|e:: g| ven cy Xpt | t c 200 */ prinIf{7c\n,X): /* cneck tnct t ne vc| ue c| X cncngec t c 200 */ Foss|ng Fo|nters os Ar guments Fci nIer: ccn Le pc::ec Ic funcI icn: cnc funcI i cn: ccn chcnge I he vc|ue: cf Ihe vcricL|e: IhcI cre pcinI ec cI. Ihi: i : Iermec cc||-cy-|e|e|ence: c reference, cr pcinIer, I c c vcricL| e i: given I c Ihe funcI icn IhcI i: Lei ng cc||ec. Ihi: i : in ccnIrc:I I c cc||-cy-vc|ue, Ihe :Icnccrc wcy IhcI funcI i cn: cre cc|| ec, in which Ihe vc|ue cf c vcricL| e i : given Ihe I c funcIicn Lei ng cc| | ec.
36
Ihe fc|| cwing excmp| e cefine: cn over oge_sensor funcIi cn which Icke: c pcrI numLer cnc c pcinI er I c cn i nIeger vcricL| e. Ihe funcIi cn wi|| cvercge Ihe :en:cr cnc :Icre Ihe re:u|I in Ihe vcricL| e pcinIec cI Ly resu|t. Frefixing cn crgumenI ncme wiIh * cec|cre: IhcI Ihe crgumenI i: c pci nIer. vcic cvercge_:en:cr{inI pcrI, inI *re:u|I) { i nI :um = 0: i nI i : fcr {l = 0: l < 10: i ++) :um += cnc|cg{pcrI): *re:u|I = :um/10: } NcIi ce IhcI I he funcIi cn iI:e| f i: cec| crec c: c vcic. lI cce: ncI neec I c reI urn cnyIhi ng, Leccu:e iI in:Iecc :I cre: iI: cn:wer in Ihe memcry | cccIi cn given Ly Ihe pcinI er vcricL|e IhcI i: pc::ec Ic iI. Ihe pcinI er vcricL|e i : u:ec in I he |c:I |ine cf Ihe funcIi cn. ln I hi : :IcI emenI , Ihe cn:wer :um/10 i: :Icrec cI Ihe | cccIicn pcinIec cI Ly re:u|I. NcIi ce IhcI Ihe * i: u:ec Ic c::i gn c vc|ue I c Ihe | cccIi cn pcinIec Ly re:u| I. keturn| ng Fo|nters |rom Funct|ons Fci nIer: ccn c|:c Le reIurnec frcm funcIicn:. FuncI i cn: cre cefi nec I c reIurn pcinI er: Ly preceecing Ihe ncme cf Ihe funcI i cn wiIh c :I cr, ju:I | i ke cny cIher Iype cf pci nIer cec|crcIi cn. inI ri ghI,| efI: inI *cirpIr{inI ci r) { if {cir==0) { reI urn{&righI): } if {cir==1) { reIurn{&|efI ): } reIurn{NULL): } Ihe funcI i cn d|r ptr reIurn: c pcinIer I c Ihe g| cLc| r| ght when iI : crgumenI d|r i: 0, c pci nIer Ic | e|t when iI : crgumenI i: 1, cnc NbLL" i f iI: crgumenI i : cIher Ihcn 0 cr 1.
37
Arroys lC :uppcrI: crrcy: cf chcrccI er:, inIeger:, | cng inI eger:, f| ccIi ng-pci nI numLer:, :IrucI ure:, pci nIer:, cnc crrcy pcinI er: {mu|Ii- cimen:i cnc| crrcy:). Whi|e un| i ke regu|cr C crrcy: i n c numLer cf re:pecI:, I hey ccn Le u:ec in c :imi |cr mcnner. Ihe mcin rec:cn: IhcI crrcy: cre u:efu| cre IhcI Ihey c| |cw ycu I c c||cccI e :pcce fcr mcny in:Icnce: cf c given Iype, :enc cn crLiIrcry numLer cf vc|ue: I c funcI icn:, cnc prcvice Ihe mecn: fcr iIercIing cver c :eI cf vc|ue:. /rrcy: in lC cre cifferenI cnc inccmpcIiL| e wiIh crrcy: in cIher ver:i cn: cf C. Ihi: inccmpcIi Li| iIy i : ccu:ec Ly I he fccI IhcI reference: I c lC crrcy: cre checkec Ic i n:ure I hcI Ihe reference i: Iru|y wiIhin Ihe Lcunc: cf IhcI crrcy. ln crcer I c ccccmp|i:h Ihi : checki ng in Ihe generc| cc:e, iI i: nece::cry IhcI Ihe :ize cf Ihe crrcy Le :I crec wiIh Ihe ccnI enI: cf Ihe crrcy. |t | : | npc|t cnt t c |enence| t nct cn c||cy c| c g|ven t ype cnc c pc| nte| tc tne :cne t ype c|e | nccnpct | c|e type: | n |C. wne|ec: t ney c| e | c|ge|y | nt e|cncngecc| e | n |egu|c| C. Dec| or|ng ond In|t| o||z|ng Arroys /rrcy: cre cec|crec u:ing :ucre LrcckeI:. Ihe fc|| cwing :IcI emenI cec|cre: cn crrcy cf Ien inI eger:: inI fcc|10]: ln Ihi: crrcy, e|emenI: cre numLerec frcm 0 Ic . E| emenI : cre ccce::ec Ly enc| c:i ng Ihe incex numLer wiIhin :ucre LrcckeI :: |oo[4] cencI e: Ihe fi fIh e|emenI cf Ihe crrcy fcc {:ince ccunIi ng Legin: cI zerc). /rrcy: cre iniIic|izec Ly cefcu|I Ic ccnIcin c|| zerc vc|ue:. /rrcy: mcy c| :c Le iniIic|izec cI cec|crcIi cn Ly :pecifying Ihe crrcy e| emenI:, :epcrcI ec Ly ccmmc:, wiIhin cur| y Lrcce:. lf nc :ize vc|ue i: :peci fi ec wiIhi n Ihe :ucre LrcckeI : when I he crrcy i: cec|crec LuI iniI ic|izcIi cn i nfcrmcIi cn i: given, I he :ize cf Ihe crrcy i: ceI erminec Ly Ihe numLer cf e|emenI: given i n Ihe cec|crcIi cn. Fcr excmp| e,
38
inI fcc|]= {0, 4, 5, -8, 17, 301}: crecIe: cn crrcy cf :ix inI eger:, wiIh |oo[0] euc|ing 0, |oo[1] euc|i ng 4, eI c. lf c :ize i : :peci fi ec cnc i niI ic|izcIi cn ccIc i: given, Ihe | engI h cf I he iniIic|izcIi cn ccIc mcy ncI exceec Ihe :peci fiec |engIh cf Ihe crrcy cr cn errcr re:u|I :. lf, cn I he cIher hcnc, ycu :peci fy Ihe :ize cnc prcvice fewer i niI ic| izcIi cn e| emenI : Ihcn I he IcI c| | engIh cf Ihe crrcy, Ihe remcining e| emenI: cre iniIic|izec I c zerc. ChcrccIer crrcy: cre Iypi cc| |y I exI :I ring:. Ihere i : c :pecic| :ynIcx fcr iniIic|izing crrcy: cf chcrccIer:. Ihe chcrccIer vc|ue: cf Ihe crrcy cre enc| c:ec i n ucI cIi cn mcrk:: chcr :Iring|]= He| | c Ihere: Ihi: fcrm crecI e: c chcrccI er crrcy cc|| ec str|ng wiIh Ihe /SCll vc|ue: cf Ihe :pecifiec chcrccIer:. ln ccciI icn, Ihe chcrccIer crrcy i : I ermincI ec Ly c zerc. 8eccu:e cf Ihi : zerc- IermincIi cn, Ihe chcrccIer crrcy ccn Le I recI ec c: c :I ring fcr purpc:e: cf prinIi ng {fcr excmp|e). ChcrccI er crrcy: ccn Le iniIic|izec u:ing Ihe cur| y Lrcce: :ynIcx, LuI Ihey wi|| ncI Le cuIcmcI icc||y nu| |-IermincI ec i n IhcI cc:e. ln generc| , pri nIi ng cf chcrccIer crrcy: IhcI cre ncI nu| |-I ermincIec wi|| ccu:e prcL|em:. Foss|ng Arroys os Ar guments When cn crrcy i: pc::ec I c c funcIi cn c: cn crgumenI , Ihe crrcy': pcinI er i : ccIuc||y pc::ec, rcIher I hcn Ihe e| emenI : cf Ihe crrcy. l f Ihe funcIi cn mccifie: Ihe crrcy vc|ue:, Ihe crrcy wi|| Le mcci fi ec, :ince Ihere i : cn|y cne ccpy cf Ihe crrcy in memcry. ln ncrmc| C, Ihere cre Iwc wcy: cf cec|cring cn crrcy crgumenI : c: cn crrcy cr c: c pci nIer Ic Ihe I ype cf Ihe crrcy' : e| emenI:. ln lC crrcy pcinIer: cre inccmpcIiL| e wiIh pci nIer: I c Ihe e| emenI : cf cn crrcy :c :uch crgumenI : ccn cn|y Le cec|crec c: crrcy:. /: cn excmp| e, Ihe fc| |cwing funcIicn Icke: cn i ncex cnc cn crrcy, cnc reIurn: Ihe crrcy e|emenI :pecifi ec Ly Ihe incex: inI reIrieve_e| emenI {inI i ncex, i nI crrcy|]) { reIurn crrcy|incex]: } NcIi ce Ihe u:e cf Ihe :ucre LrcckeI: I c cec|cre Ihe crgumenI crrcy c: c pcinIer I c cn crrcy cf inI eger:.
39
When pc::ing cn crrcy vcricL|e I c c funcIi cn, ycu cre ccIuc||y pc::i ng Ihe vc|ue cf Ihe crrcy pcinI er iI:e| f cnc ncI cne cf iI: e| emenI :, :c nc :ucre LrcckeI : cre u:ec. vcic fcc{) { inI crrcy|10]: reIri eve_e|emenI{3, crrcy): }
Mu|t|-d| mens|ono| Arroys
/ Iwc-cimen:icnc| crrcy i: ju:I |i ke c :i ng| e ci men:i cnc| crrcy whc:e e| emenI : cre cne- cimen:i cnc| crrcy:. Dec| crcI i cn cf c Iwc-ci men:i cnc| crrcy i: c: fc||cw:: inI k|2]|3]: Ihe numLer i n Ihe fi r:I :eI cf LrcckeI : i: I he numLer cf 1-D crrcy: cf i nI. Ihe numLer i n Ihe :eccnc :eI cf LrcckeI: i: Ihe |engIh cf ecch cf Ihe 1- D crrcy: cf inI. ln Ihi: excmp|e, k i : cn crrcy ccnIcining Iwc 1-D crrcy:: k[0] i : c 1-D crrcy cf cc|cr=L|ue>inI cf | engI h 3: k[0][1] i : cn cc| cr=L|ue>inI. /rrcy: cf wiIh cny numLer cf cimen:i cn: ccn Le generc|izec frcm Ihi: excmp|e Ly cccing mcre LrcckeI : i n Ihe cec|crcIi cn. Determ| n|ng the s|ze o| Arroys ot kunt| me /n ccvcnIcge cf Ihe wcy lC cec| : wiIh crrcy: i : IhcI ycu ccn ceIermi ne I he :ize cf crrcy: cI runIime. Ihi: c|| cw: ycu I c cc :ize checki ng cn cn crrcy if ycu cre uncerIci n cf iI : cimen:i cn: cnc pc::iL|y prevenI ycur prcgrcm frcm crc:hing. S| nce _orroy_s| ze | : nct c :t cncc|c C |ectu|e. ccce w|| tten u:| ng tn| : p||n|t| ve w| || cn|y ce cc| e t c ce ccnp||ec w|t n |C. Ihe _orr oy_s|ze primiIive reIurn: Ihe :ize cf Ihe crrcy given I c iI regcrc| e:: cf Ihe ci men:icn cr Iype cf Ihe crrcy. Here i : cn excmp| e cf cec|crcIi cn: cnc i nI erccI i cn wiIh Ihe _orr oy_s|ze pri miIive:
40
inI i|4]={10,20,30}: inI j|3]|2]={{1,2},{2,4},{15}}: inI k|2]|2]|2]: _crrcy_:ize{i): /* |et u|n: 4 */ _crrcy_:ize{j): /* |et u|n: 3 */ _crrcy_:ize{j|0]): /* |et u|n: 2 */ _crrcy_:ize{k): /* |et u|n: 2 */ _crrcy_:ize{k|0]): /* |etu|n: 2 */ Structur es SIrucIure: cre u:ec I c :I cre ncn-hcmcgencu: LuI re|cIec :eI: cf ccIc. E| emenI : cf c :IrucIure cre referencec Ly ncme in:I ecc cf numLer cnc mcy Le cf cny :uppcrIec I ype. SIrucIure: cre u:efu| fcr crgcni zing re|cI ec ccIc inI c c ccherenI fcrmcI, recucing Ihe numLer cf crgumenI: pc::ec I c funcIi cn:, increc:ing Ihe effecIive numLer cf vc|ue: which ccn Le reIurnec Ly funcIi cn:, cnc crecIi ng ccmp| ex ccIc repre:enI cIi cn: :uch c: cirecI ec grcph: cnc |i nkec |i :I:. Ihe fc|| cwing excmp| e :hcw: hcw Ic cefine c :I rucIure, cec|cre c vcricL| e cf :I rucI ure Iype, cnc ccce:: iI: e| emenI :. :IrucI fcc { inI i: inI j: }: :IrucI fcc f1: vcic :eI_f1{i nI i ,inI j) { f1.i =i: f1.j =j: } vcic geI_f1{inI *i,inI *j) { *i=f1.i: *j=f1.j : }
41
Ihe fi r:I pcrI i: Ihe :IrucIure cefiniIi cn. lI ccn:i:I : cf Ihe keywcrc :I rucI, fc|| cwec Ly Ihe ncme cf Ihe :IrucI ure {whi ch ccn Le cny vc|ic icenI ifier), fc|| cwec Ly c |i :I cf ncmec e|emenI: in cur| y Lrcce:. Ihi : cefiniIi cn :pecifie: I he :IrucI ure cf I he Iype :IrucI |oo. Cnce Ihere i: c cefiniIi cn cf Ihi : fcrm, ycu ccn u:e Ihe Iype :IrucI |oo ju:I | i ke cny cIher Iype. Ihe |ine :I rucI fcc f1: i: c g| cLc| vcricL|e cec|crcI i cn whi ch cec|cre: Ihe vcricL| e |1 I c Le cf I ype :IrucI |oo. Ihe ccI cpercI cr i : u:ec I c ccce:: Ihe e|emenI: cf c vcricL| e cf :IrucIure I ype. ln Ihi : cc:e, |1.| cnc |1.j refer Ic Ihe Iwc e| emenI: cf |1. Ycu ccn IrecI Ihe ucnIiI ie: |1.| cnc |1.j ju:I c: ycu wcu|c I recI cny vcricL|e: cf Iype inI {Ihe Iype cf Ihe e| emenI: wc: cefinec in Ihe :IrucIure cec|crcIi cn cI I he I cp Ic Le inI). Fci nIer: I c :I rucIure I ype: ccn c|:c Le u:ec, ju:I |i ke pcinI er: I c cny cI her Iype. Hcwever, wiIh :IrucIure:, Ihere i : c :pecic| :hcrI-cuI fcr referri ng Ic I he e|emenI: cf Ihe :I rucI ure pci nIec I c. :IrucI fcc *fpIr: vcic mci n{) { fpI r=&f1: fpI r->i=10: fpI r->j=20: } ln Ihi : excmp| e, |ptr i: cec|crec I c Le c pcinIer I c Iype :I rucI |oo. ln mcin, iI i : :eI I c pci nI Ic Ihe g| cLc| |1 cefinec cLcve. Ihen Ihe e| emenI: cf Ihe :IrucIure pci nIec I c Ly |ptr {in Ihi: cc:e Ihe:e cre Ihe :cme c: Ihe e| emenI : cf |1), cre :eI. Ihe crrcw cpercI cr i : u:ec in:I ecc cf Ihe ccI cpercI cr Leccu:e fpIr i : c pcinI er Ic c vcricL| e cf Iype :I rucI |oo. NcI e I hcI [*|ptr}.| wcu|c hcve wcrkec j u:I c: we|| c: |ptr->|, LuI iI wcu|c hcve Leen c|um:ier. NcI e IhcI cn| y pci nIer: I c :IrucIure:, ncI Ihe :IrucIure: Ihem:e|ve:, ccn Le pc::ec I c cr reI urnec frcm funcIi cn:.
42
Comp| ex In| t| o||zot|on exomp|es Ccmp| ex Iype: -- crrcy: cnc :IrucI ure: -- mcy Le iniIic|izec upcn cec|crcI i cn wiIh c :euence cf ccn:IcnI vc|ue: ccnIcinec wiIhin cur|y Lrcce: cnc :epcrcI ec Ly ccmmc:. /rrcy: cf chcrccIer mcy c|:c Le iniI ic| izec wiIh c ucI ec :I ri ng cf chcrccIer:. Fcr iniIic|izec cec| crcIi cn: cf :ing| e cimen:i cnc| crrcy:, Ihe | engI h ccn Le | efI L|cnk cnc c :uiI cL| e |engIh Lc:ec cn Ihe iniI ic| izcI icn ccI c wi|| Le c::i gnec I c iI . /u|t | -c| nen:| cnc| c||cy: nu:t ncve t ne :| ze c| c|| c|nen:|cn: :pec||| ec wnen t ne c||cy | : cec|c| ec. lf c | engIh i: :peci fiec, I he i niI ic| izcIi cn ccI c mcy ncI cverf| cw IhcI | engI h in cny ci men:i cn cr cn errcr wi|| re:u|I. Hcwever, Ihe i niI ic|izcIi cn ccIc mcy Le :hcrI er Ihcn Ihe :peci fiec :i ze cnc Ihe remci ning enIri e: wi|| Le ini Iic|izec Ic 0. Fc|| cwing i: cn excmp| e cf | egc| g|cLc| cnc | ccc| vcricL|e iniIi c|izcIicn:: /* cec|c|e ncny g|ccc|: c| vc|| cu: t ype: */ inI i=50: inI *pIr=NULL: f| ccI fcrr|3]={ 1.2, 3., 7.4 }: inI Icrr|2]|4]={ { 1, 2, 3, 4 }, { 2, 4, , 8} }: chcr c|]=Hi Ihere hcw cre ycu: chcr ccrr|5]|10]={Hi ,Ihere,hcw,cre,ycu}: :IrucI Lcr { i nI i : i nI *p: | cng j : } L={5, NULL, 10L}: :IrucI Lcr Lcrr|2] = { { 1, NULL, 2L }, { 3 } }: /* cec|cre | ccc|: cf vcri cu: Iype: */ inI fcc{) { i nI x: /* |ccc| vc||cc|e x w| tn | n|t| c| vc|ue 0 */ i nI y= Icrr|0]|2]: /* |ccc| vc|| cc|e y w|t n |n| t|c| vc| ue 3 */ i nI *ipIr=&i: /* |ccc| pc| nt e| t c |nt ege| wn| cn pc| nt : tc t ne g| ccc| | */ i nI | crr|2]={10,20}: /* |ccc| c||cy |c|| w| tn e| enent : !0 cnc 20 */ :IrucI Lcr | L={5,NULL,10L}: /* |ccc| vc|| cc|e c| t ype :t |uct cc| w| t n | =5 cnc =!0 */ chcr |c|]=ccrr|2]: /* | ccc| :t ||ng | c w| t n | n| t| c| vc|ue "ncw" */ ... }
43
Stotements ond Express|ons
CpercI cr: ccI upcn cLj ecI: cf c cerIci n Iype cr Iype: cnc :peci fy whcI i : Ic Le ccne I c Ihem. Expre::icn: ccmLine vcricL| e: cnc ccn:IcnI: I c crecIe new vc|ue:. SIcIemenI : cre expre::i cn:, c::i gnmenI :, funcI icn cc| |:, cr ccnI rc| f| cw :IcI emenI: whi ch mcke up C prcgrcm:. Operotors Ecch cf Ihe ccIc Iype: hc: iI: cwn :eI cf cpercI cr: IhcI ceIermine which cpercIicn: mcy Le perfcrmec cn I hem. Integer Oper ot|ons Ihe fc|| cwing cpercIi cn: cre :uppcrIec cn i nIeger:: Ar|thmet| c. ccciI i cn +, :uLIrccIi cn -, mu|I ip| i ccIi cn *, civi:i cn /. Compor|son. grecI er-Ihcn >, | e::-I hcn <, euc|iI y ==, grecI er-I hcn-euc| >=, | e::- Ihcn-euc| <=. 8|tw|se Ar|thmet|c. LiIwi:e-CF ], LiIwi:e- /ND &, LiIwi:e- exc|u:ive-CF /, LiIwi:e- NCI ~. 8oo| eon Ar|thmet|c. | cgi cc|-CF ]], | cgi cc|- /ND &&, | cgicc|-NCI l. When c C :IcIemenI u:e: c Lcc| ecn vc|ue {fcr excmp| e, i f), iI Icke: Ihe inI eger zerc c: mecning fc| :e, cnc cny inI eger cIher Ihcn zerc c: mecning Irue. Ihe Lcc|ecn cpercI cr: reI urn zerc fcr fc|:e cnc cne fcr Irue. 8cc| ecn cpercI cr: && cnc ]] wi|| :I cp execuIi ng c: :ccn c: I he I ruI h cf Ihe finc| expre::i cn i: ceI erminec. Fcr excmp|e, in Ihe expre::icn c && L, i f c i : fc| :e, I hen L cce: ncI neec Ic Le evc|ucIec Leccu:e Ihe re:u|I mu:I Le fc|:e. Ihe && cpercIcr Iherefcre wi|| ncI evc|ucIe L. Long Integers / :uL:eI cf I he cpercIi cn: i mp| emenIec fcr inIeger: cre imp|emenIec fcr | cng i nIeger:: criI hmeIi c ccciIi cn +, :uLI rccIi cn -, cnc mu|Ii p|i ccIi cn *, cnc Ihe i nIeger ccmpcri :cn cpercIi cn:. 8iIwi:e cnc Lcc| ecn cpercIi cn: cnc civi:i cn cre ncI :uppcrI ec.
44
F|oot|ng Fo|nt Numbers lC u:e: c pcckcge cf puL| i c-ccmci n f| ccI ing pcinI rcuIine: ci :I riLuIec Ly McI crc|c. Ihi: pcckcge i nc|uce: criIhmeIi c, Iri gcncmeI ric, cnc | cgcriIhmi c funcIicn:. Since f| ccIing pci nI cpercIi cn: cre imp| emenI ec in :cfIwcre, Ihey cre much :| cwer Ihcn Ihe i nIeger cpercIi cn:: we reccmmenc cgci n:I u:ing f| ccIi ng pcinI i f ycu cre ccncernec cLcuI perfcrmcnce. Ihe fc|| cwing cpercIi cn: cre :uppcrIec cn f| ccI ing pcinI numLer:: Ar|thmet| c. ccciI i cn +, :uLIrccIi cn -, mu|I ip| i ccIi cn *, civi:i cn /. Compor|son. grecI er-Ihcn >, | e::-I hcn <, euc|iI y ==, grecI er-I hcn-euc| >=, | e::- Ihcn-euc| <=. 8u||t-|n Moth Funct|ons. / :eI cf Iri gcncmeIric, | cgcriIhmi c, cnc expcnenIi c| funcIi cn: i: :uppcrI ec. Fcr ceIci |:, gc Ic Ihe Li Lrcry FuncIi cn De:cripI icn:. Ihe:e funcIi cn: cre inc|ucec cmcng Ihc:e iI emizec c: McIh funcIi cn:. Chorocters ChcrccIer: cre cn| y c|| cwec in chcrccIer crrcy:. When c ce|| cf Ihe crrcy i : referencec, iI i: cuIcmcIi cc|| y ccercec inI c c inI eger repre:enIcI i cn fcr mcnipu| cIi cn Ly Ihe i nIeger cpercIi cn:. When c vc|ue i: :Icrec inI c c chcrccI er crrcy, iI i: ccercec frcm c :I cnccrc 1- LiI i nIeger inI c cn 8-LiI chcrccIer {Ly IrunccI ing I he upper eighI LiI:). Ass| gnment Operotors ond Expr ess| ons Ihe Lc:ic c::i gnmenI cpercI cr i : =. Ihe fc||cwing :IcI emenI ccc: 2 I c Ihe vc|ue cf c. c = c + 2: Ihe cLLrevicIec fcrm c += 2: ccu| c c| :c Le u:ec I c perfcrm Ihe :cme cpercIi cn. /| | cf Ihe fc|| cwing Lincry cpercIcr: ccn Le u:ec in I hi : fc:hicn: + - * / 7 << >> & / ]
45
Incr ement ond Decr ement Oper otors
Ihe incremenI cpercI cr ++ incremenI: Ihe ncmec vcricL| e. Fcr excmp| e, I he ccn:IrucIicn c++ i : euivc|enI Ic c= c+1 cr c+= 1. / :IcI emenI IhcI u:e: cn incremenI cpercIcr hc: c vc|ue. Fcr excmp| e, I he :I cIemenI c= 3: pri nIf{c=7c c+1=7c\n, c, ++c): wi|| ci :p|cy Ihe I exI c=3 c+1=4. lf I he i ncremenI cpercI cr ccme: cfI er Ihe ncmec vcricL|e, Ihen Ihe vc|ue cf Ihe :IcI emenI i: cc| cu|cIec cfIer Ihe i ncremenI cccur:. Sc Ihe :IcI emenI c= 3: pri nIf{c=7c c+1=7c\n, c, c++): wcu|c ci :p|cy c=3 c+1=3 LuI wcu| c fi ni :h wiIh c :eI Ic 4. Ihe cecremenI cpercIcr - - i: u:ec in Ihe :cme fc:hi cn c: Ihe incremenI cpercI cr. Doto Access Operotors & / :i ng| e cmper:cnc prececing c vcricL| e, cn crrcy reference, cr c :IrucI ure e|emenI reference reIurn: c pcinI er I c I he | cccIicn in memcry where IhcI infcrmcIi cn i : Leing :I crec. Ihi : :hcu| c ncI Le u:ec cn crLiIrcry expre::icn: c: Ihey cc ncI hcve c :I cL| e p|cce in memcry where Ihey cre Lei ng :I crec. * / :ing| e * preceecing cn expre::i cn which evc|ucIe: I c c pci nI er reIurn: Ihe vc|ue which i : :I crec cI IhcI cccre::. Ihi : prcce:: cf ccce::ing I he vc|ue :I crec wiIhin c pci nIer i: kncwn c: ce|e|e|enc| ng. [<exp|>] /n expre::icn in :ucre Lrcce: fc| |cwing cn expre::i cn which evc|ucI e: I c cn crrcy {cn crrcy vcricL| e, Ihe re:u|I cf c funcIi cn which reIurn: cn crrcy pcinIer, eIc.) check: I hcI Ihe vc|ue cf I he expre::icn fc|| : wiIhin Ihe Lcunc: cf Ihe crrcy cnc reference: I hcI e|emenI. . / ccI LeIween c :IrucIure vcricL|e cnc Ihe ncme cf cne cf i I: fi e|c: reIurn: Ihe vc|ue :I crec in I hcI fi e|c.
->
46 /n crrcw LeIween c pcinIer I c c :IrucIure cnc I he ncme cf cne cf i I: fi e|c: in I hcI :IrucIure ccI : Ihe :cme c: c ccI cce:, excepI iI ccI: cn Ihe :IrucIure pci nIec cI Ly iI: | efI hcnc :ice. Where | i : c :I rucIure cf c Iype wiIh | c: cn e| emenI ncme, Ihe Iwc expre::i cn: f.i cnc {&f)->i cre euivc|enI. Frecedence ond Order o| Evo|uot| on Ihe fc|| cwing IcL| e :ummcrize: Ihe ru|e: fcr prececence cnc c::ccicIiviIy fcr Ihe C cpercI cr:. CpercI cr: |i :Iec ecr| i er in Ihe IcL| e hcve higher prececence: cpercIcr: cn Ihe :cme |ine cf I he IcL|e hcve euc| prececence. Operotor Assoc| ot|v|ty {) |] |efI I c ri ghI l ~ ++ -- - {<t ype>) ri ghI Ic | efI * / 7 |efI I c ri ghI + - |efI I c ri ghI << >> |efI I c ri ghI < <= > >= |efI I c ri ghI == l= |efI I c ri ghI & |efI I c ri ghI / |efI I c ri ghI ] |efI I c ri ghI && |efI I c ri ghI ]] ri ghI Ic | efI = += -= eIc. ri ghI Ic | efI , |efI I c ri ghI
Contro| F|ow lC :uppcrI : mc:I cf Ihe :I cnccrc C ccnI rc| :IrucI ure:. Cne ncIcL|e excepIi cn i: Ihe :wi Ich :IcI emenI , which i : ncI :uppcrI ec.
47
Stotements ond 8|ocks / :i ng| e C :IcI emenI i : encec Ly c :emi cc| cn. / :erie: cf :IcI emenI : mcy Le grcupec IcgeIher inI c c c|cck u:i ng cur|y Lrcce:. ln:ice c L| cck, | ccc| vcricL| e: mcy Le cefi nec. 8| cck: mcy Le u:ec in p| cce cf :IcI emenI: in Ihe ccnI rc| f|cw ccn:IrucI :. I|-E|se Ihe i f e| :e :IcI emenI i : u:ec I c mcke ceci :i cn:. Ihe :ynIcx i:: if {<exp|e::| cn>) <:t ct enent -!> e| :e <:t ct enent -2> <exp|e::| cn> i: evc|ucIec: if iI i : ncI euc| I c zerc {e.g., | cgic Irue), Ihen <:t ctenent-!> i: execuI ec. Ihe e| :e c|cu:e i : cpI i cnc|. lf Ihe if pcrI cf Ihe :IcI emenI cic ncI execuIe, cnc Ihe e|:e i: pre:enI , Ihen <:t ct enent -2> execuIe:. Wh||e Ihe :ynIcx cf c whi| e | ccp i: Ihe fc|| cwing: whi| e {<exp|e::|cn>) <:t ct enent > whi|e Legin: Ly evc|ucIing <exp|e::| cn>. l f i I i: fc|:e, Ihen <:t ct enent > i : :kippec. lf iI i: Irue, Ihen <:tct enent > i: evc|ucI ec. Ihen Ihe expre::icn i : evc|ucIec cgcin, cnc Ihe :cme check i : perfcrmec. Ihe | ccp exiI: when <exp|e::| cn> Leccme: zerc. Cne ccn ec:i|y crecIe cn infiniI e | ccp in C u:ing Ihe whi| e :IcI emenI: whi| e {1) <:t ctenent> For
48
Ihe :ynIcx cf c fcr | ccp i : I he fc|| cwing: fcr {<exp|-!>:<exp|-2>:<exp|-3>) <:t ctenent> Ihe fcr ccn:IrucI i: euivc|enI I c Ihe fc|| cwing ccn:IrucI u:ing whi|e: <exp|-!>: whi| e {<exp|-2>) { <:t ctenent> <exp|-3>: }
Iypi cc| |y, <exp|-!> i : cn c::i gnmenI, <exp|-2> i : c re|cIi cnc| expre::i cn, cnc <exp|- 3> i: cn incremenI cr cecremenI cf :cme mcnner. Fcr excmp|e, Ihe fc|| cwing ccce ccunI: frcm 0 Ic , pri nIing ecch numLer c| cng I he wcy: inI i: fcr {i = 0: i < 100: i ++) pri nIf{7c\n, i): 8reok U:e cf Ihe Lreck :IcIemenI prcvice: cn ecr| y exiI frcm c whi| e cr c fcr | ccp.
49
LCD Scr een Fr|nt|ng lC hc: c ver:i cn cf I he C funcIicn prinIf fcr fcrmcII ec prinIi ng I c I he LCD :creen. Ihe :ynIcx cf pri nIf i : I he fc|| cwing: prinIf{<|c|nct -:t|| ng>, <c|g- !> , ... , <c| g-N>): Ihi: i : Le:I i|| u:IrcIec Ly :cme excmp| e:. Fr|nt|ng Exomp|es Exomp| e 1: Fr|nt|ng o messoge Ihe fc|| cwing :IcIemenI prinI : c IexI :I ring I c Ihe :creen. prinIf{He|| c, wcr|cl\n): ln Ihi: excmp|e, Ihe fcrmcI :Iring i : :imp|y prinI ec Ic Ihe :creen. Ihe chcrccI er \n cI Ihe enc cf Ihe :I ring :i gnifie: enc- cf-|i ne. When cn enc- cf- |ine chcrccIer i: prinI ec, Ihe LCD :creen wi| | Le c|ecrec when c :uL:euenI chcrccI er i : prinI ec. Ihu:, mc:I pri nI f :IcI emenI : cre I ermincIec Ly c \n. Exomp| e 2: Fr|nt|ng o number Ihe fc|| cwing :IcI emenI prinI : Ihe vc|ue cf I he inIeger vcricL|e x wiIh c Lrief me::cge. prinIf{Vc|ue i : 7c\n, x): Ihe :peci c| fcrm %d i : u:ec I c fcrmcI Ihe pri nIing cf cn inIeger i n ceci mc| fcrmcI . Exomp| e 3: Fr|nt|ng o number |n b|nor y Ihe fc|| cwing :IcIemenI prinI : Ihe vc|ue cf I he inIeger vcricL|e x c: c Li ncry numLer. prinIf{Vc|ue i : 7L\n, x): Ihe :peci c| fcrm %b i : u:ec I c fcrmcI Ihe prinIing cf cn inI eger i n Lincry fcrmcI . Cn|y Ihe |cw LyI e cf I he numLer i : prinIec.
50
Exomp| e 4: Fr|nt|ng o ||oot|ng po|nt number Ihe fc| | cwing :IcIemenI prinI: I he vc|ue cf Ihe f| ccIing pcinI vcri cL| e n c: c f| ccIing pci nI numLer. prinIf{Vc|ue i : 7f\n, n): Ihe :peci c| fcrm %| i : u:ec I c fcrmcI Ihe prinIing cf f| ccIing pcinI numLer. Exomp| e 5: Fr|nt|ng two numbers |n hexodec| mo| |ormot prinIf{/=7x 8=7x\n, c, L): Ihe fcrm %x fcrmcI : cn inI eger I c prinI i n hexccecimc|. For mott|ng Commond Summor y For mot Commond Doto Iype Descr| pt| on 7c inI cecimc| numLer 7x inI hexccecimc| numLer 7L inI |cw LyIe c: Lincry numLer 7c inI |cw LyIe c: /SCll chcrccIer 7f f| ccI f| ccIi ng pci nI numLer 7: chcr crrcy chcr crrcy {:Iri ng)
Spec|o| Notes Ihe fi nc| chcrccIer pc:iI i cn cf I he LCD :creen i: u:ec c: c :y:Iem hecrILecI. Ihi : chcrccIer ccnIinucu:|y L|ink: LeIween c | crge cnc :mc|| hecrI when Ihe Lccrc i : cpercIing prcper|y. lf I he chcrccI er :I cp: L|i nking, Ihe Lccrc hc: fci| ec. ChcrccIer: I hcI wcu|c Le prinI ec Leycnc Ihe fi nc| chcrccIer pc:iI icn cre I runccIec. When u:i ng c Iwc-|ine ci :p|cy, Ihe prinI f{) ccmmcnc I recI : Ihe ci:p|cy c: c :i ng| e |cnger |i ne. FrinI ing cf | cng inIeger: i : ncI pre:enI| y :uppcrI ec.
51
Freprocessor Ihe preprcce::cr prcce::e: c fi| e Lefcre iI i : :enI Ic I he ccmpi|er. Ihe lC preprcce::cr c|| cw: cefiniI icn cf mccrc:, cnc ccnciIi cnc| ccmpi |cIicn cf :ecIi cn: cf ccce. U:ing preprcce::cr mccrc: fcr ccn:IcnI : cnc funcIi cn mccrc: ccn mcke lC ccce mcre effici enI c: we|| c: ec:i er I c recc. U:ing i f I c ccnciIicnc| |y ccmpi | e ccce ccn Le very u:efu| , fcr in:I cnce, fcr ceLugging purpc:e:. Ihe :pecic| preprcce::cr ccmmcnc u:e hc: Leen inc| ucec Ic c| | cw prcgrcm: Ic ccu:e c prcgrcm Ic ccwn| ccc I c iniIicI e Ihe ccwn|ccc cf :I crec prcgrcm: IhcI cre ncI in Ihe lC |iLrcry. Fcr excmp| e, :uppc:e ycu hcve c :eI cf :I crec prcgrcm: i n c fi| e ncmec my|iL.ic, :cme cf which ycu neec fcr ycur currenI prcgrcm I c wcrk. /* | ccc ny || c|c|y */ u:e my|iL.i c
vcic mci n{) { chcr :|32] = IexI :I ring wrcppi ng Lcc| y\n: fix {:): /* cpp| y ny || x |unct | cn tc : cnc p|| nt |t */ pri nIf{:): } Freprocessor Mocros Freprcce::cr mccrc: cre cefinec Ly u:ing I he cefine preprcce::cr cirecIive cI Ihe :IcrI cf c |i ne. / mccrc i : | ccc| Ic Ihe fi| e in which iI i : cefi nec. Ihe fc| |cwing excmp| e :hcw: hcw Ic cefi ne preprcce::cr mccrc:. cefi ne FlGHI_MCICF 0 cefi ne LEFI_MCICF 1 cefi ne GC_FlGHI{pcwer) {mcIcr{FlGHI_MCICF,{pcwer))) cefi ne GC_LEFI{pcwer) {mcI cr{LEFI_MCICF,{pcwer))) cefi ne GC{|efI ,ri ghI) {GC_LEFI{|efI): GC_FlGHI{ri ghI):} vcic mcin{) { GC{0,0): }
52
Freprcce::cr mccrc cefiniI i cn: :I crI wiIh I he cefine ci recIive cI Ihe :IcrI cf c |ine, cnc ccnIinue Ic Ihe enc cf Ihe | ine. /fIer cefine i : Ihe ncme cf Ihe mccrc, :uch c: kIGHI_MOIOk. lf Ihere i : c pcrenIhe:i : cirecI| y cfIer Ihe ncme cf Ihe mccrc, :uch c: Ihe GO_kIGHI mccrc hc: cLcve, Ihen Ihe mccrc hc: crgumenI:. Ihe GO_kIGHI cnc GO_LEFI mccrc: ecch Icke cne crgumenI . Ihe GC mccrc Icke: Iwc crgumenI:. /fIer Ihe ncme cnc Ihe cpIi cnc| crgumenI |i :I i : Ihe Lccy cf Ihe mccrc. Ecch I ime c mccrc i: invckec, iI i: rep|ccec wiIh iI: Lccy. l f Ihe mccrc hc: crgumenI :, I hen ecch p|cce Ihe crgumenI cppecr: in Ihe Lccy i : rep|ccec wiIh Ihe ccI uc| crgumenI prcvicec. lnvcccIicn: cf mccrc: wiIhcuI crgumenI: | cck |ike g| cLc| vcricL| e reference:. lnvcccIi cn: cf mccrc: wiIh crgumenI : |cck |i ke cc|| : I c funcIi cn:. Ic cn exI enI , Ihi : i : hcw Ihey ccI. Hcwever, mccrc rep|ccemenI hcppen: Lefcre ccmpi| cIi cn, wherec: g| cLc| reference: cnc funcIi cn cc| |: hcppen cI run Iime. /| :c, funcIi cn cc| |: evc|ucIe I heir crgumenI: Lefcre Ihey cre cc|| ec, wherec: mccrc: :imp|y perfcrm I exI rep|ccemenI . Fcr excmp| e, i f Ihe ccIuc| crgumenI given I c c mccrc ccnI cin: c funcI i cn cc| |, cnc Ihe mccrc in:IcnIicI e: iI : crgumenI mcre Ihcn cnce in iI : Lccy, Ihen Ihe funcIicn wcu|c Le cc| |ec mu|Iip| e Ii me:, wherec: iI wcu|c cn|y Le cc|| ec cnce i f iI were Leing pc::ec c: c funcIi cn crgumenI in:I ecc. /pprcpricI e u:e cf mccrc: ccn mcke lC prcgrcm: cnc ec:i er I c recc. lI c|| cw: ccn:I cnI: Ic Le given :ymLc|i c ncme: wiIhcuI reuiring :Icrcge cnc ccce:: Iime c: c g|cLc| wcu|c. lI c|:c c|| cw: mccrc: wiIh crgumenI: I c Le u:ec in cc:e: when c funcIi cn cc|| i: ce:ircL|e fcr cL:IrccIi cn, wiIhcuI Ihe perfcrmcnce penc|Iy cf cc|| ing c funcI icn.
53
Cond| t|ono| comp|| ot| on lI i: :cmeI ime: ce:ircL| e I c ccnciI i cnc||y ccmpi| e ccce. Ihe pri mcry excmp| e cf Ihi: i: I hcI ycu mcy wcnI Ic perfcrm ceLuggi ng cuIpuI :cmeI ime:, cnc ci :cL|e iI cI cI her I ime:. Ihe lC preprcce::cr prcvice: c ccnveni enI wcy cf ccing Ihi : Ly u:ing I he i fcef ci recIive. vcic gc_| efI {i nI pcwer) { GC_LEFI{pcwer): i fcef DE8UG pri nIf{Gci ng LefI\n): Leep{): enci f } ln Ihi: excmp| e, when Ihe mccrc DE8bG i: cefinec, Ihe ceLugging me::cge Gcing LefI wi|| Le pri nI ec cnc Ihe Lccrc wi|| Leep ecch Iime go_| e|t i : cc|| ec. l f I he mccrc i: ncI cefi nec, Ihe me::cge cnc Leep wi|| ncI hcppen. Ecch ifcef mu:I Le fc||wec Ly cn enci f cI Ihe enc cf Ihe ccce which i : Leing ccnciIi cnc|| y ccmpi | ec. Ihe mccrc I c Le checkec ccn Le cnyIhing, cnc i fcef L| cck: mcy Le ne:Iec. Un|i ke regu|cr C preprcce::cr:, mccrc: ccnncI Le ccnciI i cnc||y cefi nec. lf c mccrc cefi niIi cn cccur: in:ice cn i fcef L|cck, iI wi|| Le cefi nec regcrc| e:: cf wheIher Ihe i fcef evc|ucIe: Ic Irue cr fc| :e. Ihe ccmpi| er wi|| genercIe c wcrning i f mccrc cefi niIi cn: cccur wiIhin cn ifcef L| cck. Ihe i f, e|:e, cnc e|if cirecIive: cre c| :c cvci|cL| e, LuI cre cuI:ice Ihe :ccpe cf Ihi: cccumenI. Fefer I c c C reference mcnuc| fcr hcw Ic u:e Ihem.
54
Compor|son w|th r egu|or C pr eprocessors Ihe wcy in which lC cec| : wiIh | cccing mu| Iip|e fi| e: i: funccmenIc||y ci fferenI frcm Ihe wcy in which iI i : ccne in :Icnccrc C. ln pcrI icu|cr, when u:ing :Icnccrc C, fi| e: cre ccmpi |ec ccmp| eIe|y incepencenI| y cf ecch cIher, Ihen |inkec IcgeIher. ln lC, cn Ihe cIher hcnc, c|| fi |e: cre ccmpi | ec IcgeI her. Ihi: i : why :Icnccrc C neec: funcI i cn prcI cI ype: cnc extern g|cLc| cefiniI i cn: i n crcer fcr mu|Ii p| e fi |e: Ic :hcre funcIi cn: cnc g| cLc|:, whi| e lC cce: ncI. ln c :Icnccrc C preprcce::cr, preprcce::cr mccrc: cefi nec in cne C fi| e ccnncI Le u:ec in cncI her C fi| e un| e:: cefinec cgci n. /| :c, Ihe :ccpe cf mccrc: i: cn| y frcm Ihe pcinI cf cefi niIi cn Ic Ihe enc cf I he fi|e. Ihe :c| uIi cn Ihen i: I c hcve Ihe prcIcI ype:, extern cec|crcIi cn:, cnc mccrc: in heccer fi| e: which cre I hen inc| ucec cI Ihe I cp cf ecch C fi| e u:i ng Ihe inc|uce cirecIive. Ihi: :Iy| e inI erccI: we| | wiIh Ihe fccI IhcI ecch fi |e i: ccmpi |ec incepencenI cf c| | Ihe cI her:. Hcwever, :ince cec| crcI i cn: in lC cc ncI fi|e :ccpe, iI wcu| c Le inccn:i :IenI I c hcve c preprcce::cr wiIh fi | e :ccpe. Iherefcre, fcr ccn:i :I ency iI wc: ce:ircL|e Ic give lC mccrc: Ihe :cme Lehcvicr c: g| cLc|: cnc funcI icn:. Iherefcre, preprcce::cr mccrc: hcve g| cLc| :ccpe. lf c mccrc i: cefi nec cnywhere in Ihe fi | e: | cccec i nIc lC, iI i: cefi nec everywhere. Iherefcre, Ihe inc|uce cnc uncef cirecIive: cic ncI :eem I c hcve cny cpprcpri cIe purpc:e, cnc were ccccrcing| y |efI cuI. Ihe fccI IhcI cefine cirecIive: ccnIcinec wiIhin if L| cck: cre cefinec regcrc|e:: cf wheIher Ihe i f evc|ucI e: I c Le Irue cr fc| :e i: c :ice effecI cf mcking I he preprcce::cr mccrc: hcve g| cLc| :ccpe. CIher Ihcn Ihe:e mcci fi ccIi cn:, Ihe lC preprcce::cr :hcu|c Le ccmpcI iL| e wiIh regu| cr C preprcce::cr:.
55
Ihe IC L|br or y F|| e LiLrcry fi | e: prcvice :Icnccrc C funcI i cn: fcr inIerfccing wiIh hcrcwcre cn Ihe rcLcI ccnI rc|| er Lccrc. Ihe:e funcIicn: cre wriIIen eiIher in C cr c: c::emL|y |cngucge criver:. LiLrcry fi| e: prcvice funcI icn: Ic cc Ihi ng: |i ke ccnI rc| mcI cr:, mcke I cne:, cnc inpuI :en:cr: vc|ue:. lC cuIcmcIi cc|| y | ccc: Ihe |iLrcry fi| e every Iime iI i : i nvckec. Depencing cn which Lccrc i: Lei ng u:ec, c ci fferenI |iLrcry fi| e wi| | Le reuirec. lC mcy Le ccnfi gurec I c |ccc ci fferenI |iLrcry fi |e: c: iI : cefcu|I: lC wi|| cuI cmcI icc|| y |ccc I he ccrrecI |i Lrcry fcr Ihe Lccrc ycu're u:i ng cI Ihe mcmenI. SepcrcIe cccumenIcI icn ccver: c|| |i Lrcry funcIi cn: cvci|cL| e fcr I he Hcncy 8ccrc cnc FCX: i f ycu hcve cncIher Lccrc, :ee ycur cwner': mcnuc| fcr cccumenIcI i cn. Ic uncer:Icnc LeII er hcw Ihe |iLrcry funcI i cn: wcrk, :Iucy cf I he |iLrcry fi| e :curce ccce i : reccmmencec: e.g., Ihe mcin | iLrcry fi|e fcr I he Hcncy 8ccrc i: ncmec | iL_hL.i c. Fcr ccnveni ence, ccmmcn|y c ce:cri pIi cn cf ccmmcn| y u:ec |iLrcry funcIi cn: fc| | cw:.
pri nIf{<:t|| ng>, <c|g!>, <c| g2>, ... ): /* p|| nt: <:t|| ng>. || tne :t || ng ccnt c| n: 7 ccce: tnen t ne <c| g:> c|t e| t ne :t || ng w| || ce p|| nt ec |n p|cce c| t ne 7 ccce: | n t ne |c|nct :pec| || ec cy tne ccce. 7c p|| nt : c cec| nc| nunce|. 7| p|| nt : c || cct | ng pc| nt nunce|. 7c p|| nt : c cnc|cct e|. 7c p|| nt: cn | ntege| |n c| nc|y. 7x p|| nt : cn |nt ege| | n nexccec| nc|. */
mcI cr{<nct c|_>, <:peec>) /* ccnt|c|: t ne nct c|:. <nct c|_> | : cn | ntege| cetween 0 cnc 3 (! | e:: |c| FCX}. <:peec> | : cn | ntege| cetween - !00 cnc !00 wne|e 0 necn: t ne nct c| | : c|| cnc negct| ve nunce|: |un t ne nct c| | n t ne |eve|:e c| |ect | cn */
57
fc{<nctc|_>): /* t u|n: cn t ne nct c| :pec| || ec (c| |ect |cn | : cet e|n|nec cy p|ug c||entct|cn */
Lk{<nctc|_>): /* t u|n: cn t ne nct c| :pec| || ec | n t ne cppc:| te c| |ect | cn ||cn |c */
cff{<nctc|_>): /* t u|n: c|| t ne nct c| :pec| || ec */
cc{): /* t u|n: c|| nct c| pc|t : c|| */ Frocesses Frcce::e: wcrk in pcrc|| e|. Ecch prcce::, cnce iI i : :I crI ec, wi|| ccnIinue unIi | iI fini :he: cr unIi| i I i: ki|| ec Ly cncIher prcce:: u:ing Ihe ki||_prcce::{<p| cce::_| c)>): :IcI emenI . Ecch prcce:: IhcI i : ccIive geI : 50m: cf prcce::ing Ii me. Ihen Ihe prcce:: i: pcu:ec I empcrcri |y cnc Ihe nexI prcce:: geI : iI : :hcre cf Iime. Ihi: ccnI inue: unIi| c| | Ihe ccI ive prcce:: hcve gcII en c :| ice cf Iime, Ihen iI c|| repecI : cgcin. Frcm Ihe u:er': :Icncpci nI iI cppecr: IhcI c|| Ihe ccIive prcce::e: cre running in pcrc| |e|. Frcce::e: ccn ccmmuniccI e wiIh cne cncIher Ly reccing cnc mcci fying g|cLc| vcricL|e:. Ihe g| cLc| : ccn Le u:ec c: :emcphcre: :c IhcI cne prcce:: ccn :i gnc| cncIher. Frcce:: lD: mcy c| :c Le :Icrec in g|cLc| : :c IhcI cne prcce:: ccn ki || cncIher when neecec. Up Ic 4 prcce::e: i niIi cIec Ly Ihe :IcrI_prcce::{) | iLrcry funcI icn ccn Le ccIive cI cny I i me. Ihe |iLrcry funcIi cn: fcr ccnI rc|| ing prcce::e: cre: :IcrI_prcce::{<|unct |cn_ncne>{<c| g!>, <c| g2>, . . .)): /* :tc|t_p|cce:: |et u|n: cn | ntege| tnct | : tne <p|cce::_| c> cnc :t c|t : t ne |unct | cn <|unct |cn_ncne> c: c :epc|ct e p|cce:: */
cefer{): /* wnen p|ccec | n c |unct| cn t nct |: u:ec c: c p| cce:: t n|: w||| ccu:e t nct p|cce:: tc g| ve up t ne |enc| nce| c| |t : t|ne :|| ce wneneve| ce|e| | : cc||ec */
ki ||_prcce::{<p|cce::_| c>): /* t n| : w| || te|n| nct e t ne p|cce:: :pec| || ec cy t ne <p| cce::_| c> */ Encoders [Hondy 8oord on|y}
58
Ihe encL| e_encccer{) | iLrcry funcIi cn i : u:ec Ic :IcrI c prcce:: which upccI e: Ihe Ircn:iI i cn ccunI fcr Ihe encccer :peci fi ec. Ihe encccer | iLrcry funcI icn: cre ce:ignec fcr :en:cr: ccnnecI ec Ic {ci giIc|) pcrI: 7,8,12,13. Ihe ccrre:pcnci ng <enccce|> vc|ue: cre 0,1,2,3. Every encL| ec encccer u:e: c |cI cf Ihe H8': prcce::cr -- :c ccn'I encL| e cn encccer un|e:: ycu cre gcing Ic u:e iI, cnc neve| put cn encc|e :t ctenent | n:| ce c| c |ccp. encL| e_encccer{<enccce|>): /* t u|n: cn t ne :pec| || ec enccce| (e| t ne| 0.!.2. c| 3 wn| cn c|e p|uggec | ntc c| g| tc| pc|t: . 8. !2. !3 |e:pect | ve|y}. n| : :ncu|c ce ccne cn| y cnce - neve| encc|e cn c|| eccy encc|ec enccce|. || cn enccce| | : nct encc|ec. |ecc_enccce| w| || c|wcy: |et u|n 0. */
ci:cL| e_encccer{<enccce|>) /* t u|n: c|| t ne :pec| || ec enccce| */
re:eI_encccer{<enccce|>) /* :et : tne :pec| || ec enccce| vc|ue t c 0 */
recc_encccer{<enccce|>) /* |et u|n: cn |nt tnct | : tne cu||ent vc|ue c| t ne :pec| || ec enccce| */
59
60 Add senses to the Robo-11 standard so that it can detect and move along a line, by using the IR Reflector Sensor. 1 Using the Robo-11 standard robot, remove the top structure that has the AX- 11 attached.
2 Turn the robot upside down. Install the 10 mm plastic spacer using a 3 x 25 mm screw screwed into the universal plate according to the positions as shown in the picture ( positions 5,2 and 5,9 : the first set of numbers refer to the longitude positions from the leftmost side while the second set is the horizontal positions form the top down. )
3 Take two IR Reflector Sensors (ZX-03) and place them onto the spacers, twisting the screw through the spacer and sensor and screwing it tightly together with a 3 mm nut. Do the same for both sets, and set the robot upright.
Building Type 1
61 /* Example for Robo-11 liner1 : Black line Detection Hardware configuration - Motor left connected to DC Motor chanel M-0 - Motor right connected to DC Motor chanel M-1 - ZX-03 left connected to AI-31 - ZX-03 Right connected to AI-17 */
#define pow 50 /*Configuration power drive motor 50% */ #define ref 70 /*Configuration analog reference 70 */ int left=0,right =0; // To keep input analog value
void main(void) { ao(); while(! stop_button()) // Check STOP button pressed in process { printf("Press start! \n); // Show message while(! start_button()); // Check START button pressed to run printf(" Track Line\n); // Show message for working while(! stop_button()) // Check STOP button pressed in process { left = analog(31); // Read left sensor data right = analog(17); // Read right sensor data if((left>ref)&&(right>ref) //check out line { run_fd(0.01); // Direct forward } else if((left<ref)&&(right >ref)) // check left sensor in line { turn_right(1.5); // Turn right 1.5 sec } else if((left>ref)&&(right <ref)) // check right sensor in line { turn_left (1.5); // Turn left 1.5 sec }
4 Replace the top structure that has the AX-11 board on it back onto the bottom part. Then connect the left IR Reflector Sensor (looking down from the top) to terminal Al-31 and the right one to terminal Al-17 of the AX-11
The Robo-11 Liner1 is now complete and ready to search and detect lines.
Robo-11 Liner1 Test
After the Robo-11 Liner1 has been put together, we will then write a test program to test the operation of the Robo-11 Liner1 by having it detect a black line and move backwards and change directions once it detects the line.
Type in the following program code and download it to the Robo-11 liner1.
62 else if((left <ref)&&(right <ref)) //check 2 sensor in line { turn_left (1.5); // Turn left 1.5 sec } } printf("Stop..\n); // Show message off all motor ao(); // Off all motor for end program beep(); // Sound beep signal for end program } } void turn_left(float spin_time) { motor(0,-pow); // Motor0 backward for pow define value motor(1,pow); // Motor1 forward for pow define value sleep(spin_time); // Delay set by parameter spin_time } void turn_right(float spin_time) { motor(0,pow); // Motor0 forward for pow define value motor(1,-pow); // Motor1 backward for pow define value sleep(spin_time); // Delay set by parameter spin_time } void run_fd(float delay) { motor(0,pow); // Motor0 forward for pow define value motor(1,pow); // Motor1 forward for pow define value sleep(delay); // Delay set by parameter delay } void run_bk(float delay) { motor(0,-pow); // Motor0 backward for pow define value motor(1,-pow); // Motor1 backward for pow define value sleep(delay); // Delay set by parameter delay }
TIPS ON THE IR REFLECTOR SENSOR The heart of this sensor circuit is the sensor that detects reflections from infrared light . It consists of the Infrared LED which emits infrared light to the surface. Photo-transistors will then receive the reflected infrared lights. If no infrared light is received, the OUT terminal will have low voltage when measured. In the case that it receives infrared light , whether low or high current passes through the photo-transistor depends on the intensity of the light received which in turn varies according to the distance of the reflection. (Sensor TCRT5000 can be used at a distance of 0.1 - 1.5 centimeters). Therefore, 0.5 - 5V can be measured at the OUT terminal, and the AX-11 will get a value of 10 to 255.
63 Create the test field by cutting two 20 cm long and 1 in wide black tape and placing it 50 cm apart on a flat surface.
Testing It
Place the Robo-11 Liner1 on the floor and then turn on the POWER switch. The LCD screen displays the message Press Start. Press START on the AX-11. The robot will move forward using only 50% of its power, while using the IR Reflector Sensor to detect the black line. The robot will immediately change directions if it detects a black line, the direction depending on the operation of the sensors.
If the left sensor detects the line first, the robot will turn right. However, if the right sensor detects the line first, it will turn left. If both sensors detect a line, the robot will also turn left.
How accurate the Robo-11 Liner1 detects the black line depends on the chosen decision variable, whether is defined as the black line or the white surface. In the test program, the parameter is defined as 80. This value may be changed depending on the test area, which may have more or less light. Other factors may include the distance from the sensor to the floor, or if the test field is modified to have white lines on a black surface instead.
64 Building Type 2 1 The Robo-11 Liner2 will have 3 IR Reflector sensors installed, enabling a more efficient detection. Using the Robo- 11 standard robot, remove the top structure that has the AX-11 attached.
2 Turn the robot upside down. Install the 10 mm plastic spacer using a 3 x 25 mm screw screwed into the universal plate according to the positions (5,2), (8,6) and (5,9). The first set of numbers refers to the longitude positions from the leftmost side while the second set is the horizontal positions form the top down.
3 Place the IR Reflector Sensors (ZX-03) onto the spacers, twisting the screw through the spacer and sensor and screwing it tightly together with a 3 mm nut. Do the same for all sets, and set the robot upright.
4 Replace the top structure with the AX-11 board back onto the bottom part. Then connect the left IR Reflector Sensor (looking down from the top) to terminal Al-31 and the right one to terminal Al-17 of the AX-11
65 Conditions in testing the Line Sensor
The programmer needs to test reading the values from the line sensor, in this case, detecting a black line and white surface. Then he must calculate the value that is able to differentiate between the reflection from the black line and the white field surface. The program can be written as following:
When the black line is detected, the converted analog signals to digital signals will give a value of 40 to 60.
When the white surface is detected, the converted analog signals to digital signals will give a value of 40 to 60.
Therefore, 80 is chosen as the reference value for the black line detection. Thus, if the value read from the line sensor is less than 80, the sensor will consider it to be on a black line. But if the value read is more than 80, than the sensor is considered to be on the white surface area.
When the Robot Moves
Results of all sensors are as following:
Left Line Sensor Cent ral Line Sensor Right Line Sensor Detected white surface. The value read from input Al- 31 was more than 80. Detected the black line. The value read from input Al- 25 was less than 80. Detected white surface. The value read from input Al- 17 was more than 80.
When the robot operates in this scenario, the robot must be controlled so that it moves forward and delays briefly.
Scenario 1: Robot moves along the line
66 Scenario 2: The robot moves rightwards away of the line Scenario 3: The robot moves leftwards away of the line.
Scenario 4: The robot meets an intersection
Results of all sensors are as following:
Left Line Sensor Central Line Sensor Right Line Sensor Detected the black line. The value read from input Al-31 was less than 80. Detected the black line. The value read from input Al-25 was more than/less than 80. Detected white surface. The value read from input Al- 17 was more than 80.
When the robot operates in this scenario, the robot must be controlled so that it turns left slowly and delays briefly.
Results of all sensors are as following:
Left Line Sensor Central Line Sensor Right Line Sensor Detected white surface. The value read from input Al- 31 was more than 80. Detected the black line. The value read from input Al-25 was more than/less than 80. Detected white surface. The value read from input Al- 17 was less than 80.
When the robot operates in this scenario, the robot must be controlled so that it turns right slowly and delays briefly.
Results of all sensors are as following:
Left Line Sensor Central Line Sensor Right Line Sensor Detected the black line. The value read from input Al-31 was less than 80. Detected the black line. The value read from input Al-25 was less than 80. Detected the black line. The value read from input Al-17 was less than 80.
When the robot operates in this scenario, the robot has many options to choose from whether it is to move forward, turn left , or turn right.
67 /* Example for Robot track line - Motor left connected to DC Motor chanel M-0 - Motor right connected to DC Motor chanel M-1 */
#define pow 50 /*Configuration power drive motor*/ #define ref 80 /*Configuration analog reference */ int left =0,right=0 ,mid=0; // For keep input analog value
void main(void) { ao(); while(! stop_button()) // wait STOP button pressed in process { printf("Press start!\n); // Show begining message while(! start_button()); // Wait START button pressed to run printf(" Track Line\n); // Show working message while(! stop_button()) // Wait STOP button pressed in process { left = analog(31); // Read left sensor data mid = analog(25); // Read middle sensor data right = analog(17); // Read right sensor data if((left >ref)&&(mid<ref)&&(right>ref) // Check in line { run_fd(0.01); // Direct forward } else if((left <ref)&&(mid>ref)&&(right >ref)) // Check over right { turn_left (0.1); // Turn left for backing to line } else if((left >ref)&&(mid<ref)&&(right <ref)) // Check in line { turn_right(0.3); // Turn right for backing to line } else if((left >ref)&&(mid>ref)&&(right <ref)) // Check over left { turn_right(0.1); // Turn right for backing to line } else if((left <ref)&&(mid<ref)&&(right >ref)) // Check cross line { turn_left (0.3); // Turn left for backing to line } else if((left <ref)&&(mid>ref)&&(right <ref)) // Check bet ween cross line { turn_left (0.3); // Turn left for backing to line } else // If out of condition { run_fd(0.01); // Direct forward } } Robo-11 Liner2 Test
After the Robo-11 Liner2 has been put together, we will next write a test program to test the operation of the Robo-11 Liner2 by having it detect and move forward along a black line.
Type in the following program code and download it to the Robo-11 Liner2.
68 printf("Stop..\n); // Show finish message ao(); // Off all motor for endi ng program beep(); // Sound beep signal for ending program } }
void turn_left(float spin_time) { motor(0,-pow); // Motor0 backward with pow value motor(1,pow); // Motor1 forward with pow value sleep(spin_time); // Delay set by parameter spin_time } void turn_right(float spin_time) { motor(0,pow); // Motor0 forward with pow value motor(1,-pow); // Motor1 backward with pow value sleep(spin_time); // Delay set by parameter spin_time } void run_fd(float delay) { motor(0,pow); // Motor0 forward with pow value motor(1,pow); // Motor1 forward with pow value sleep(delay); // Delay set by parameter delay } void run_bk(float delay) { motor(0,-pow); // Motor0 backward with pow value motor(1,-pow); // Motor1 backward with pow value sleep(delay); // Delay set by parameter delay }
Testing It
Place the Robo-11 liner2 over the black line on the floor (provided in the set) and then turn on the POWER switch. The LCD screen displays the message Press Start. Press START on the AX-11. The robot will move forward using only 50% of its power. At the same time, the display screen will show the message "Track Line. When the intersection is located, the robot will always decide to turn left and will only stop operating when the STOP switch is pressed.
How accurately the Robo-11 Liner2 detects the black line depends on the chosen decision variable, whether it is defined as the black line or the white surface, similar to the Robo-11 Liner1. It also depends on choosing the appropriate speed level. If it moves too fast, it may swing out of its course.
69 This robot was further developed from the Robo-11 standard by adding switches that will detect obstacles via collision.
BUILDING THE ATTACKER 1 Using the Robo-11 Standard robot (or the Robo-11 Liner2), take a strength joiner and attach it to the front of the robot with a 3 x 10 screw and 3 mm nut as shown in the picture. It should be twisted outward and installed at approximately 45 degrees.
2 Next, connect an obtuse joiner to the end of that strength joiner.
3 At the other end of the obtuse joiner from step 2, attach an angled joiner. This angled joiner will then be used to connect the switch.
70 4 Take the switch and install it to that robot arm that was built in step 3, by using a 3 mm spacer, 3 x 10 screw, and 3 mm nut and screwing them in together tightly.
5 Then proceed to build the robot arm for the other side, using the same steps. When finished, connect the signal cable of the left switch to terminal Dl-15 and the signal cable of the right switch to terminal Dl-10 of the AX-11 board. The Robo-11 Attacker is now finished and ready to be tested.
71
ABOUT THE SWITCH CIRCUIT Pressing the switch results in two occurrences.
When the switch is not pressed, let the results be logic "1 When the switch is pressed, let the results be logic "0, and LED1 light up.
Since the switch can give t wo results, it is considered to be a digital input component. Therefore, in connecting it to the AX-11 board, it must be connected to the digital input terminals D1 which has 9 channels altogether, D1-0 to D1-8.
In addition, it can also use the LED display on the s witch as a digital output by connected it to the digital output terminal D0 which also has 9 channels. The LED on the switch will turn on or off depending on t he logic "0 or "1 being sent. When logic "0 is sent, the LED will light (This method of use is not recommended for beginners)
Caution: When the LED display on the switch is used as an output, the switch must not be used or pressed or else the switch terminal ports may be damaged.
Robo-11 Attacker Test
The next step would be to write a test program to test the operation of the Robo-11 Attacker by having it detect objects by touch or collision and then to change directions to avoid that object.
Type in the following program code and download it to the Robo-11 Attacker.
72 /* Example for object detection by Touch sensor - Motor left connected to DC Motor chanel M-0 - Motor right connected to DC Motor chanel M-1 - Touch s ensor left side c onnected to DI-15 - Touch s ensor right side connected to DI-10 */ #define pow 50 /*Configuration power drive motor*/ void main() { int obj_left,obj_right; // For keep result detec t object printf("P ress Start!\n); // Display message start_press(); // Wait until START button pressed printf("Robot Move...\n); // Show running message while(!stop_button()) // I nfinite loop { obj_left = digital(15); // Keep left sensor detection obj_right = digital(10); // Keep right sensor detection if(obj_left==0 && obj_right==0) // I n case both sensor dont detect { run_fd(0.1); // Forward 0.1 second } else if(obj_left==0 && obj_right==1) // I n case right s ens or detec t objec t only { run_bk(0.5); // Backward 0.5 sec turn_left(0.5); // T urn left 0.5 sec } else if(obj_left==1 && obj_right==0) // I n case left sensor detect object { run_bk(0.5); // Backward 0.5 second turn_right(0.5); // T urn right 0.5 second } else if(obj_left==1 && obj_right==1) // I n case both sensor detect object { run_bk(0.5); // Backward 0.5 second turn_right(1.0); // T urn right 1.0 second } } ao(); // O ff motor all c hannel beep(); // Sound alarm printf("Stop...\n); // Show ending message } void turn_left(float s pin_time) { motor(0,-pow); // Motor0 backward with pow value motor(1,pow); // Motor1 forward with pow value sleep(spin_time); // Delay set by parameter spin_time } void turn_right(float spin_time) { motor(0,pow); // Motor0 forward with pow value motor(1,-pow); // Motor1 backward with pow value sleep(spin_time); // Delay set by parameter spin_time } void run_fd(float delay) { motor(0,pow); // Motor0 forward with pow value motor(1,pow); // Motor1 forward with pow value sleep(delay); // Delay set by parameter delay } void run_bk(float delay) { motor(0,-pow); // Motor0 backward with pow value motor(1,-pow); // Motor1 backward with pow value sleep(delay); // Delay set by parameter delay }
73 Testing It
Place the Robo-11 Attacker on the floor (provided in the set) and then turn on the POWER switch. The LCD screen displays the message Press Start. Press START on the AX-11. The robot will move forward using only 50% of its power. At the same time, the display screen will show the message "Robot Move.
When the robot runs into an obstacle with the left arm: The robot will move backwards for 0.5 seconds and turn right for 0.5 seconds. Then it will continue to move forward.
When the robot runs into an obstacle with the right arm: The robot will move backwards for 0.5 seconds and turn left for 0.5 seconds. Then it will continue to move forward.
The robot will stop when the STOP switch is pressed.
The Robo-11 Attacker uses a switch to enable digital communication with the sensor. When the switch is pressed, or activated, the digital signal "0 will be sent. With the proper coding, the Robo-11 Attacker will be able to avoid the obstacle and will also have the capability for Maze Solving if additional sensors are installed.
74 Adding the Infrared Ranger Sensor GP2D120 to the Robo-11 Standard robot enables it to detect obstacles at a distance without having to collide into or touch the object.
BUILDING THE RANGER 1 Using the Robo-11 Standard robot (or the Robo-11 Liner2 or Attacker), take an angled joiner and attach it to the left and right front of the robot with a 3 x 10 screw and 3 mm nut as shown in the picture. (If the Robo-11 Attacker is used and modified, the position of the switch arm might need to be changed).
2 Next, insert a strength joiner vertically into both angled joiners.
3 Take two more angled joiners and attach it to the other ends of the strength joiner.
75
4 Then attach another angled joiner to the end of the angled joiner in step 3.
5 Install the GP2D120 module to the end of the angled joiner from step 4. The arms might need to be pulled out a bit for installation. Use a 3 x 10 screw and two 3 mm nuts to install the GP2D120 to the arm from steps 1-4. Then connect the signal cable of the module to the input terminal A1-6 of the AX-11 board.
Now the Robo-11 Ranger robot is ready to measure the range and detect obstacles at a distance without having to make any contact with the object.
GP2D12 and GP2D120 Infrared Ranger and Sensor Module Measures the range using Infrared light Can measure a distance of 10 to 80 cm for the GP2D12 and 4 to 30 cm for the GP2D120 Uses 4.5-5 V voltage and 33 mA Provides 0.4 - 2.4 V output range at +5V supply.
The GP2D12/GP2D120 are infrared sensor modules that have 3 terminals, which are t he voltage input (Vcc), ground (GND), and the voltage output (Vout). The values from the GP2D12 must be read after the initiating period of the module, which usually lasts around 32 - 52.9 ms. After this time, the voltage output can be measured.
For the GP2D120, the output at the 30 cm distance and +5V input is within the 0.25 to 0.55 V range, with the average being 0.4V. Thus, the output variation withi n the 4 to 30 cm range is 2.25V + 0.3V.
Warning for the GP2D12 and GP2D120 signal cable.
Since the GP2D12 and GP2D120 have different terminal layouts than that of the AX-11 board, even though they look the same, a special signal cable was made for the two modules. The cable is already connected to the modules. All the user needs to do is connect this cable to the AX-11 board. The user must not remove this cable at all times and MUST NOT switch the GP2D120 module cable with the cable of other sensor modules.
76 Robo-11 Ranger Test
In writing the program to test the Robo-11 Ranger robot, we emphasize on the communication with the GP2D120 module to detect and measure the distance between the object and the robot so that it can avoid the obstacle without having any physical contact.
Type in the following program code and download it to the Robo-11 Ranger.
77 /* Example for infrared detector sensor by GP2D120 - Motor left connected to DC Motor chanel M-0 - Motor right connected to DC Motor chanel M-1 - GP2D120 connected to AI-6 */ #use "gp2d120_lib.ic /* gp2d120_lib.ic */ #define pow 50 /* Set 50% motor power */ void main() { float result; printf("Press Start!\n); // Show begining message start_press(); // Wait START button pressed printf("Robot Move...\n); // Show running message while(! stop_button()) // Infinite loop { result = distance(); // Get distance value if (result <= 20.0 && result != -1.0 ) // Check distance <=20 ? // if TRUE escape { run_bk(1.0); // Backword 1 second turn_left (0.5); // Turn left 0.5 second } else { run_fd(0.1); // Forward 0.1 second } } ao(); // Off motor all channel beep(); // Sound alarm printf("Stop...\n); // Show ending message } void turn_left(float spin_time) { motor(0,-pow); // Motor0 backward with pow value motor(1,pow); // Motor1 forward with pow value sleep(spin_time); // Delay set by parameter spin_time } void turn_right(float spin_time) { motor(0,pow); // Motor0 forward with pow value motor(1,-pow); // Motor1 backward with pow value sleep(spin_time); // Delay set by parameter spin_time } void run_fd(float delay) { motor(0,pow); // Motor0 forward with pow value motor(1,pow); // Motor1 forward with pow value sleep(delay); // Delay set by parameter delay } void run_bk(float delay) { motor(0,-pow); // Motor0 backward with pow value motor(1,-pow); // Motor1 backward with pow value sleep(delay); // Delay set by parameter delay }
78 Testing It
Place the Robo-11 Ranger on the floor and then turn on the POWER switch. The LCD screen displays the message Press Start. Press START on the AX-11. The robot will move forward using only 50% of its power. At the same time, the display screen will show the message "Robot Move.
When the robot moves closer to the obstacle and is within the specified distance : The Robo-11 Ranger robot will move backwards 1 second and turn left for 1 second. Then it will move forward.
The specified range to detect objects in this test is 20 cm. .
The robot will stop when the STOP switch is pressed.
The Robo-11 Ranger is another example of analog communication with the sensor. The value read from the sensor is converted to digital data and processed further to provide results. The results in this case is the distance measured from the sensor to the object.
79 Additional sensors and components to measure the movement distance are added so that the user can control the robot to move within a specified distance more accurately.
BUILDING THE SMARTMOVER 1 Using the Robo-11 standard robot, remove the structure of the robot that is attached to the top of the AX-11 board. On the bottom part, attach the encoder wheel sticker to the two main track wheels.
2 Take an angled joiner and attach it to the base plate at the positions of 16,3 and 16,9 (counting from the side opposite of the motor gear set) with a 3 x 10 mm screw and a 3 mm nut. The right angle side should be turned outwards as shown in the picture 3 Attach a 25 mm copper tube to the angled joiner with a 3 x 6 mm screw. The copper tubes should be facing outwards as shown in the picture. Do the same for both sides. .
80 4 Take the ZX-21 code wheel reflector sensor and attach it to the other end of the copper tube. The infrared reflector sensor should be turned inwards to face the main track wheel. Screw together with a 3 x 6 mm screw and repeat the same for both sides.
5 In installing the ZX-21, the infrared reflector should be placed in the main track wheels with a distance of 2 to 3 mm away from the code wheel sticker. Practically, if the sensor is attached to the copper tube as in step 5, the distance will be just right.
6 Then place the top structure that was removed back onto the AX-11 board. Connect the left signal cable from the ZX- 21 to terminal IN-8, and the right signal cable to terminal IN-7 of the AX-11 board. The Robo-11 SmartMover is now complete.
81
Used with the 18 color tab code wheel sticker; each color making a 20 degree angle. The output is a pulse signal which can be connected directly to a micro- controller.
The heart of this sensor module is the infrared reflector sensor and the code wheel sticker. The infrared light that is emitted from the sensor will reflect on the code wheel sticker. If it hits the black area, the photo-transistor will receive little reflected light, causing logic "1 to be sent to the digital receiver which consists of two notgets. However, if is it reflected onto a white or silver area, more reflection will occur and the photo-transistor will operate well, sending logic "0. When the wheel turns, alternate reflections like these will occur, causing pulse output signals. One complete round of t he wheel will give 9 pulse and 18 signals.
ZX-21 Code Wheel Reflector Sensor Measuring distance with the Encoder Wheel Sensor
The ZX-21 Encoder Wheel sensor will work in accordance with the code wheel sticker by detecting the infrared reflections from the code wheel sticker attached to the robot. The code wheel sticker has a diameter of 3.5 cm, with 9 alternating black and silver tab areas each; altogether resulting in 18 color tabs. If the arc of one color area is defined as s and d is the 3.5 cm diameter, thus
The circumference of the outer wheel is 2 r = (2*3.14*3.5/2) = 10.99cm
Distance s (one step range) has a value of d/18 = (3.14*3.5)/18 = 0.61cm
82 /*encoder_lib.ic*/ /* Hardware Configuration - Encoder left connect to port IN-8 - Encoder right connect to port IN-7 */ int LEFT =1; // Define for encoder left side channel int RIGHT =0; // Define for encoder right side channel int FORWARD = 1; // Define for drive robot forward int BACKWARD = 2; // Define for drive robot backward int SPIN_LEFT = 3; // Define for drive robot spin right int SPIN_RIGHT = 4; // Define for drive robot spin left int TURN_LEFT = 5; // Define for drive robot turn left int TURN_RIGHT = 6; // Define for drive robot turn right int POWER = 40; // Define power for drive robot and initial at 40% float STEP=0.0; // Variable for keep Global step
// Function for reset encoder left and right// void reset_encoder_all() { reset_encoder(LEFT); // Reset Encoder left side(IN-8) reset_encoder(RIGHT); // Reset Encoder right side(IN-7) } // Function for initial Encoder before working // void encoder_init() { enable_encoder(LEFT); // Enable count Encoder left side(IN-8) enable_encoder(RIGHT); // Reset count Encoder right side(IN-7) reset_encoder_all(); // Reset twice Encoder } // Function for read step for left/right side Encoder // int read_step(int ch) { read_encoder(ch); // Read count Encoder by channel reference return(read_encoder(ch)); // Return read count value }
The ZX-21 will count 1 every time the wheel code area shifts position to the next area tab, whether it is from black to silver (white) or silver (white) to black. The change of wheel codes our caused when the wheel turns. When the count changes or increases by 1, it means that the robot has moved 1 step, or a distance of 0.61 centimeters.
Encoder_lib.ic Library
To make it convenient in using the ZX-21 Encoder Wheel and the AX-11 board with the Interactive C program, a library for the wheel encoder to use when measuring the movement range for various operations of the robot was prepared. In this library, you will find a complete set of functions that involve the encoder wheel.
83 //------- Function for read total step ------------// float totel_s tep() { return(STEP); // Return Global s tep count } //------- Function for read total distance ----------// float total_dis t() { return(STEP*0.61); // Return Global distance count } //------- Function for c lear total step c ount ---------// void clear_dist_all() { STEP = 0.0; // Clear Global step count value } //------- Function for c ount step by reference ---------// void count_step(int sel_move,int s tep,int s el_count) { int flag=0,left,right; reset_encoder_all(); // Reset twice E ncoder if(s el_move==FORWARD) // Condition forward FD(); else if(sel_move==BACKWARD) // Condition backward BK(); else if(sel_move==SPIN_LEFT) // Condition spin left S_LEFT(); else if(sel_move==SPIN_RIGHT) // Condition spin right S_RIGHT(); else if(sel_move==TURN_LEFT ) // Condition turn left T_LEFT (); else if(sel_move==TURN_RIGHT) // Condition turn right T_RIGHT(); while(! flag) // Loop for check c ount step { left = read_step(LEFT ); // Read step left right = read_step(RIGHT); // Read step right if(s el_count==LEFT && left>=step) // E ncoder left side complete? flag = 1; // Set flag when c ount complete else if(sel_count==RIGHT && right>=s tep) // Encoder right side c omplete? flag = 1; // Set flag when c ount complete } ao(); // O ff all motor if(s el_move==FORWARD || sel_move==BACKWARD) // Condition update Global step count { STEP = STEP + (float)read_step(s el_count); // Update s tep count if drive robot forward or backward }r eset_encoder_all(); // Reset twice E ncoder } //------- Function for distance counting by reference ------// void count_dist(int a,int b,int c ) { count_step(a,(b*100)/61,c ); // Calc ulate distance to step count and // drive robot in this result } //------- Robot forward driving func tion ----------// void FD() { motor(0,PO WER); // Motor 0 forward motor(1,PO WER); // Motor 1 forward }
84 //------- Robot backward driving function ----------// void BK() { motor(0,-POWER); // Motor 0 backward motor(1,-POWER); // Motor 1 backward } //------- Robot spin left function ----------// void S_LEFT() { motor(0,-POWER); // Motor 0 backward motor(1,POWER); // Motor 1 forward } //------- Robot spin right function ----------// void S_RIGHT() { motor(0,POWER); // Motor 0 forward motor(1,-POWER); // Motor 1 backward } //------ Robot turn left function ----------// void T_LEFT() { off(0); // Motor 0 break motor(1,POWER); // Motor 1 forward } //------- Robot t urn left function ----------// void T_RIGHT() { off(1); // Motor 1 break motor(0,POWER); // Motor 0 forward }
Explanations of the functions
Two ZX-21 encoder wheel sensors are referenced when the user calls upon the functions in the encoder_ib.ic library: the left sensor which is connected to port IN-8 and the right sensor which is connected to port IN-8 of the AX-11 board. The M-0 slot is also used to drive the left motor wheel of the robot and the M-1 to drive the right wheel.
In the beginning of the program, if the user wants to use this library, he or she must call upon it by using the command #use "encoder_lib.ic. In the first part of the program, and within the main function, the user must call the encoder_init function in order to be able to start using both encoder wheels.
85
1. reset_encoder_all function
Used to clear the count values from the encoder wheel sensor and start again.
Function Format
Void reset_encoder_all ()
2. encoder_init function
Used to initiate the encoder wheel sensor. In writing a program, this function must be called at the beginning of the main program.
Function format Void encoder_init()
3. read_step function
Used to read the count value from the encoder wheel sensor
Function format Int read_step (int ch)
Parameters Ch Used to choose the encoder wheel sensor that the user wants to read.
Define Left if you want to read the value from the left encoder wheel Define Right if you want to read the value from the right encoder wheel
Return Value
The return value is the step count received from the encoder wheel specified.
86
4. Total_step function
Used to read the cumulative values from the encoder wheel sensor by measuring the steps only when the robot moves forward and backwards. The variable STEP is used to store the cumulative steps.
Function format Float total_step ()
Return Value The return value is the cumulative step count read from the encoder wheel.
5. Total_dist function
Used to read the cumulative distance from the encoder wheel sensor by measuring the distance only when the robot moves forward and backwards. Calculate with 1 step equal to 0.61 centimeters.
Function format Float total_dist()
Return Value The return value is the cumulative distance read from the encoder wheel.
6. clear_dist_all function
Used to clear the cumulative count.
Function format Void clear_dist_all()
87
7. count_step function
Used to command the robot to move according to the number of steps defined.
Function format Void count_step (int sel_move, int step, int sel_count)
Parameter Sel_move used to specify how the robot moves as following:
Forward for forward movement Bacward for backward movement Spin_left To rotate left Spin_right To rotate right Turn_left To turn left Turn_right To turn right
Step Used to define the number of steps that the user wants Sel_count Used to choose which encoder wheel sensor to read from, as following
Left choose the left encoder wheel Right choose the right encoder wheel
8. count_dist function
Used to command the robot to move according to a specified distance; modified from the count_step function.
Function format Void count_dist (int a , int b, int c)
88
Parameters
a Used to define the robot movement as following
Forward for forward movement Bacward for backward movement Spin_left To rotate left Spin_right To rotate right Turn_left To turn left Turn_right To turn right
b Used to define the distance the user wants in centimeters c Used to choose the encoder wheel sensor that is to be used, as following
Left choose the left encoder wheel sensor Right choose the right encoder wheel sensor
9. FD function
Used to drive the robot forward
function format void FD()
10. BK function
Used to drive the robot backwards
function format void BK()
11. S_Left function
Used to make the robot to rotate left
Function format void S_LEFT()
89
12. S_Right function
Used to make the robot to rotate right
Function format void s_right()
13. T_Left function
Used to make the robot turn left
Function format T_LEFT ()
14. T_RIGHT function
Used to make the robot turn right
Function format T_RIGHT ()
15. POWER variable
Use to define the driving power of the robot, with values from 0% to 100%. If the value is not specified in the program, the initial value is 40% (POWER = 40) as defined in the library.
90
Robo-11 SmartMover Test
The test program for the Robo-11 SmartMover robot can be separated into two tests. The first is to let the robot move a specified distance, which is the basic test for the robot and the encoder wheel sensor. Then add another operation for the robot to follow by letting it move in the shape of a character from the alphabet. This shows how the encoder wheel sensor can be used in more complex situations to make the robots turns and changes of direction more accurate.
60 cm-mover: Drive the Robo-11 SmartMover forward for 60 centimeters
Type in the following program and download it into the Robo-11 SmartMover
/*Example for Robot samrt movement by reflective encoder sensor and codewheel */ /* - Encodder pulse left connected to IN-8 - Encodder pulse right connected to IN-7 */
#use "encoder_lib.ic /*Include Library file encoder_lib.ic*/ void main() { encoder_init(); // Initial Encoder POWER = 50; // Set power at 50% printf("Press Start!\n); // Show begining message while(1) // Infinite loop { while(! start_button()); // Wait START button pressed printf("\n); // Clear LCD display count_dist(FORWARD,60,RIGHT); / Forward 60 cm reference with // Encoder right side printf("STEP %f\n,total_dist()); // Display step count value } }
91
Testing It
Place the Robo-11 SmartMover on the floor and then turn on the POWER switch. The LCD screen displays the message Press Start. Press START on the AX-11. The robot will move forward using only 50% of its power for a distance of 60 centimeters and stops, as well as displaying the distance moved. If the START switch is pressed again, the robot moves forward for another 60 centimeters, stops, and displays the cumulative distance which it moved. The value will have increased from the original value by 60 cm.
For this program, the line #use "encoder_lib.ic must be used to call upon the functions in the encoder_lib.ic library that will be used with the ZX-21 encoder wheel sensor. Then initiate the encoder wheel sensor by using the function encoder_init, followed by defining the motor power to 50% of its maximum power. Next, a message appears on the LCD awaiting the START switch to be pressed. The robot will then move forward for a distance of 60 centimeters and stops. The robot will display the cumulative distance on the LCD. If the START switch is pressed again, the robot will operate in the same way, while the cumulative value that is displayed will increase by 60 centimeters each time.
U-mover: Driving the Robo-11 SmartMover in a U-Shape
Type in the following program and download it to the Robo-11 SmartMover
/*Example-2 for Robot samrt movement by reflective encoder sensor and codewheel */ #use "encoder_lib.ic /*Include Library file encoder_lib.ic*/ void main() { encoder_init(); // Initial Encoder printf("Press Start!\n); // Show begining message while(1) // Infinite loop { while(! start_button()); // Wait START button pressed clear_dist_all(); // Clear total distance printf("\n); // Clear display count_dist(FORWARD,60,RIGHT); // Robot forward 60 cm reference by // Encoder right side count_step(SPIN_RIGHT,18,LEFT); // Robot spin right 18 step reference // by Encoder left side count_dist(FORWARD,60,RIGHT); // Robot forward 60 cm // reference by Encoder right side count_step(SPIN_RIGHT,18,LEFT); // Robot spin right 18 step // reference by Encoder left side count_dist(FORWARD,60,RIGHT); // Robot forward 60 cm // reference by Encoder right side } }
92 Testing It
Place the Robo-11 SmartMover on the floor and then turn on the POWER switch. The LCD screen displays the message Press Start. Press START on the AX-11. The robot will move forward using only 50% of its power for a distance of 60 centimeters and rotate right. Then it will move forward for another 60 centimeters, rotate right again, and move another 60 centimeters. It will continue to repeat these actions. If the user looks down from a top view, he will see that the robots movements are of that similar to the English alphabet U.
However, in this program, if the robot needs to make a 90 degree turn to get the desired direction, the user may sometimes have to use the count_step or count_dist function. In this test, to get a 90 degree turn, the following values must be specified count_step(SPIN_RIGHT, 18, LEFT); In the actual results, the robot may not be able to rotate 90 degrees exactly due to the fact that the rotational axis may not always be stable. To fix this problem, test by letting the robot rotate at different step values until it gets the desired angle.
93 With the ZX-08* digital sensor, the robot has yet another means to detecting obstacles by infrared light without making any contact with the object.
* Additional component that does not come with the set
BUILDING THE OBJECTOR 1 Using the Robo-11 Standard robot (or the Robo-11 Liner2), take a strength joiner and attach it to the right corner at the front of the robot with a 3 x 10 screw and 3 mm nut as shown in the picture. Do not screw in tightly yet.
2 Attach an obtuse joiner onto the strength joiner, with the obtuse angle facing inwards.
3 Next, place a strength joiner to the end of the obtuse joiner. You will get a robotic arm to place the sensor.
94 4 Twist the arm to the right, making an angle of 45 degrees with the robot. Then screw in the screw and nut together tightly.
5 Install the ZX-08 sensor to the strength joiner at the end of the robot arm with a 3 x 10 mm screw and 3 mm nut. Screw in tightly.
6 Create another robotic arm to install another ZX-08 by using steps 1-4.
7 Install the ZX-08 to the end of the robotic arm that was just built. Then connect the signal cables as following:
(1) Connect Tx at the left of the ZX-08 to terminal OUT-0 (2) Connect Rx at the left of the ZX-08 to terminal Dl010 (3) Connect Tx at the right of the ZX-08 to terminal OUT-1 (4) Connect Rx at the right of the ZX-08 to terminal Dl-11
The Robo-11 Objector is now complete and ready for the test program.
95
ZX-08 Infrared Sensor
This sensor has both the infrared light receiver and transmitter within itself. The ZX-08 sensor can detect obstacles at a maximum distance of 6 centimeters. The Rx signal cable must be connected to the digital input (Dl or IN), while the Tx must be connected to any digital output (OUT) on the AX-11 board. Once the signal cables are connected, sending logic "1 to Tx will make the infrared LED on the ZX-08 module light up. If there is an obstacle blocking in front, the infrared light will send reflect that object back to the infrared receiver, causing a logic "0 to be sent to the AX-11 input.
96 /* Example for Robot infrared detector sensor by called ZX-08 - Motor left connected to DC Motor channel M-0 - Motor right connected to DC Motor channel M-1 - TX of ZX-08 left side connected to OUT-0 - TX of ZX-08 right side connected to OUT-1 - RX of ZX-08 left side connected to DI-10 - RX of ZX-08 right side connected to DI-11 */ #define pow 50 /*Configuration power drive motor*/
void main() { int obj_left,obj_right; // For keep result detect object printf("Press Start! \n); // Show begining message start_press(); // Wait START button pressed printf("Robot Move...\n); // Show running message set_digital_out(0); // Send TX ir signal to left sensor set_digital_out(1); // Send TX ir signal to right sensor while(! stop_button()) // Infinite loop { obj_left = digital(10); // Get detection result from left sensor obj_right = digital(11); // Get detection result from right sensor if(obj_left==0 && obj_right==0) // If left and right do not detect object { run_fd(0.1); // Forward 0.1 second } else if(obj_left ==0 && obj_right ==1 ) // If right sensor detect object { run_bk(0.5); // Backward 0.5 second turn_left (0.5); // Turn left 0.5 second } else if(obj_left ==1 && obj_right ==0 ) // If left sensor detect object only { run_bk(0.5); // Backward 0.5 second turn_right(0.5); // Turn right 0.5 second } else if(obj_left ==1 && obj_right ==1 ) // If both sensor detect object { run_bk(0.5); // Backward 0.5 second turn_right(1.0); // Turn right 1.0 second } }
Robo-11 Objector Test
The next step would be to write a test program to test the operation of the Robo-11 Objector by having it detect objects by not touching or colliding with the objects and then to change directions to avoid that object.
Type in the following program code and download it to the Robo-11 Objector.
97 ao(); // O ff motor all channel beep(); // Sound alarm printf("Stop...\n); // Show ending message } void turn_left(float spin_time) { motor(0,-pow); // Motor0 backward with pow value motor(1,pow); // Motor1 forward with pow value sleep(spin_time); // Delay set by parameter spin_time } void turn_right (float spin_time) { motor(0,pow); // Motor0 forward with pow value motor(1,-pow); // Motor1 backward with pow value sleep(spin_time); // Delay set by parameter spin_time } void run_fd(float delay) { motor(0,pow); // Motor0 forward with pow value motor(1,pow); // Motor1 forward with pow value sleep(delay); // Delay set by parameter delay } void run_bk(float delay) { motor(0,-pow); // Motor0 backward with pow value motor(1,-pow); // Motor1 backward with pow value sleep(delay); // Delay set by parameter delay }
Testing It
Place the Robo-11 Objector on the floor and then turn on the POWER switch. The LCD screen displays the message Press Start. Press START on the AX-11. The robot will move forward using only 50% of its power. At the same time, the display screen will show the message "Robot Move.
When the left sensor finds an object: The Robo-11 Objector robot will move backwards for 0.5 seconds and turn right for 0.5 seconds. Then it will continue to move forward.
When the right sensor finds an object: The Robo-11 Objector robot will move backwards for 0.5 seconds and turn left for 0.5 seconds. Then it will continue to move forward.
The robot will stop when the STOP switch is pressed.
98 Increase the Robo-11 robots capability in detecting objects at a far distance without any making contact by using the SRF04* Ultra Sonic Sensor
* Additional component that does not come with the set.
BUILDING THE SONAR ROBOT 1 Using the Robo-11 Standard robot (or the Robo-11 Liner2), take an angled joiner and attach it to the front of the robot with a 3 x 10 screw and 3 mm nut at position 1, 6 as shown in the picture. Let the right angle face outwards and screw together tightly.
2 Take another angled joiner and attach it to the angled joiner from step 1. Make sure the other end is facing the left of the robot as shown in the picture.
3 Then take another angled joiner and attach it to the angled joiner from step 2. . Make sure the other end faces the front of the robot at shown in the picture.
99 4 Yet another angled joiner is taken and attached to the angled joiner from step 3. This time, let the right angle side face the front of the robot.
5 Take the SRF04 module and attach it to the ADX-SRF04 board. Then install it to the angled joiner from step 4 using a 3 mm plastic spacer, 3 x 10 mm screw, and 3 mm nut. Attach the ADX-SRF04 to the top right corner (looking in from the front of the robot and SRF04 module)
6 Connect the signal cables of the ADX-SRF04 board to the ports on the AX-11 board as following:
a. Connector ECHO to terminal IC1 of the AX-11 b. Connector PULSE to terminal IN-9 of the AX-11
The Robo-11 Sonar is now complete and ready to be tested.
10 0
/*Example for object detection of Robo-11 by sonar sensor */ /* Hardware configuration - ECHO pin connected to IC1 - TRIGGER PULSE pin connected to IN-9 - Motor left connected to DC Motor chanel M-0 - Motor right connected to DC Motor chanel M-1 */ #use "srf04_lib.ic /* Include library srf04_lib.ic */ #define pow 50 /*Configuration power drive motor*/ void main() { int result; // Define variable for storing distance value ao(); // Off all motors sonar_init(); // Initial sonar sensor printf("Press Start!\n); // Show begining message while(! start_button()); // Wait START button pressed beep(); // Drive beep sound while (!stop_button()) // Check STOP button pressed { result = sonar_sample(); // Get and store distance value if (result <= 20 && result >= 0 ) // Check distance <=20 and >=0 ? // if TRUE escape
SRF04 ULTRASONIC SENSOR +5V power supply and 30 mA currency Uses a 40 kHz ultrasonic receiver and transmitter Measures a distance of 3 cm - 3m 10 micro-second pulse signal Returns a pulse signal in which the pulse width is proportional to the measured distance. Small in size: 43 mm x 20 mm x 17 mm (w x l x h)
The SRF04 will send the ultrasonic frequency signal out and then measure the time for the signal to reflect back. The output from the SRF04 is in the form of a pulse, in which the width is proportional to the distance of the detected object. The ultrasonic frequency of the SRF04 is 40 kHz.
Robo-11 Sonar Test
The test program of the Robo-11 Sonar will emphasize on communicating with the SRF04 module in order to detect and measure the distance between the robot and an object. The results that were measured will then be used to determine the movements of the robot so that it can avoid the obstacles without having any contact with the object.
Type in the following program code and download it to the Robo-11 Sonar.
10 1 {run_bk(0.5); // Backword 0.5 second turn_left (0.5); // Turn left 0.5 second } else { run_fd(0.1); // Forward 0.1 second }} beep(); // Sound beep ao(); // Off all motors } void turn_left(float spin_time) {motor(0,-pow); // Motor0 backward with pow value motor(1,pow); // Motor1 forward with pow value sleep(spin_time); // Delay set by parameter spin_time } void turn_right(float spin_time) {motor(0,pow); // Motor0 forward with pow value motor(1,-pow); // Motor1 backward with pow value sleep(spin_time); // Delay set by parameter spin_time } void run_fd(float delay) {motor(0,pow); // Motor0 forward with pow value motor(1,pow); // Motor1 forward with pow value sleep(delay); // Delay set by parameter delay } void run_bk(float delay) {motor(0,-pow); // Motor0 backward with pow value motor(1,-pow); // Motor1 backward with pow value sleep(delay); // Delay set by parameter delay } Testing It
Place the Robo-11 Sonar on the floor and then turn on the POWER switch. The LCD screen displays the message Press Start. Press START on the AX-11. The user will hear a beep sound and then robot will move forward using only 50% of its power.
When the robot moves closer to the obstacle and is within the specified distance : The Robo-11 Sonar robot will move backwards for 0.5 second and rotate left for 0.5 seconds. Then it will move forward.
The specified range to detect obstacles in this test is 20 cm.
The robot will stop when the STOP switch is pressed. You will hear the beep again before it stops.
The Robo-11 Sonar is an example of using special communication with the sensor by using pulse counts, which is different from the GP2D120 module which returns a voltage value, or the ZX-08 module which returns basic logic signals.
10 2 Increase the capability for the Robo-11 to locate a position and direction by using the CMPS03 Electronic Compass module which uses a magnetic field sensor in locating a particular direction. BUILDING THE COMPASSOR 1 Using the Robo-11 Standard robot (or the Robo-11 Liner2), take an angled joiner and attach it to the front of the robot with a 3 x 10 screw and 3 mm nut at position 1, 6 as shown in the picture. Let the right angle face outwards and screw together tightly.
2 Take a strength joiner and attach it to the other end of the angled joiner from step 1.
3 Take another strength joiner and attach it to the other end of the strength joiner from step 2.
10 3 4 Yet another strength joiner is taken and attached to the strength joiner from step 3 5 Take an angled joiner and attach it to the other end of the strength joiner from step 4, making sure the end of the joiner faces the front of the robot. The structure is now ready for the CMPS03 to be installed.
6 Attach the CMPS03 module to the ADX-CMPS03 board and then install it onto the structure built in steps 1- 5. Use a plastic spacer, a 3 x 10 mm screw, and a 3 mm nut, and screw them in together tightly.
Next connect the signal cable from terminal PWM of the ADX-CMPS03 to terminal Dl-14 of the AX-11 board. The Robo-11 Compassor is now complete.
10 4 CMPS03 Electronic Compass Module
Uses a +5V power supply and 20 mA currency Uses two of Phillips KMZ51 magnetic field sensors 0.1 degree accuracy, with approximately 3-4 degree error rate. Pulse output with a width of 1 to 37 ms and 0.1 ms increment rate. I 2 C Bus system output which sends data in two formats: 0 to 255 and 0 to 3599.
Robo-11 Compassor Test
Adjust the Reference direction for the Robo-11 Compassor robot
In the following preparations, the direction of the CMPS03 Electronic Compass module will be defined and adjusted so that it can be used as the main reference value. The value will then be stored in the internal memory of the CMPS03, which will be done only once. This reference data will not be erased even if there is no power supplied to the CMPS03.
1. Turn the power switch of the Robo-11 Compassor on. 2. Place the robot on an empty field and face it towards the north. Press the switch on the ADX-CMPS03 once and let it go. 3. Then turn the robot so that it is facing east. Press the switch on the ADX-CMPS03 once more and let it go. 4. Then turn the robot to face south. Press the switch on the ADX- CMPS03 once more and let it go. 5. Last, turn the robot to face west. Press the switch on the ADX- CMPS03 once more and let it go. Now the CMPS03 compass module can tell directions accurately.
Writing the test program for the Robo-11 Compassor
In this test program for the Robo-11 Compassor, we will imagine that the robot is placed in a very large field with a smooth surface, making it unable to check its movement by touch or by its reflector sensors. The only method left is to use the electronic compass module to detect the magnetic field and use it to determine which direction it should move next.
Type in the following program and download it to the Robo-11 Compassor robot.
10 5 /*Example for Robot movement control by compass sensor */ /* Hardware configuration - PWM channel from adapter board(CMPS03) connected to DI-14 - Motor left connected to DC Motor chanel M-0 - Motor right connected to DC Motor chanel M-1 */ #use "cmps03_pwm_lib.ic /* Include library srf04_lib.ic */ #define pow 40 /*Configuration power drive motor*/
void main() { long result; // Definf variable for storing angle value ao(); // O ff all motors CMPS03_set_channel(14); // Initial CMPS-03 sensor used DI-14 printf("Press Start! \n); // Show begining message while(! start_button()); // Wait START button pressed beep(); // Sound beep while (! stop_button()) // Check STOP button pressed { result = read_angle(); // Keep angle value printf("Angle %d\n,result); // Display angle if (result > 0L && result <= 40L) // Check angle value <=40 ? // if TRUE escape { run_fd(0.05); // Forward 0.05 second } else { turn_left (0.05); // Turn left 0.05 second } } beep(); // Sound beep ao(); // O ff all motors } void turn_left(float spin_time) { motor(0,-pow); // Motor0 backward with pow value motor(1,pow); // Motor1 forward with pow value sleep(spin_time); // Delay set by parameter spin_time } void turn_right (float spin_time) { motor(0,pow); // Motor0 forward with pow value motor(1,-pow); // Motor1 backward with pow value sleep(spin_time); // Delay set by parameter spin_time } void run_fd(float delay) { motor(0,pow); // Motor0 forward with pow value motor(1,pow); // Motor1 forward with pow value sleep(delay); // Delay set by parameter delay } void run_bk(float delay) { motor(0,-pow); // Motor0 backward with pow value motor(1,-pow); // Motor1 backward with pow value sleep(delay); // Delay set by parameter delay }
10 6
Testing It
Place the Robo-11 Compassor on the test field and then turn on the POWER switch. The LCD screen displays the message Press Start. Press START on the AX-11. The user will hear a "beep sound. The robot will then locate its position to see which angle or direction it is facing by reading the values from the CMPS03 module. It will also display the results (Angle xxx: where xxx is the angle value read). If the angle is not equal to the specified angle, the robot will rotate left in intervals of 0.05 seconds until it finds the angled desired. The robot will then proceed to move forward using only 40% of its power. The robot will continue to check the angle value as it moves to ensure that it is moving in the right direction. The desired direction is at an angle of 0 to 40 degrees.
The robot will stop when the STOP switch is pressed. The user will hear a beep before it stops.
The Robo-11 Compassor is an interesting example of developing small automatic robots that can move on its own, with the help of efficient modules such as the CMPS03, a widely used sensor in the RoboCup Junior competition, or the International Football Robot Junior Championship. This is because the competition field usually does not have any reference points for the robot to detect its position, and thus the electronic compass module is very helpful.
The values read from the CMPS03 module is the measured width of the PWM signal, which is another example of signal processing that is different from all the other sensors.