Robo-11 - INEXGLOBAL2 Robo-11 : Interactive C Robot kit Activity book The AX-11 68HC11...
Transcript of Robo-11 - INEXGLOBAL2 Robo-11 : Interactive C Robot kit Activity book The AX-11 68HC11...
Robo-11 : Interactive C Robot kit Activity book1
Robo-11Interactive C robot kit
Activity bookconstruction
programming referencefull sourcecode for all robot activities
(C) Innovative Experiment Co.,Ltd.
2Robo-11 : Interactive C Robot kit Activity book
The AX-11 68HC11 Microcontroller Activity board is developed based-on Handyboard
and Extension board; the open source controller board from MIT, USA. The current version
is Revision 6 (R6). Innovative Experiment Co.,Ltd (Thailand) modify and change some
libraries to support many alternate functions. All information of hardware modification is
opened to public.
The Handy Board is distributed under MIT’s free licensing policy, in which the design may
be licensed for for personal, educational, or commercial use with no charge.
Interactive C (IC) is provided free of charge as a service to educators and the general
public. IC7.08ax supports the Handy Board with Expansion Board and AX-11 board. IC is
property of KISS Institute for Practical Robotics, a 501(c)3 nonprofit organization.
Interactive C was written by Randy Sargent of the KISS Institute for Practical Robotics.
Randy was assisted by Mark Sherman. Portions of the code and the libraries are based on
the public distribution of Interactive C 2.8 written by Randy Sargent, Anne Wright and
Fred Martin.
Robo-11 : Interactive C Robot kit Activity book3
Contents
Chapter 1 : Hardware Introduction..........................................................5
Chapter 2 : Building Robo-11 Standard..................................................21
Chapter 3 : Interactive C Programming Reference.................................45
Chapter 4 : Interactive C Library..............................................................75
Chapter 5 : Robo-11 Attacker................................................................87
Chapter 6 : Robo-11 Ranger...................................................................91
Chapter 7 : Robo-11 Liner.........................................................................99
Chapter 8 : Robo-11 SmartMover.............................................................115
4Robo-11 : Interactive C Robot kit Activity book
Robo-11 : Interactive C Robot kit Activity book5
Interactive C robot kit is a high performance robot kit in C programming for
power hungry hobbyist. Included is the 68HC11 microcontroller board : AX-11, Additional
sensors : Switch-IR reflector-GP2D120 IR, Ranger-Encoder wheel detector, 2 DC gearboxes
and Mechanical parts for build and modified 8 sample robot.
1.1 Components used in buildinga small automatic robot; Robo-111.1.1 AX-11 Activity board
The AX-11 is a modified version of the popular Handy board from MIT and the first
ever microcontroller board used for learning C language by Interactive C programming.
The AX-11 is a 6811-based microcontroller system that lets you build mobile robots for
educational, hobbyist, and industrial purposes. People use the AX-11 Board to run robot
design courses and competitions at the university and high school level, build robots for fun,
and control industrial devices.
This board uses the 68HC11 microcontroller and has 32KB non-volatile RAMs, 9-
digital inputs , 21-analog inputs, 4-DC motor driver, 6-Servo motor driver, 16x2 LCD module
for displaying and RS-232 serial port interface circuit with computer fro downloading the
program.
The AX-11 activity board features :
68HC11 microcontroller
32KB RAMs with backup system
9-digital inputs
8-bit Analog to Digial Converter 21-channel
Input Capture and Output compare port for interfacing special sensors
such as Ultrasonic ranger, Encoder, Digital Compass
4-DC motor driver with indicators
6-Servo motor driver
a 16x2 LCD module with LED back light for displaying
2 of Button switch for START and STOP operation
Chapter 1Hardware introduction
6Robo-11 : Interactive C Robot kit Activity book
One KNOB for Analog to Digial Converter demonstration
Piezo speaker
RS-232 serial port interface for downloadin and interaction the software
6 pieces of AA battery holder. Support all alcaline and rechargable type
Buit-in recharging circuit
+7.2 or +9Vdc supply from battery (not included) or +12Vdc supply from
DC adaptor
The AX-11 activity board are designed to support the learning of microcontroller
with high language programming in C by Intreractive C. Besides you can use the AX-11
activity board to study about 68HC11 microcontroller architecture with Assembly langauge
programming or Basic or ANSI C.
With expansion ports, you can interface 68HC11 microcontroller with simple and
advance external devices such as Real-Time Clock IC, Ultrasonic ranger, 2-wires devices,
Digital compass and more.
Robo-11 : Interactive C Robot kit Activity book7
)**
+#,
-
.
.
.
."
.
.#
.
.$
#
%
'
$
#
"
,/
+#,
,
#
#
,0
,
123
"
!4
4
4
!4
5.
""
#
+#,
#
6,
780"
6,
6,
6,
%$
79
12 7
17 2
8:
5.
17 2
12 7
8:
#
"
+#,
"
" 28
"
#
$
'
"
#
" # $ % '
"
#
$
9
9
9
9"
9
9#
9
9$
0(
+#,
' % $ # "
"
#
$
"
#
$
%
'
"
#
$
#
"'
"%
"$
"
"#
%
'
"
%
'
"
#
"
"#$
#
6&
(
(
( (!
+#,
6&
( &
,
+,**
-
("**;
:7$
"
5.
+,
( (!
8
"
8 "
# 8
+#,
%
$
%
"
#
$
9
9
9
9"
9
9#
9
9$
80:
# $ '
7" 7
2<!"
"
+#,
"
#
+,*
#4%
-
5.
(
5.
(
;6#,
%
2<!
2<!
2<!
7 7 8
+ +
"
8
# $ '
7" 7
2<!"
"
+#,
'%
#
+,*
-
-
5.
(
5.
(
;6#,
%
2<!
2<!
2<!
7 7 8
+ +
"
8
=
=$
'
" # $ % '
2
2
2
2"
2
2#
2
2$
"
#
$
2(
12
>7
78
78"
+#,
# $
"
#
'
%$
"
!"#$ %"$$&"
28
-
78
$
""
"
%
"
'
28"
+#,
+#,
-
-
-
$-
-
5."**;
'
$/8"%
1
#
$/8#$"
$/8#
+#,
0'"
0'"
$/8
18%/8(
-
#%"$!"
( )*"+ !,*-+"
./
-4%
-4"
0
1
%&" !&"$
2
%&" !&"$
? ?
+
@" !3!&"#$ 4!,
#,
=(0"**;
56
'
:7$%#
4
3
.1/**
/)-
67/
8
67/
+#,
6,";6#,
79
79
'
%
'
%
$
#
"
5
$
"6&
$
%
$
#
"
2(
'
70
+#,
" % $
$ " %
"
#
$
9
9
9
9"
9
9#
9
9$
+#,
$/8$"
' #
# '
="
=#
" # $ % '
"
#
$
9
9
9
9"
9
9#
9
9$
80:
+#,
$/8#$'
%
$
#
"
0("
8
#8
+#,
#
"
' $=$
=
=#
=
="
=
=
=
%
7.'
,((
$
+#,
"
#
# =$
=
=#
=
="
=
=
=
+#,
2
1
0
$/8#
$/8"$
90
9
9
9
9
9
+,
+#,
"821
-
=(0"**;
"&"
# &!$
%&"
!&"$
+#,
+#,
+#,
79
!4
4
2<.
28#
"
6,
+
+#,
+#,
+#, -
7
7
7
7
7
7
72
-
+#,
$-
+#,
$-
.#%'
8(178
( 2.!2
%1/A
"
!
80:
!
" % $
$ " %
' #
# '
+
6,
7.'
,((
$
+#,
"
#
# =$
=
=#
=
="
=
=
=
2
1
0
"821
,
%
,
%
;6#,
;6#,
$/8#
;6#,
-
+,**
+#,
8'
$
#
:
,
,((
,
$6,
$-
.#%'
B#,
$
;""
#;#,
.#%'
.#%'
2(
;6#,
;6#,
;6#,
2(
,"
;6#,
;6#,
-
+#,
;6#,
;6#,
;6#,
$/8
"
$/8
#
+#, $
$/8
;6#,
;6#,
+#,
;6#,
+#,
;6#,
"
6#,
+,*
:7$%
$6
"
$6
4;#
;
.#%' 6,"
:!=
;1
8Robo-11 : Interactive C Robot kit Activity book
!!"#
#"$%!$#"##&'(!'&'&!
'&)*!
+ !%,!$- )%!'&)*! -./' "00! &*# 1 -
#"$!-$)'%!0/$#"# ! -2#$!*!!0!!
"1*AC)
Robo-11 : Interactive C Robot kit Activity book9
!)C);7)C*%
*;
AX-11 activity board interfaces with computer serial port for downloading the In-
teractive C firmware and code. User code will be stored in memory with back up circuit.
The code is saved although the power off about 250 hours continually. The LOW BATT red
indicator will shows if the battery low power. It need to change the battery if you use
alcaline type and charge with the external DC adaptor. AX-11 board has built-in low
current battery charger circuit. If use 1800mAH, need 16 hours charging time. User who
need to speed the battery charging, the external battery charger is required. We suggest
use the 1 or 2 cells battery fast chargere; V-6280 Vanson (show in the Figure 1-4).
1.1.2 Universal PlatePlate 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.
10Robo-11 : Interactive C Robot kit Activity book
1.1.3 Motor GearboxUses a 4.5 to 6V and 180 mA DC motor with a ratio of 48:1 ; torque 2kgF/cm; and
120:1 ; torque 4kgF/cm. Two sets per type are provided.
1.1.4 TrackThere are 3 sizes. Four 8-Joint tracks; Four 10-Joint Tracks; and two 30-joint tracks.
1.1.5 Angled Shaft BaseTwo pieces of each the long base and short base are provided.
1.1.6 Metal Axel4 mm in diameter and 100 mm in length. Four axels come in the set.
Robo-11 : Interactive C Robot kit Activity book11
1.1.7 WheelsThere are four different types which are Main sprocket (2 pieces), Large Track Sup-
port Wheel (2 pieces), Medium Track Support Wheel (10 pieces) and hubs (12 pieces).
1.1.8 Knobby PlateThis is used to attach the AX-11 with the universal plates.
1.1.9 Plastic Joiner60 pieces of varied color joiners made from PVC plastic. They can be connected
together or by using screws and 3 mm nuts in installation. There are 4 types; Right angle,
Obtuse, Straight joiner and Hole straight joiner.
The hole straight joiner has 3 sizes; 3, 5 and 12 holes.
1.1.10 Nut and Screw SetThere are 2 of 2mm. tap screws, 4 of 3x7mm. screws, 30 of 3x10mm. screws, 4 of 3
x15 mm. screws, 4 of 3x40mm. screws, 30 of 3mm. nuts and 4 of 3mm. Thumb screws.
12Robo-11 : Interactive C Robot kit Activity book
1.1.11 Spacer and StandoffsThey are some mechanical parts for supporting the plate and sensor board. This kit
includes 4 pieces set of plastic spacer (3mm., 10mm., 15mm. and 25mm.) 4 sets, 4 of
30mm. metal hexagonal standoffs.
1.1.14 Switch InputThe switch input is used to detect collision at logic “0”. Two sets along with the
connecting cable are provided.
1.1.15 IR ReflectorUsed to detect the perimeter, lines, and the wheel code. The results are in voltage.
Three sets along with the connecting cable are provided.
1.1.16 IR RangerMeasures distance ranging from 4 to 30 cm using infrared light. The results are in
voltage.
Robo-11 : Interactive C Robot kit Activity book13
1.2 Interactive C software1.2.1 System requirements
CPU Celeron 300MHz or higher
10MB Harddisk space
32MB RAM or higher
CD-ROM drive
Free serial port RS-232 or USB to Serial port converter if computer available only
USB port (UCON-232S is recommended).
Microsoft Windows 98SE or higher, Window XP service pack 2 is recommended.
1.2.2 Installation(1) Insert AX-11 CD-ROM to CD-ROM drive.
(2) Enter to Software folder and double-click on the IC708axSetup.exe. The setup
window will appear. Click on the Next button to begin the installation and click the OK or
Next button in every step until the installation complete.
14Robo-11 : Interactive C Robot kit Activity book
1.3 About power source of AX-11The preparations that we are about to talk about is writing the main control pro-
gram, 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 program-
mer.
1.3.1 First time using AX-11 or changing the new battery(1) Upside down the AX-11 board. Open the battery holder cover. Put 6 pieces of
AA battery. Becareful the battery polarity.
(2) Turn-on the POWER switch. If the batttery power level more enough, the green
PWR. LED will light.
(3) In first time using, at LCD screen of the AX-11 activity board will display :
If no anything to show, may be from 2 reasons as follows.
(3.1) Firmware lost. Need to download again.
(3.2) There is any code into AX-11 memory. User can download the new
code to run continue.
Normally, AX-11 board has the memory back-up system. It can save the data or
code about 250 hours (10 days approximation). Therefore the changing new battery af-
ter empty will not affect to the memory.
Robo-11 : Interactive C Robot kit Activity book15
1.3.2 Use the external DC power supply(1) Interactive C robot kit provides the adjustable DC adaptor for supplying the AX-
11 activity board. Before using, select the output voltage to +12V. Plug the DC adaptor to
a wall outlet.
(2) Make sure the battery holder of the AX-11 board empty. Do not connect theDC adaptor to AX-11 board if the alcaline batteries are in the holder except using
the rechargable batteries.
(3) Connect the DC adaptor to the DC in jack of AX-11 board, making sure the
power switch is off.
(4) Turn-on the POWER switch. The green PWR. LED will light following the figure below.
WARNING ! : If using the external DC adaptor, MUST REMOVE or DO NOT PUT ANY ALCALINEBATTERIES INTO THE BATTERY HOLDER to protect the alcaline batteries burning.
>7
78
78"
7.'
7.%
7.$
>2&(
8/5(
(;
! "# "$" #!%"&' "! () "%"&(( $""*"+&$"&$,""%)!
-".//
16Robo-11 : Interactive C Robot kit Activity book
2.5.2 How to use with the rechargable battery(1) The new rechargable battery need to charge befroe using. The AX-11 activity
has buit-in low current charger circuit. User can put the new rechargable battery into the
holder at the back of the AX-11 board and charge with +12V DC adaptor. The charging
time 16 hours for 1800mAH rating.
(2) Select the output voltage to +12V. Plug the DC adaptor to a wall outet.
(3) Connect the DC adaptor to the DC in jack of AX-11 board, making sure the
power switch is off. No need to turn-on POWER. The yellow CHG. LED will light to indicate
the charging operation. This indicator will dim when the battery voltage full.
(4) To faster charging, the 6 cells AA or more external battery charger is required.
>7
78
78"
7.'
7.%
7.$
>2&(
8/5(
(;
!"#$ "% " %&'&( "(& )*"+#'"% "&,&+" " % "-"(&, " !%&''"% "(& )"% ".*") /"/"'%"&,","/% "!#"+/
0"122
Robo-11 : Interactive C Robot kit Activity book17
1.3.3 How to use with the rechargable battery(1) The new rechargable battery need to charge befroe using. The AX-11 activity
has buit-in low current charger circuit. User can put the new rechargable battery into the
holder at the back of the AX-11 board and charge with +12V DC adaptor. The charging
time 16 hours for 1800mAH rating.
(2) Select the output voltage to +12V. Plug the DC adaptor to a wall outet.
(3) Connect the DC adaptor to the DC in jack of AX-11 board, making sure the
power switch is off. No need to turn-on POWER. The yellow CHG. LED will light to indicate
the charging operation. This indicator will dim when the battery voltage full.
(4) To faster charging, the 6 cells AA or more external battery charger is required.
>7
78
78"
7.'
7.%
7.$
>2&(
8/5(
(;
!!"!##
$%"&&'(')#)'""*+,#%("& ' - ' , "! " ! "& . ) ! ' - $! &'( ("&)'""*&/+*##!00 ### (&"'-- 0&$%##,!0
122
18Robo-11 : Interactive C Robot kit Activity book
1.4 Interface to computer1.4.1 Interface with the RS-232 serial port or COM port
If your computer has a free RS-232 serial port or COM port, you can connect the
AX-11 baord with the COM port directly by CX-4 serial port cable (included with AX-11 kit).
The green SER. LED will light to confirm the connection following the figure below.
>7
78
78"
7.'
7.%
7.$
>2&(
8/5(
(;
!!"
! #!
$%
&' ()"*+, ("-./('%#%!0 '( 1 ( 2
Robo-11 : Interactive C Robot kit Activity book19
1.4.2 Interface with USB portMany modern computer and laptop not available the COM port. Thus, the
conenction of AX-11 with these machine must do with USB port. The USB to RS-232 serial
port comverter is required. The UCON-232S is recommended (see more info at
www.inexlobal.com or your INEX’s distributor nearby you) . The connection diagram is
shown the figure below.
>7
78
78"
7.'
7.%
7.$
>2&(
8/5(
(;
!"#
!"#$ #%&#' (#() #$ # *#+(,$ #" # ##- "$#.#$ # /
$% $ !"# "% $
Before using the USB to RS-232 serial port converter do not forget install its driver
and checking the USB Serial port address by clicking to the Control panel System
Hardware Device manager ports.
20Robo-11 : Interactive C Robot kit Activity book
Robo-11 : Interactive C Robot kit Activity book21
This chapter describes about how to building the Interactive C robot kit. The first
robot kit to build is Robo-11 Standard. Features of Robo-11 Standard are as follows :
Driving with DC motor gearboxes and Track wheel
Controlled by 68HC11 cmicrocontroller with AX-11 Activity board
32Kbytes memory
Re-programmable
Support many types of sensor and detector such as
ZX-01 Switch input board for attacking detection,
ZX-03 Infrared Reflector for line tracking and area,
GP2D120 Infrared distance sensor,
SRF05 Ultrasonic sensor,
CMPS03 Digital compass,
and more...
Provides Character LCD moduel 16x2 for displaying the robot operation.
2.1 Buiding the Robo-11 Standard robotThe steps are presented in this chapter as the construction procedure for making
the Robo-11 Standard; the first robot of tje Interactive C robot kit. Builder must prepare ascrewdriver for tightening all screws and 6 of AA batteries (Ni-MH rechargable 1800mAH isrecommended) for Robo-11 power.
Chapter 2Building Robo-11 Standard
22Robo-11 : Interactive C Robot kit Activity book
2. Insert the main sprocket to the gearbox’s shaft. Stick the Codewheel sticker. Fix the
scrocket with 2mm. tap screw. Do both DC gearboxes.
3. Put up side down. Attach the Long angled shaft base with the base at the specific
position as shown in the figure A2-4. Tighten the 3x9mm. screw to a leave hole from step 1.
Next, tight a 3x10mm. screw and 3mm. nut to fix the second hole of the Long angled shaft
base as shown in the figure A2-4.
1. Fix 2 of the 48:1 DC motor gearboxes at the base. Must attach the left DC gearbox at
the edge of the base following Figure A2-1. Tighten the 3x7mm. screws from bottom side
to fix both gearboxes. Leave the inside hole of the right gearbox. Do not tighten the screw.
Robo-11 : Interactive C Robot kit Activity book23
4. Attach the rest of Long angled shaft base with a base by inserted the 3x10mm. screws
from top side through the hole and tighten with 3mm. nuts following the Figure A2-5.
5. Turn the base over. Attach 2 of the Short angled shaft bases at the front of the robot’s
base as shown in the Figure A2-8 by inserted the 3x10mm. screws from bottom side through
the shaft bases’ holes and tighten with 3mm. nuts. Tighten the screw on the inside hole.
Leave the outside holes.
6. Fix a Hexagonal standofff at the rest hole of Short angled shaft base and 5-hole Straight
joiner by 3x10mm. screw. Tighten from bottom side. Do both sides.
24Robo-11 : Interactive C Robot kit Activity book
7. With the board still upside down, Insert the metal axel into the holes of the long angled
shaft in the hole positions of 1, 4 and 7 as shown in the Figure A2-8. Place the Medium
track support wheels over the metal axel. Insert the hubs over the wheels so that the
wheels and the axels are connected tightly.
8. Turn up the base. Insert the 4th metal axel into the holes of the short angled shaft. Place
the Large support wheel over the axel. Insert the hubs over the wheels so that the wheels
and the axels are connected tightly.
Robo-11 : Interactive C Robot kit Activity book25
The example shown above is only a sample to show you the standard type oftrack width used. You can of course assemble your own track length based onyour own requirements for your robot.
9. Create two track belts by putting the different size tracks together. One track would
consist of the following: One 30-joint, One 10-joint and Two 8-joint tracks. Connect all
tracks together. Take one end and connect it to the other end of the track to form one
complete loop. Repeat the steps to make two track sets. If the track is too tight or loose,
you can either adjust the length of the track or adjust the position of the short angled shaft
base until the track has a good fit.
10. Attach the tracks to the supporting wheels of the robot.
26Robo-11 : Interactive C Robot kit Activity book
11. Prepare an AX-11 Actiity board, one base plate, 3 of Thumb screws and Robo-11
chasis from step 10.
12. Fix the second base plate on the top of Hexagonal standoffs with 3 of thumb screws;
two at the front and one at the back. At the back end, tighten a thumb screw into a hole
of DCgearbox and plate base.
!" #!"
13. Remove the protection paper of 2-side tape of the Knobby plate. Stick the Knobby
plate on the battery holder cover.
Robo-11 : Interactive C Robot kit Activity book27
14. Open the batter holder at the back of AX-11 board. Put the 6 of AA batteries. The
rechagable 1800mAH or higher is recommended. Cloase the holder. Attach the AX-11
that fixed the Knobby plate on the Robo-11 chasis. Do not attach the board overlie the
thumb screw at the bakc end of robot chasis.
15. Plug the DC motor gearboxes cable to Motor connectors. The right motor is connected
to the white M-1 output and left motor is connected to the black M-0 output. However
the motor’s pole (white or black connector) can be changed depending on the pro-
gramming and mission. Normally, refer from the motor output’s indicator, if both light green,
it means the forward movement and both light red mean the backward movement. You
can change later if the operation incorrect.
16. Arrange all cables and check all connection carefully. Your Robo-11 Standardis now ready for programing.
28Robo-11 : Interactive C Robot kit Activity book
2.2 Testing program with Interactive CThe preparations that we are about to talk about is writing the main control pro-
gram, or what they call the Firmware, into the memory of the AX-11 board; the controller
of Robo-11 Standard. 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.
(1) 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. Must change the
battery first or 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. Make sure the batteryinside AX-11 is rechargable type. If not, must remove all batteries first.Once power is supplied, the yellow CHG. LED will light, and the red LED will disappear.
(2) Connect the AX-11 baord with the COM port directly by CX-4 serial port cable
(included with robot kit). The green SER. LED will light to confirm the connection following
the figure below.
!"#$ #%&#' (#() #$ # *#+(,$ #" # ##- "$# . # $ # /
Robo-11 : Interactive C Robot kit Activity book29
(3) Open the Interactive C by entering to Start Program Interactive C 7.08ax
Interactive C7.08ax. The title icon will appear for a moment.
The Choose target window will apppear following. Select the AX-11R6. Click
on the OK button.
(4) IC Port Selection window will appear. Click at the COM port address that con-
nect with AX-11 board and click on the OK button to next.
30Robo-11 : Interactive C Robot kit Activity book
(5) If your AX-11 board does not install firmware or lost, the SerialConnectDialog will
appear. Click on the Download Firmware button.
(6) Firmware Download window will appear and shows the steps in downloading
the firmware to the AX-11 board
Robo-11 : Interactive C Robot kit Activity book31
(6.1) Start by connecting the download cable to the serial port and to the
AX-11 board. The green SER. LED is lit.
(6.2) Turn off the POWER switch.
(6.3) Press the STOP switch on the AX-11 board. While still holding it down,
turn on the power of the AX-11 board. Both LED at PWR. and BATT. must off. Now the AX-
11 board ready for firmware downloading.
If the PWR LED is lit, it means the board is unable to enter the down-
load mode of the program, and to check the download cable again before repeating
the steps for download.
If the BATT LED is lit, it means the voltage supply of the battery is low
and needs to be recharged for at least another 30 minutes before using it again if use
rechargable battery or chage the new batteries if use alcaline type.
32Robo-11 : Interactive C Robot kit Activity book
(7) If everything is alright, click on the Download Firmware button.
(8) Download main library following.
(9) After downloading, the AX-11 board will beep a sound and the display will
show following message below.
Robo-11 : Interactive C Robot kit Activity book33
(10) The Interactive C program will then go to the Interaction window, which is
used for testing the program.
The AX-11 activity board is now ready for program coding and operation.
(11) 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. Go to the Interaction window,
type in the function
Printf (“Hello world !\n”);
Then press Enter.
(12) The monitor shows the results from the AX-11, displaying 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.
34Robo-11 : Interactive C Robot kit Activity book
(13) Next we will create a simple Interactive C program to use with the AX-11 board.
(13.1) Click to create a new program folder.
(13.2) Type in the program below, and save it as hello.ic.
void (main) void;
printf(“Hello world !\n”);
beep();
(13.3) Click button to download the program. A window willappear asking to save the file *.ic first. Here, the file is hello.ic. A window displaying thestatus of the download will then appear.
(3.4) Run the program by
Method 1: Turn off and on the POWER switch once to reset the board.
Method 2: Run the program by clicking the button on the menu.
The message will appear on the AX-11 display.
Robo-11 : Interactive C Robot kit Activity book35
2.3 Robo-11 Standard programming activityAfter the Robo-11 Standard 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.
(1) Type in the Listing2-1 code and download it to the Robo-11
/* 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 70 /* Configuration power drive motor */void main() ao(); // Off all motors printf("Press Start!\n"); // Show begining message start_press(); // Wait START button pressed while(1) // Infinite loop run_fd(2.0); // Robot forward 2 second run_bk(2.0); // Robot backward 2 second
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 delayvoid 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
! "# !#$%&!%'(!' ! !
')'$(#$#(*'&!*!
36Robo-11 : Interactive C Robot kit Activity book
!!#$%&!%'(!'! !
')'$(#$#(*'&!*!*'&!$+,!-.$#! $/!
(2) Testing It ! Place the Robo-11 on the floor and then turn on the POWER switch.
The LCD screen displays the message Press START button on the AX-11.
The robot will move forward for 2 seconds, using only 50% of its power. Ob-
serve 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 functional-
ity of the motors. Both will turn to red.
If you don’t get these results, switch the motor cable’s terminal charge on
the AX-11 until you get the correct results. Use this motor connection for future operations.
(3) From Listing 2-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 Listing 2-2 code and download it to the
Robo-11.
/* Example for Robot movement-2 Hardware configuration - Motor left connected to DC Motor chanel M-0 - Motor right connected to DC Motor chanel M-1 */#define pow 70 /*Configuration power drive motor*/
void main() ao(); // Off all motors printf("Press Start!\n"); // Show begining message start_press(); // Wait START button pressed while(1) // Infinite loop run_fd(2.0); // Robot forward 2 second turn_left(1.0); // Robot backward 1 second 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 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
Robo-11 : Interactive C Robot kit Activity book37
(4) Place the Robo-11 Standard on the floor and then turn on the POWER switch.
The LCD screen displays the message .
(5) Press START button on the AX-11. Observe the robot operation.
The robot will move forward for 2 seconds. 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, move-
ment time, and the friction at the wheels of the robot.
2.4 Things to be know when downloading theprogram to the AX-11
If the AX-11 and Interactive C program is used together continuously without turn-
ing 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 communi-
cate, 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 be-
ginning by downloading the program’s library to the AX-11 board.
38Robo-11 : Interactive C Robot kit Activity book
2.5 How to use Robo-11 with USB to RS-232 serialport converter
Normally the Robo-11 controller board; AX-11 will connect with computer’s COM
port by using the CX-4 serial cable. The Figure 2-2 shows the connection diagramn of the
CX-4 cable. However many modern computers or laptops avialable only USB port. Using
with AX-11 they are need the USB to RS-232 Serial port converter.
2.5.1 UCON-232SThis is a compact size RS232 Serial to USB Convertor. Its fully compatible with all our
robotic kits and microcontroller for Laptop or Desktop users whose computers do not have
a RS232 Serial Port.
The mainly function of this converter is making the Virtual COM port compatible
with true RS-232 serial port. The Figure 2-3 shows the UCON-232S photo and features.
The UCON-232S is used FT232RL from FTDI. It is USB-UART converter chip. FTDI support
the driver for computer to know this device. You can see more information and down-
load the latest driver at www.ftdichip.co.uk or www.parallax.com.
0.#!1 !%'!%'($#$*'"23!#$+%$)+!
• FT232RL USB to Serial TTL-level UART converter chip
• UART interface support for 7 or 8 data bits, 1 or 2 stop
bits and all parity.
• Fully assisted hardware or X-On / X-Off software hand-
shaking.
• Data transfer rates 300 baud to 1 Megabaud (RS232).
• Full UART pin configuration includes TxD, RxD, DTR, DSR,
RTS, CTS, DCD and RI
• Get power from USB bus and supply power to exter-
nal not over 100mA.
0.#!4"!$.#!
Robo-11 : Interactive C Robot kit Activity book39
2.5.2 UCON-232S driver installation(1) Download the USBDriverInstallerV2.0.0.exe file from www.parallax.com or copy
from Interactive C CD-ROM.
(2) Double-click at the USBDriverInstallerV2.0.0.exe file to installation UCON-232S
driver.
(3) Plug the UCON-232S to USB port. Wait a moment. The blue LED of UCON-232S
lights ready to use.
(4) Check the COM port address by clicking Start Control Panel System
Hardware Device Manager
40Robo-11 : Interactive C Robot kit Activity book
(5) See the list of USB serial port and remember the COM port address to work with
AX-11 board. Normally UCON-232S will create COM3 or above.
Robo-11 : Interactive C Robot kit Activity book41
2.5.3 How to work with AX-11 activity board and Interactive C(1) Connect the DB-9 end of the CX-4 serial cable to UCON-232S and the other
end connect to AX-11 board. Turn-on power.
(2) Open Interactive C. Choose the hardware to AX-11R6 and click on the OKbutton. The IC Port Selection window will appear.
(3) Select the USB serial port that you know. If the COM port is over COM12, click on
the Custom Port button.
(4) The Serial Port Input dialog will appear. Put the message \\.\comX to choose
the COM port that created from UCON-232S. Thus, X is number of COM port. From ex-
ample below is COM15. Click on the OK button.
42Robo-11 : Interactive C Robot kit Activity book
(5) The IC Port Selection window will appear again and show only one COM port
selection. Click at the circle to choosing and click on the OK button.
(6) Interaction window of Interactive C will appear. Observe the title bar. It shows
the COM port that interface with Interactive C. For this example is COM15.
Robo-11 : Interactive C Robot kit Activity book43
2.6 Basic Problem Solving2.6.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. Change the new battery if using alcaline type or
Use the external power from the DC adapter +12V 500 mA (making sure no any alcaline
battery in the holder before plug the DC power to AX-11 board)
- Check the correct COM port especially using USB to Serial port converter.
- Download the firmware again.
2.6.2 If the AX-11 cannot communicate with the Interactive CSolve 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. Change the new battery if using alcaline type or
Use the external power from the DC adapter +12V 500 mA (making sure no any alcaline
battery in the holder before plug the DC power to AX-11 board)
- Check the correct COM port especially using USB to Serial port converter.
- If everything is ok, download the firmware again.
2.6.3 If the firmware can not be downloadedSolve 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 (making sure no any alcaline battery in the holder before plug the DC power to
AX-11 board)
- Check the correct COM port especially using USB to Serial port converter.
- If it is still not working, send the robot back to the manufacturer or distribu-
tor to check its functionality
44Robo-11 : Interactive C Robot kit Activity book
Robo-11 : Interactive C Robot kit Activity book45
3.1 IntroductionInteractive C (IC for short) is a C language consisting of a compiler (with interactive
command-line compilation and debugging) and a run-time machine language module.
IC implements a subset of C including control structures (for, while, if, else), local and
global variables, arrays, pointers, structures, 16-bit and 32-bit integers, and 32-bit floating
point numbers.
IC works by compiling into pseudo-code for a custom stack machine, rather than
compiling directly into native code for a particular processor. This pseudo-code (or p-
code) is then interpreted by the run-time machine language program. This unusual ap-
proach to compiler design allows IC to offer the following design tradeoffs:
Interpreted execution that allows run-time error checking. For example, IC
does array bounds checking at run-time to protect against some programming errors.
Ease of design. Writing a compiler for a stack machine is significantly easier
than writing one for a typical processor. Since IC’s p-code is machine-independent, port-
ing IC to another processor entails rewriting the p-code interpreter, rather than changing
the compiler.
Small object code. Stack machine code tends to be smaller than a native
code representation.
Multi-tasking. Because the pseudo-code is fully stack-based, a process’s
state is defined solely by its stack and its program counter. It is thus easy to task-switch
simply by loading a new stack pointer and program counter. This task-switching is handled
by the run-time module, not by the compiler.
Since IC’s ultimate performance is limited by the fact that its output p-code is inter-
preted, these advantages are taken at the expense of raw execution speed.
Chapter 3Interactive C
Programming Reference
46Robo-11 : Interactive C Robot kit Activity book
3.2 Using ICWhen IC is running and has a connection to a compatible processor board such
as the Handy Board or RCX, C expressions, function calls, and IC commands may be
typed in the command entry portion of the interaction window.
For example, to evaluate the arithmetic expression 1 + 2, type in the following:
1 + 2;
When this expression is entered from the interaction window, it is compiled by the
console computer and then downloaded to the attached system for evaluation. The
connected board then evaluates the compiled form and returns the result, which is printed
on the display section of console interaction window.
To evaluate a series of expressions, create a C block by beginning with an open
curly brace and ending with a close curly brace . The following example creates a local
variable i and prints 10 (the sum of i + 7) to the board’s LCD screen:
int i=3; printf(“%d”, i+7);
3.3 IC InterfaceBoth new (unsaved) and saved files can be opened for editing in IC. A row of tabs
lists the files that have been opened. Clicking a file’s tab activates it for editing. The first
tab for the interface is always the interaction window.
The File menu has standard entries for New, Open, Close, Save, Save As, Print and
Exit. Under File - Save As, if no file name extension is supplied, IC automatically saves with
the “.ic” extension.
To download the active file, simply click the button. The active file will
also be saved, unless it is new, in which case the user is prompted for a “save as” file
name. Remark: a preprocessor command #use has been added to IC to specify any
other saved files (personal libraries) that need to be downloaded along with the active
file [Note: #use is quite different from the #include prepreocessor command of standard
C environments. #include is not implemented for reasons given later in the section de-
scribing the IC-preprocessor.]
If a downloaded program does not do what is intended, it may corrupt the p-code
interpreter, particularly if pointers are being employed. The interface provides an option
under the Settings button for downloading the firmware to reinitialize the board.
When there is a connection to a board and the downloaded programs include
“main”, then “main” can be executed using the button. The button will
halt execution of the attached system.
Robo-11 : Interactive C Robot kit Activity book47
FileNew (Ctrl+N) Create the new file
Open (Ctrl-O) Open the exist file
Close (Ctrl+W) Close the active file
Save (Ctrl + S) Save the active file
Save As Save the active file to
new name
Print (Ctrl+P) Print out the active code
Exit Exit program
EditUndo Undo the last edit action
Redo Redo the last edit action
Cut Cut text to clipboard
Copy Copy text to clipboard
Paste Paste text from clipboard
Select all Select all text
Find Find words
Find Next Find next words
Goto line Go to the target line
Indent Indent message
Indent All Indent all file
Tools :Check parens Check parentheses
Upload array Upload data from array
List functions Show the list of function
List global variables Show the list of global variable
List loaded files Show the downloaded file
List # Define Show the list of defined
variable
View diagram Show AX-11 board layout
Download firmware Download firmware to AX-11
Download Libraries Download library of IC7.08ax
SettingIncerase Font size
Decrease Font size
Change controller type
Change serial port
Disconnect serial port
HelpManual Interactive C HTML manual
About License of IC
48Robo-11 : Interactive C Robot kit Activity book
Interactive C function1. Printing
printf Display message on the LCD screen of AX-11 board
2. Digitla Input Outputclear_digital_out Clear or send logic “0” to the specific port
set_digital_out Set or send logic “1” to the specific port
test_digital_out Test logic at the specific digital output port
3. Motoralloff or a0 Off all motor driver
bk Backward driving
fd Forward driving
init_expbd_servos Enable servo motor driver
motor Choose motor driver power; value is -100 to 100
off Off the specific motor driver channel
4. Soundbeep Generate 500Hz signal in 0.3 second approximation
beeper_off Turn off sound
beeper_on Turn on sound with the latest frequency
set_beeper_pitch Set the sound frequency
Tone Generate the sound with the specific frequency of
set_beeper_pitch function and set the duration time in second.
5. Timingmseconds Count time in millisecond unit
msleep Set delay time in millisecond unit
reset_system_time Reset time
seconds Count time in second unit
sleep Set delay time in second unit
Robo-11 : Interactive C Robot kit Activity book49
6. Sensoranalog Get value from the specific analog input
digital Get value from the specific digital input
disable_encoder Disable the encoder function
enable_encoder Enable the encoder function
knob Read value from potentiometer at KNOB position of AX-11
read_encoder Read data from the encoder function
reset_encoder Reset the encoder function
start_button Read START button value
start_press Loop for checking the STARTswitch is pressed
stop_button Read STOP button value
stop_press Loop for checking the STOP switch is pressed
7. Mathatan Calculate Arctangent (TAN-1). Result is in Radian unit
cos Calculate Cosine (COS). Result is in Radian unit
exp Calculate the power of natural exponential (en)
exp10 Calculate the power of 10 (10n)
log Calculate the natural logarithm
log10 Calculate the logarithm of 10
random Random number in range 2 to 32,767
sin Calculate Sine (SIN). Result is in Radian unit
sqrt Calculate the square-root of integer
tan Calculate Tangent (TAN). Result is in Radian unit
8. Multi-taskinghog_processor Allocates an additional 256 milliseconds of execution to the
currently running process.
defer Makes a process swap out immediately after the function is
called.
kill_process Destroy processes
start_process Start a process, which then runs in parallel with other active
processes.
50Robo-11 : Interactive C Robot kit Activity book
Under the Tools menu, among other options, are ones for listing downloaded files,
global variables, and functions (including library functions).
The interface provides additional capabilities for program entry/edit, minor adjust-
ment to the display, and for setting up the serial interface to a board.
C programs are automatically formatted and indented. Keywords, library func-
tions, comments, and text strings are high-lighted with color unless this feature is turned
off.
IC does parenthesis-balance-highlighting when the cursor is placed to the right of
any right parenthesis, bracket, or brace.
3.4 The main() FunctionAfter functions have been downloaded to a board, they can be invoked from IC
so long as the board is connected. If one of the functions is named main(), it can be run
directly from the interface as noted earlier, and otherwise will be run automatically when
the board is reset.
Note: to reset the Handy Board without running the main() function (for instance,
when hooking the board back to the computer), hold down the board’s Start button
while activating the board. The board will then reset without running main().
3.5 IC versus Standard CThe IC programming language is based loosely on ANSI C. However, there are
major differences.
Many of these differences arise from the desire to have IC be “safer” than stan-
dard C. For instance, in IC, array bounds are checked at run time; for this reason, arrays
cannot be converted to pointers in IC. Also, in IC, pointer arithmetic is not allowed.
Other differences are due to the desire that the IC runtime be small and efficient.
For instance, the IC printf function does not understand many of the more exotic format-
ting options specified by ANSI C.
Yet other differences are due to the desire that IC be simpler than standard C. This
is the reason for the global scope of all declarations.
In the rest of this document, when we refer to “C”, the statement applies to both IC
and standard C. When we wish to specify one or the other, we will refer to either “IC” or
“standard C”. When no such qualifiers are present, you should assume that we are talking
about IC.
Robo-11 : Interactive C Robot kit Activity book51
3.5.1 A Quick C TutorialMost C programs consist of function definitions and data structures. Here is a simple
C program that defines a single function, called main.
/* Simple example IC Programmer’s Manual */
void main()
printf(“Hello, world!\n”); // Something simple
The expression
/* <text> */
forms a multi-line or bracketed comment. In contrast, text that starts with “//” forms
a single line comment, which continues only to the end of the line. Comments are ig-
nored by IC when the program is compiled.
All functions must have a return type. Since main does not return a value, it uses
void, the null type, as its return type. Other types include integers (int) and floating point
numbers (float). This function declaration information must precede each function defini-
tion.
Immediately following the function declaration is the function’s name (in this case,
main). Next, in parentheses, are any arguments (or inputs) to the function. main has none,
but an empty set of parentheses is still required.
After the function arguments is an open curly-brace . This signifies the start of the
actual function code. Curly-braces signify program blocks, or chunks of code.
Next comes a series of C statements. Statements demand that some action be
taken. Our demonstration program has a single statement, a printf (formatted print). This
will print the message “Hello, world!” to the LCD display. The \n indicates end-of-line. The
printf statement ends with a semicolon (;). All C statements must be ended by a semico-
lon. Beginning C programmers commonly make the error of omitting the semicolon that is
required to end each statement.
The main function is ended by the close curly-brace .
Let’s look at an another example to learn some more features of C. The following
code defines the function square, which returns the mathematical square of a number.
int square(int n)
return(n * n);
52Robo-11 : Interactive C Robot kit Activity book
The function is declared as type int, which means that it will return an integer value.
Next comes the function named square, followed by its argument list in parenthe-
ses. square has one argument, n, which is an integer. Notice how declaring the type of
the argument is done similarly to declaring the type of the function.
When a function has arguments declared, those argument variables are valid within
the “scope” of the function (i.e., they only have meaning within the function’s own code).
Other functions may use the same variable names independently.
The code for square is contained within the set of curly braces. In fact, it consists of
a single statement: the return statement. The return statement exits the function and re-
turns the value of the C expression that follows it (in this case “n * n”).
Except where grouped by parentheses, expressions are evaluated according to a
set of precedence rules associated with the various operations within the expression. In
this case, there is only one operation (multiplication), signified by the “*”, so precedence
is not an issue.
Let’s look at an example of a function that performs a function call to the square
program.
float hypotenuse(int a, int b)
float h;
h = sqrt((float)(square(a) + square(b)));
return(h);
This code demonstrates several more features of C. First, notice that the floating
point variable h is defined at the beginning of the hypotenuse function. In general, when-
ever a new program block (indicated by a set of curly braces) is begun, new local vari-
ables may be defined.
The value of h is set to the result of a call to the sqrt function. It turns out that sqrt is
a built-in IC function that takes a floating point number as its argument.
We want to use the square function we defined earlier, which returns its result as an
integer. But the sqrt function requires a floating point argument. We get around this type
incompatibility by coercing the integer sum (square(a) + square(b)) into a float by pre-
ceding it with the desired type, in parentheses. Thus, the integer sum is made into a float-
ing point number and passed along to sqrt.
The hypotenuse function finishes by returning the value of h.
Robo-11 : Interactive C Robot kit Activity book53
3.6 Data ObjectsVariables and constants are the basic data objects in a C program. Declarations
list the variables to be used, state what type they are, and may set their initial value.
3.6.1 VariablesVariable names are case-sensitive. The underscore character is allowed and is of-
ten used to enhance the readability of long variable names. C keywords like if, while, etc.
may not be used as variable names.
Functions and global variables may not have the same name. In addition, if a
local variable is named the same as a function or a global variable, the local use takes
precedence; ie., use of the function or global variable is prevented within the scope of
the local variable.
3.6.1.1 Declaration
In C, variables can be declared at the top level (outside of any curly braces) or at
the start of each block (a functional unit of code surrounded by curly braces). In general,
a variable declaration is of the form:
<type> <variable-name>; or
<type> <variable-name>=<initialization-data>;
In IC, <type> can be int, long, float, char, or struct <struct-name>, and determines
the primary type of the variable declared. This form changes somewhat when dealing
with pointer and array declarations, which are explained in a later section, but in general
this is the way you declare variables.
3.6.1.2 Local and Global Scopes
If a variable is declared within a function, or as an argument to a function, its bind-
ing is local, meaning that the variable has existence only within that function definition. If
a variable is declared outside of a function, it is a global variable. It is defined for all
functions, including functions which are defined in files other than the one in which the
global variable was declared.
3.6.1.3 Variable Initialization
Local and global variables can be initialized to a value when they are declared. If
no initialization value is given, the variable is initialized to zero.
All global variable declarations must be initialized to constant values. Local variables
may be initialized to the value of arbitrary expressions including any global variables, func-
tion calls, function arguments, or local variables which have already been initialized.
54Robo-11 : Interactive C Robot kit Activity book
Here is a small example of how initialized declarations are used.
inti=50; /* declare i as global integer; initial value 50 */longj=100L; /* declare j as global long; initial value 100 */intfoo()
intx; /* declare x as local integer; initial value 0 */longy=j; /* declare y as local integer; initial value j */
Local variables are initialized whenever the function containing them is executed. Glo-
bal variables are initialized whenever a reset condition occurs. Reset conditions occur when:
1. Code is downloaded;
2. The main() procedure is run;
3. System hardware reset occurs.
3.6.1.4 Persistent Global Variables
A special persistent form of global variable, has been implemented for IC. A persis-
tent global variable may be initialized just like any other global variable, but its value is
only initialized when the code is downloaded and not on any other reset conditions. If no
initialization information is included for a persistent variable, its value will be initialized to
zero on download, but left unchanged on all other reset conditions.
To make a persistent global variable, prefix the type specifier with the keyword
persistent. For example, the statementpersistent int i=500;
creates a global integer called i with the initial value 500.
Persistent variables keep their state when the board is turned off and on, when main is
run, and when system reset occurs. Persistent variables will lose their state when code is down-
loaded as a result of loading or unloading a file. However, it is possible to read the values of your
persistent variables in IC if you are still running the same IC session from which the code was
downloaded. In this manner you could read the final values of calibration persistent variables,
for example, and modify the initial values given to those persistent variables appropriately.
Persistent variables were created with two applications in mind:
Calibration and configuration values that do not need to be re-calculated
on every reset condition.
Robot learning algorithms that might occur over a period when the robot is
turned on and off.
Robo-11 : Interactive C Robot kit Activity book55
3.6.2 Constants
3.6.2.1 Integer Constants
Integers constants may be defined in decimal integer format (e.g., 4053 or -1),
hexadecimal format using the “0x” prefix (e.g., 0x1fff), and a non-standard but useful
binary format using the “0b” prefix (e.g., 0b1001001). Octal constants using the zero prefix
are not supported.
3.6.2.2 Long Integer Constants
Long integer constants are created by appending the suffix “l” or “L” (upper- or
lower- case alphabetic L) to a decimal integer. For example, 0L is the long zero. Either the
upper or lower-case “L” may be used, but upper-case is the convention for readability.
3.6.2.3 Floating Point Constants
Floating point numbers may use exponential notation (e.g., “10e3” or “10E3”) or
may contain a decimal period. For example, the floating point zero can be given as “0.”,
“0.0”, or “0E1”, but not as just “0”. Since the board has no floating point hardware, floating
point operations are much slower than integer operations, and should be used sparingly.
3.6.2.4 Characters and String Constants
Quoted characters return their ASCII value (e.g., ‘x’).
Character string constants are defined with quotation marks, e.g., “This is a char-
acter string.”.
3.6.2.5 NULL
The special constant NULL has the value of zero and can be assigned to and com-
pared to pointer or array variables (which will be described in later sections). In general,
you cannot convert other constants to be of a pointer type, so there are many times
when NULL can be useful.
For example, in order to check if a pointer has been initialized you could compare
its value to NULL and not try to access its contents if it was NULL. Also, if you had a defined
a linked list type consisting of a value and a pointer to the next element, you could look
for the end of the list by comparing the next pointer to NULL.
56Robo-11 : Interactive C Robot kit Activity book
3.6.3 Data TypesIC supports the following data types:
3.6.3.1 16-bit Integers
16-bit integers are signified by the type indicator int. They are signed integers, and
may be valued from -32,768 to +32,767 decimal.
3.6.3.2 32-bit Integers
32-bit integers are signified by the type indicator long. They are signed integers,
and may be valued from -2,147,483,648 to +2,147,483,647 decimal.
3.6.3.3 32-bit Floating Point Numbers
Floating point numbers are signified by the type indicator float. They have approxi-
mately seven decimal digits of precision and are valued from about 10^-38 to 10^38.
3.6.3.4 8-bit Characters
Characters are an 8-bit number signified by the type indicator char. A character’s
value typically represents a printable symbol using the standard ASCII character code,
but this is not necessary; characters can be used to refer to arbitrary 8-bit numbers.
3.6.3.5 Pointers
IC pointers are 16-bit numbers which represent locations in memory. Values in
memory can be manipulated by calculating, passing and dereferencing pointers repre-
senting the location where the information is stored.
3.6.3.6 Arrays
Arrays are used to store homogenous lists of data (meaning that all the elements of
an array have the same type). Every array has a length which is determined at the time
the array is declared. The data stored in the elements of an array can be set and re-
trieved in the same manner as for other variables.
3.6.3.7 Structures
Structures are used to store non-homogenous but related sets of data. Elements of a
structure are referenced by name instead of number and may be of any supported type.
Structures are useful for organizing related data into a coherent format, reducing
the number of arguments passed to functions, increasing the effective number of values
which can be returned by functions, and creating complex data representations such as
directed graphs and linked lists.
Robo-11 : Interactive C Robot kit Activity book57
3.6.4 PointersThe address where a value is stored in memory is known as the pointer to that
value. It is often useful to deal with pointers to objects, but great care must be taken to
insure that the pointers used at any point in your code really do point to valid objects in
memory.
Attempts to refer to invalid memory locations could corrupt your memory. Most
computing environments that you are probably used to return helpful messages like ‘Seg-
mentation Violation’ or ‘Bus Error’ on attempts to access illegal memory. However, you
won’t have this safety net on the board you are connecting to. Invalid pointer
dereferencing is very likely to go undetected, and will likely render invalid your data, your
program, or even the pcode interpreter.
3.6.4.1 Pointer Safety
In past versions of IC, you could not return pointers from functions or have arrays of
pointers. In order to facilitate the use of structures, these features have been added to
the current version. With this change, the number of opportunities to misuse pointers have
increased. However, if you follow a few simple precautions you should do fine.
First, you should always check that the value of a pointer is not equal to NULL (a
special zero pointer) before you try to access it. Variables which are declared to be point-
ers are initialized to NULL, so many uninitialized values could be caught this way.
Second, you should never use a pointer to a local variable in a manner which
could cause it to be accessed after the function in which it was declared terminates.
When a function terminates the space where its values were being stored is recycled.
Therefore not only may dereferencing such pointers return incorrect values, but assigning
to those addresses could lead to serious data corruption. A good way to prevent this is to
never return the address of a local variable from the function which declares it and never
store those pointers in an object which will live longer than the function itself (a global
pointer, array, or struct). Global variables and variables local to main will not move once
declared and their pointers can be considered to be secure.
The type checking done by IC will help prevent many mishaps, but it will not catch
all errors, so be careful.
3.6.4.2 Pointer Declaration and Use
A variable which is a pointer to an object of a given type is declared in the same
manner as a regular object of that type, but with an extra * in front of the variable name.
The value stored at the location the pointer refers to is accessed by using the *
operator before the expression which calculates the pointer. This process is known as
dereferencing.
58Robo-11 : Interactive C Robot kit Activity book
The address of a variable is calculated by using the & operator before that vari-
able, array element, or structure element reference.
There are two main differences between how you would use a variable of a given
type and a variable declared as a pointer to that type.
For the following explanation, consider X and Xptr as defined as follows:
long X; long *Xptr;
Space Allocation — Declaring an object of a given type, as X is of type
long, allocates the space needed to store that value. Because an IC long takes four bytes
of memory, four bytes are reserved for the value of X to occupy. However, a pointer like
Xptr does not have the same amount of space allocated for it that is needed for an
object of the type it points to. Therefore it can only safely refer to space which has already
been allocated for globals (in a special section of memory reserved for globals) or locals
(temporary storage on the stack).
Initial Value — It is always safe to refer to a non-pointer type, even if it hasn’t
been initialized. However pointers have to be specifically assigned to the address of le-
gally allocated space or to the value of an already initialized pointer before they are safe
to use.
So, for example, consider what would happen if the first two statements after X
and Xptr were declared were the following:
X=50L; *Xptr=50L;
The first statement is valid : it sets the value of X to 50L. The second statement would
be valid if Xptr had been properly initialized, but in this case it has not. Therefore, this
statement would corrupt memory.
Here is a sequence of commands you could try which illustrate how pointers and
the * and & operators are used. It also shows that once a pointer has been set to point at
a place in memory, references to it actually share the same memory as the object it
points to:
X=50L; /* set the memory allocated for X to 50 */Xptr=&X; /* set Xptr to point to memory address of X */printf(“%d “,*Xptr); /* dereference Xptr; value at address is 50 */X=100L; /* set X to the value 100 */printf(“%d “,*Xptr); /* dereference again; value is now 100 */*Xptr=200L; /* set value at address given by Xptr to 200 */printf(“%d\n”,X); /* check that the value of X changed to 200 */
Robo-11 : Interactive C Robot kit Activity book59
3.6.4.3 Passing Pointers as ArgumentsPointers can be passed to functions and functions can change the values of the
variables that are pointed at. This is termed call-by-reference; a reference, or pointer, to a
variable is given to the function that is being called. This is in contrast to call-by-value, the
standard way that functions are called, in which the value of a variable is given the to
function being called.
The following example defines an average_sensor function which takes a port num-
ber and a pointer to an integer variable. The function will average the sensor and store
the result in the variable pointed at by result.
Prefixing an argument name with * declares that the argument is a pointer.
void average_sensor(int port, int *result)
int sum = 0;int i;for (I = 0; I < 10; i++) sum += analog(port);*result = sum/10;
Notice that the function itself is declared as a void. It does not need to return
anything, because it instead stores its answer in the memory location given by the pointer
variable that is passed to it.
The pointer variable is used in the last line of the function. In this statement, the
answer sum/10 is stored at the location pointed at by result. Notice that the * is used to
assign a value to the location pointed by result.
3.6.4.4 Returning Pointers from FunctionsPointers can also be returned from functions. Functions are defined to return point-
ers by preceeding the name of the function with a star, just like any other type of pointer
declaration.
int right,left;int *dirptr(int dir)
if (dir==0)
return(&right);if (dir==1)
return(&left);return(NULL);
The function dirptr returns a pointer to the global right when its argument dir is 0, a
pointer to left when its argument is 1, and NULL if its argument is other than 0 or 1.
60Robo-11 : Interactive C Robot kit Activity book
3.6.5 ArraysIC supports arrays of characters, integers, long integers, floating-point numbers, struc-
tures, pointers, and array pointers (multi-dimensional arrays). While unlike regular C arrays in a
number of respects, they can be used in a similar manner. The main reasons that arrays are
useful are that they allow you to allocate space for many instances of a given type, send an
arbitrary number of values to functions, and provide the means for iterating over a set of values.
Arrays in IC are different and incompatible with arrays in other versions of C. This
incompatibility is caused by the fact that references to IC arrays are checked to insure that
the reference is truly within the bounds of that array. In order to accomplish this checking in
the general case, it is necessary that the size of the array be stored with the contents of the
array. It is important to remember that an array of a given type and a pointer to the same
type are incompatible types in IC, whereas they are largely interchangeable in regular C.
3.6.5.1 Declaring and Initializing ArraysArrays are declared using square brackets. The following statement declares an
array of ten integers:
int foo[10];
In this array, elements are numbered from 0 to 9. Elements are accessed by enclos-
ing the index number within square brackets : foo[4] denotes the fifth element of the array
foo (since counting begins at zero).
Arrays are initialized by default to contain all zero values. Arrays may also be initial-
ized at declaration by specifying the array elements, separated by commas, within curly
braces. If no size value is specified within the square brackets when the array is declared
but initialization information is given, the size of the array is determined by the number of
elements given in the declaration. For example,
int foo[]= 0, 4, 5, -8, 17, 301;
creates an array of six integers, with foo[0] equaling 0, foo[1] equaling 4, etc.
If a size is specified and initialization data is given, the length of the initialization
data may not exceed the specified length of the array or an error results. If, on the other
hand, you specify the size and provide fewer initialization elements than the total length
of the array, the remaining elements are initialized to zero.
Character arrays are typically text strings. There is a special syntax for initializing
arrays of characters. The character values of the array are enclosed in quotation marks:
char string[]= “Hello there”;
This form creates a character array called string with the ASCII values of the speci-
fied characters. In addition, the character array is terminated by a zero. Because of this
zero-termination, the character array can be treated as a string for purposes of printing
(for example). Character arrays can be initialized using the curly braces syntax, but they
will not be automatically null-terminated in that case. In general, printing of character
arrays that are not null-terminated will cause problems.
Robo-11 : Interactive C Robot kit Activity book61
3.6.5.2 Passing Arrays as Arguments
When an array is passed to a function as an argument, the array’s pointer is actu-
ally passed, rather than the elements of the array. If the function modifies the array val-
ues, the array will be modified, since there is only one copy of the array in memory.
In normal C, there are two ways of declaring an array argument: as an array or as
a pointer to the type of the array’s elements. In IC array pointers are incompatible with
pointers to the elements of an array so such arguments can only be declared as arrays.
As an example, the following function takes an index and an array, and returns the
array element specified by the index:
int retrieve_element(int index, int array[])
return array[index];
Notice the use of the square brackets to declare the argument array as a pointer
to an array of integers.
When passing an array variable to a function, you are actually passing the value of
the array pointer itself and not one of its elements, so no square brackets are used.
void foo()
int array[10];retrieve_element(3, array);
3.6.5.3 Multi-dimensional ArraysA two-dimensional array is just like a single dimensional array whose elements are
one- dimensional arrays. Declaration of a two-dimensional array is as follows:
int k[2][3];
The number in the first set of brackets is the number of 1-D arrays of int. The number
in the second set of brackets is the length of each of the 1-D arrays of int. In this example,
k is an array containing two 1-D arrays; k[0] is a 1-D array of color=blue>int of length 3;
k[0][1] is an color=blue>int. Arrays of with any number of dimensions can be generalized
from this example by adding more brackets in the declaration.
3.6.5.4 Determining the size of Arrays at RuntimeAn advantage of the way IC deals with arrays is that you can determine the size of
arrays at runtime. This allows you to do size checking on an array if you are uncertain of its
dimensions and possibly prevent your program from crashing.
Since _array_size is not a standard C feature, code written using this primitive will
only be able to be compiled with IC.
62Robo-11 : Interactive C Robot kit Activity book
The _array_size primitive returns the size of the array given to it regardless of the
dimension or type of the array. Here is an example of declarations and interaction with
the _array_size primitive:
int i[4]=10,20,30;int j[3][2]=1,2,2,4,15;int k[2][2][2];_array_size(i); /* returns 4 */_array_size(j); /* returns 3 */_array_size(j[0]); /* returns 2 */_array_size(k); /* returns 2 */_array_size(k[0]); /* returns 2 */
3.6.5.5 Uploading Arrays
When an executing program is paused or has finished, IC can upload the values
stored in any global array via the serial port. This permits collecting and recording data for
purposes such as experimentation or calibration.
The IC upload array capability is accessed using the tools tab. When upload array
is activated, it lists all globally declared arrays. When an array is selected, it is opened in a
(modal) view window. The array can be copied to the clipboard, or saved to a TXT or CSV
(comma separated values) file for import to analysis software.
3.6.6 StructuresStructures are used to store non-homogenous but related sets of data. Elements of
a structure are referenced by name instead of number and may be of any supported
type.
Structures are useful for organizing related data into a coherent format, reducing
the number of arguments passed to functions, increasing the effective number of values
which can be returned by functions, and creating complex data representations such as
directed graphs and linked lists.
Structures are used to store non-homogenous but related sets of data. Elements of
a structure are referenced by name instead of number and may be of any supported
type. Structures are useful for organizing related data into a coherent format, reducing
the number of arguments passed to functions, increasing the effective number of values
which can be returned by functions, and creating complex data representations such as
directed graphs and linked lists.
The following example shows how to define a structure, declare a variable of struc-
ture type, and access its elements.
Robo-11 : Interactive C Robot kit Activity book63
struct foo
int i;int j;
;struct foo f1;void set_f1(int i,int j)
f1.i=i;f1.j=j;
void get_f1(int *i,int *j)
*i=f1.i;*j=f1.j;
The first part is the structure definition. It consists of the keyword struct, followed by
the name of the structure (which can be any valid identifier), followed by a list of named
elements in curly braces. This definition specifies the structure of the type struct foo. Once
there is a definition of this form, you can use the type struct foo just like any other type. The
line struct foo f1; is a global variable declaration which declares the variable f1 to be
of type struct foo.
The dot operator is used to access the elements of a variable of structure type. In
this case, f1.i and f1.j refer to the two elements of f1. You can treat the quantities f1.i and
f1.j just as you would treat any variables of type int (the type of the elements was defined
in the structure declaration at the top to be int).
Pointers to structure types can also be used, just like pointers to any other type.
However, with structures, there is a special short-cut for referring to the elements of the
structure pointed to.
struct foo *fptr;void main()
fptr=&f1;fptr->i=10;fptr->j=20;
In this example, fptr is declared to be a pointer to type struct foo. In main, it is set to
point to the global f1 defined above. Then the elements of the structure pointed to by fptr(in this case these are the same as the elements of f1), are set. The arrow operator is used
instead of the dot operator because fptr is a pointer to a variable of type struct foo. Note
that (*fptr).i would have worked just as well as fptr->i, but it would have been clumsier.
Note that only pointers to structures, not the structures themselves, can be passed
to or returned from functions.
64Robo-11 : Interactive C Robot kit Activity book
3.6.7 Complex Initialization examplesComplex types — arrays and structures — may be initialized upon declaration with a
sequence of constant values contained within curly braces and separated by commas.
Arrays of character may also be initialized with a quoted string of characters.
For initialized declarations of single dimensional arrays, the length can be left blank
and a suitable length based on the initialization data will be assigned to it. Multi-dimen-
sional arrays must have the size of all dimensions specified when the array is declared. If a
length is specified, the initialization data may not overflow that length in any dimension or
an error will result. However, the initialization data may be shorter than the specified size
and the remaining entries will be initialized to 0. Following is an example of legal global
and local variable initializations:
/* declare many globals of various types */int i=50;int *ptr=NULL;float farr[3]= 1.2, 3.6, 7.4 ;int tarr[2][4]= 1, 2, 3, 4 , 2, 4, 6, 8 ;char c[]=”Hi there how are you?”;char carr[5][10]=“Hi”,”there”,”how”,”are”,”you”;struct bar
int i;int *p;long j;
b=5, NULL, 10L;struct bar barr[2] = 1, NULL, 2L , 3 ;/* declare locals of various types */int foo()
int x; /* local variable x with initial value 0 */int y= tarr[0][2]; /* local variable y with initial value 3 */int *iptr=&i; /* local pointer to integer
which points to the global i */int larr[2]=10,20; /* local array larr
with elements 10 and 20 */struct bar lb=5,NULL,10L;
/* local variable of typestruct bar with i=5 and j=10 */
char lc[]=carr[2]; /* local string lc withinitial value “how” */
...
Robo-11 : Interactive C Robot kit Activity book65
3.7 Statements and ExpressionsOperators act upon objects of a certain type or types and specify what is to be done to
them. Expressions combine variables and constants to create new values. Statements are ex-
pressions, assignments, function calls, or control flow statements which make up C programs.
3.7.1 OperatorsEach of the data types has its own set of operators that determine which opera-
tions may be performed on them.
3.7.1.1 Integer OperationsThe following operations are supported on integers:
Arithmetic : addition +, subtraction -, multiplication *, division /.
Comparison : greater-than >, less-than <, equality ==, greater-than-equal
>=, less-than-equal <=.
Bitwise Arithmetic : bitwise-OR |, bitwise-AND &, bitwise-exclusive-OR ^,
bitwise-NOT ~.
Boolean Arithmetic : logical-OR ||, logical-AND &&, logical-NOT !.
When a C statement uses a boolean value (for example, if), it takes the integer
zero as meaning false, and any integer other than zero as meaning true. The boolean
operators return zero for false and one for true. Boolean operators && and || will stop
executing as soon as the truth of the final expression is determined. For example, in the
expression a && b, if a is false, then b does not need to be evaluated because the result
must be false. The && operator therefore will not evaluate b.
3.7.1.2 Long IntegersA subset of the operations implemented for integers are implemented for long
integers: arithmetic addition +, subtraction -, multiplication * and the integer comparison
operations. Bitwise and boolean operations and division are not supported.
3.7.1.3 Floating Point NumbersIC uses a package of public-domain floating point routines distributed by Motorola
(currently is Freescale). This package includes arithmetic, trigonometric, and logarithmic
functions. Since floating point operations are implemented in software, they are much
slower than the integer operations; we recommend against using floating point if you are
concerned about performance.
The following operations are supported on floating point numbers:
Arithmetic : addition +, subtraction -, multiplication *, division /.
Comparison : greater-than >, less-than <, equality ==, greater-than-equal
>=, less-than-equal <=.
Built-in Math Functions : A set of trigonometric, logarithmic, and exponen-
tial functions is supported.
66Robo-11 : Interactive C Robot kit Activity book
3.7.1.4 CharactersCharacters are only allowed in character arrays. When a cell of the array is refer-
enced, it is automatically coerced into a integer representation for manipulation by the
integer operations. When a value is stored into a character array, it is coerced from a
standard 16- bit integer into an 8-bit character (by truncating the upper eight bits).
3.8 Assignment Operators and ExpressionsThe basic assignment operator is =. The following statement adds 2 to the value of a.
a = a + 2;
The abbreviated form
a += 2;
could also be used to perform the same operation. All of the following binary op-
erators can be used in this fashion:
+ - * / % << >> & ^ |
3.9 Increment and Decrement OperatorsThe increment operator ++ increments the named variable. For example, the con-
struction a++ is equivalent to a= a+1 or a+= 1. A statement that uses an increment opera-
tor has a value. For example, the statement
a= 3; printf(“a=%d a+1=%d\n”, a, ++a);
will display the text “a=3 a+1=4”. If the increment operator comes after the named
variable, then the value of the statement is calculated after the increment occurs. So the
statement
a= 3; printf(“a=%d a+1=%d\n”, a, a++);
would display “a=3 a+1=3” but would finish with a set to 4. The decrement opera-
tor “—” is used in the same fashion as the increment operator.
3.10 Data Access Operators&
A single ampersand preceding a variable, an array reference, or a structure ele-
ment reference returns a pointer to the location in memory where that information is be-
ing stored. This should not be used on arbitrary expressions as they do not have a stable
place in memory where they are being stored.
*A single * preceeding an expression which evaluates to a pointer returns the value
which is stored at that address. This process of accessing the value stored within a pointer
is known as dereferencing.
Robo-11 : Interactive C Robot kit Activity book67
[<expr>]An expression in square braces following an expression which evaluates to an ar-
ray (an array variable, the result of a function which returns an array pointer, etc.) checks
that the value of the expression falls within the bounds of the array and references that
element.
.A dot between a structure variable and the name of one of its fields returns the
value stored in that field.
->An arrow between a pointer to a structure and the name of one of its fields in that
structure acts the same as a dot does, except it acts on the structure pointed at by its left
hand side. Where f is a structure of a type with i as an element name, the two expressions
f.i and (&f)->i are equivalent.
3.11 Precedence and Order of EvaluationThe following table summarizes the rules for precedence and associativity for the C
operators. Operators listed earlier in the table have higher precedence; operators on the
same line of the table have equal precedence.
Operator Associativity
() [] left to right
! ~ ++ — - (<type>) right to left
* / % left to right
+ - left to right
<< >> left to right
< <= > >= left to right
== != left to right
& left to right
^ left to right
| left to right
&& left to right
|| right to left
= += -= right to left
, left to right
68Robo-11 : Interactive C Robot kit Activity book
3.12 Control FlowIC supports most of the standard C control structures. One notable exception is the
switch statement, which is not supported.
3.12.1 Statements and BlocksA single C statement is ended by a semicolon. A series of statements may be
grouped together into a block using curly braces. Inside a block, local variables may be
defined. Blocks may be used in place of statements in the control flow constructs.
3.12.2 If-ElseThe if else statement is used to make decisions. The syntax is:
if (<expression>) <statement-1>
else<statement-2>
<expression> is evaluated; if it is not equal to zero (e.g., logic true), then <state-ment-1> is executed.
The else clause is optional. If the if part of the statement did not execute, and the
else is present, then <statement-2> executes.
3.12.3 WhileThe syntax of a while loop is the following:
while (<expression>)
<statement>
while begins by evaluating <expression>. If it is false, then <statement> is skipped. If
it is true, then <statement> is evaluated. Then the expression is evaluated again, and the
same check is performed. The loop exits when <expression> becomes zero.
One can easily create an infinite loop in C using the while statement:
while (1)
<statement>
3.12.4 Do-WhileThe syntax of a do-while loop is the following:
do<statement>
while (<expression>);
The equivalent while loop would be the following:
<statement>while (<expression>)<statement>
Robo-11 : Interactive C Robot kit Activity book69
3.12.5 ForThe syntax of a for loop is the following:
for (<expr-1>;<expr-2>;<expr-3>)
<statement>
The for construct is equivalent to the following construct using while:
<expr-1>;
while (<expr-2>)
<statement>
<expr-3>;
Typically, <expr-1> is an assignment, <expr-2> is a relational expression and <expr-3> is an increment or decrement of some manner. For example, the following code counts
from 0 to 99, printing each number along the way:
int i;
for (i = 0; i < 100; i++)
printf(“%d\n”, i);
3.12.6 SwitchThe syntax of a switch block is as follows:
switch (int)
case const1:
<statement list1>
break;
case const2:
<statement list2>
break;
default:
<statement list3>
The switch construct takes an integer variable as input, and compares it to each
case listed. The first matching const is selected, and execution begins there. The break is
optional, and if no break is found then execution continues through each following state-
ment. Also note that each case has a list of single statements, as opposed to a block
enclosed in curly braces.
70Robo-11 : Interactive C Robot kit Activity book
Here’s an example of how a switch might be used:
int i = 1;
switch(i)
case 0:
printf(“Case 0\n”);
break;
case 1:
printf(“Case 1\n”);
break;
default:
printf(“Default\n”);
Since i is equal to 1, the text “Case 1” will be printed to the screen. If i were equal to
0, “Case 0” would be printed. If i were any number besides 0 or 1, “Default” would be
printed.
3.12.5 BreakUse of the break statement provides an early exit from a while or a for loop.
3.13 LCD Screen PrintingIC has a version of the C function printf for formatted printing to the LCD screen.
The syntax of printf is the following:
printf(<format-string>, <arg-1> , ... , <arg-N>);
This is best illustrated by some examples.
3.13.1 Printing Examples
Example 1: Printing a message
The following statement prints a text string to the screen.
printf(“Hello, world!\n”);
In this example, the format string is simply printed to the screen. The character \nat the end of the string signifies end-of-line. When an end-of-line character is printed, the
LCD screen will be cleared when a subsequent character is printed. Thus, most printf state-
ments are terminated by a \n.
Robo-11 : Interactive C Robot kit Activity book71
Example 2: Printing a numberThe following statement prints the value of the integer variable x with a brief message.
printf(“Value is %d\n”, x);
The special form %d is used to format the printing of an integer in decimal format.
Example 3: Printing a number in binaryThe following statement prints the value of the integer variable x as a binary number.
printf(“Value is %b\n”, x);
The special form %b is used to format the printing of an integer in binary format.
Only the low byte of the number is printed.
Example 4: Printing a floating point number
The following statement prints the value of the floating point variable n as a float-
ing point number.
printf(“Value is %f\n”, n);
The special form %f is used to format the printing of floating point number.
Example 5: Printing two numbers in hexadecimal formatprintf(“A=%x B=%x\n”, a, b);
The form %x formats an integer to print in hexadecimal.
3.13.2 Formatting Command SummaryFormat Command Data Type Description
%d int decimal number
%x int hexadecimal number
%b int low byte as binary number
%c int low byte as ASCII character
%f float floating point number
%s char array char array (string)
3.13.3 Special Notes The final character position of the LCD screen is used as a system “heartbeat.”
This character continuously blinks between a large and small heart when the board is
operating properly. If the character stops blinking, the board has failed.
Characters that would be printed beyond the final character position are truncated.
When using a two-line display, the printf() command treats the display as a single
longer line.
Printing of long integers is not presently supported.
72Robo-11 : Interactive C Robot kit Activity book
3.14 PreprocessorThe preprocessor processes a file before it is sent to the compiler. The IC preproces-
sor allows definition of macros, and conditional compilation of sections of code. Using
preprocessor macros for constants and function macros can make IC code more effi-
cient as well as easier to read. Using #if to conditionally compile code can be very useful,
for instance, for debugging purposes.
The special preprocessor command #use has been included to allow programs to
cause a program to download to initiate the download of stored programs that are not in
the IC library. For example, suppose you have a set of stored programs in a file named
“mylib.ic”, some of which you need for your current program to work.
/* load my library */
#use “mylib.ic”
void main()
char s[32] = “text string wrapping badly\n”;
fix (s); /* apply my fix function to s and print it */
printf(s);
3.14.1 Preprocessor MacrosPreprocessor macros are defined by using the #define preprocessor directive at
the start of a line. A macro is local to the file in which it is defined. The following example
shows how to define preprocessor macros.
#define RIGHT_MOTOR 0
#define LEFT_MOTOR 1
#define GO_RIGHT(power) (motor(RIGHT_MOTOR,(power)))
#define GO_LEFT(power) (motor(LEFT_MOTOR,(power)))
#define GO(left,right) GO_LEFT(left); GO_RIGHT(right);
void main()
GO(0,0);
Preprocessor macro definitions start with the #define directive at the start of a line,
and continue to the end of the line. After #define is the name of the macro, such as
RIGHT_MOTOR. If there is a parenthesis directly after the name of the macro, such as the
GO_RIGHT macro has above, then the macro has arguments. The GO_RIGHT and GO_LEFTmacros each take one argument. The GO macro takes two arguments. After the name
and the optional argument list is the body of the macro.
Robo-11 : Interactive C Robot kit Activity book73
Each time a macro is invoked, it is replaced with its body. If the macro has argu-
ments, then each place the argument appears in the body is replaced with the actual
argument provided.
Invocations of macros without arguments look like global variable references. In-
vocations of macros with arguments look like calls to functions. To an extent, this is how
they act. However, macro replacement happens before compilation, whereas global
references and function calls happen at run time. Also, function calls evaluate their argu-
ments before they are called, whereas macros simply perform text replacement. For ex-
ample, if the actual argument given to a macro contains a function call, and the macro
instantiates its argument more than once in its body, then the function would be called
multiple times, whereas it would only be called once if it were being passed as a function
argument instead.
Appropriate use of macros can make IC programs and easier to read. It allows
constants to be given symbolic names without requiring storage and access time as a
global would. It also allows macros with arguments to be used in cases when a function
call is desirable for abstraction, without the performance penalty of calling a function.
3.14.2 Conditional compilationIt is sometimes desirable to conditionally compile code. The primary example of
this is that you may want to perform debugging output sometimes, and disable it at other
times. The IC preprocessor provides a convenient way of doing this by using the #ifdef
directive.void go_left(int power)
GO_LEFT(power);#ifdef DEBUGprintf(“Going Left\n”);beep();#endif
In this example, when the macro DEBUG is defined, the debugging message “Go-
ing Left” will be printed and the board will beep each time go_left is called. If the macro
is not defined, the message and beep will not happen. Each #ifdef must be follwed by an
#endif at the end of the code which is being conditionally compiled. The macro to be
checked can be anything, and #ifdef blocks may be nested.
Unlike regular C preprocessors, macros cannot be conditionally defined. If a macro
definition occurs inside an #ifdef block, it will be defined regardless of whether the #ifdefevaluates to true or false. The compiler will generate a warning if macro definitions occur
within an #ifdef block.
The #if, #else and #elif directives are also available, but are outside the scope of
this document. Refer to a C reference manual for how to use them.
74Robo-11 : Interactive C Robot kit Activity book
3.14.3 Comparison with regular C preprocessorsThe way in which IC deals with loading multiple files is fundamentally different from
the way in which it is done in standard C. In particular, when using standard C, files are
compiled completely independently of each other, then linked together. In IC, on the
other hand, all files are compiled together. This is why standard C needs function proto-
types and extern global definitions in order for multiple files to share functions and globals,
while IC does not.
In a standard C preprocessor, preprocessor macros defined in one C file cannot
be used in another C file unless defined again. Also, the scope of macros is only from the
point of definition to the end of the file. The solution then is to have the prototypes, extern
declarations, and macros in header files which are then included at the top of each C file
using the #include directive. This style interacts well with the fact that each file is compiled
independent of all the others.
However, since declarations in IC do not file scope, it would be inconsistent to
have a preprocessor with file scope. Therefore, for consistency it was desirable to give IC
macros the same behavior as globals and functions. Therefore, preprocessor macros have
global scope. If a macro is defined anywhere in the files loaded into IC, it is defined every-
where. Therefore, the #include and #undef directives did not seem to have any appropri-
ate purpose, and were accordingly left out.
The fact that #define directives contained within #if blocks are defined regardless
of whether the #if evaluates to be true or false is a side effect of making the preprocessor
macros have global scope.
Other than these modifications, the IC preprocessor should be compatible with
regular C preprocessors.
Robo-11 : Interactive C Robot kit Activity book75
Chapter 4Interactive C Library
Library files provide standard C functions for interfacing with hardware on the ro-
bot controller board. These functions are written either in C or as assembly language
drivers. Library files provide functions to do things like control motors, make tones, and
input sensors values.
IC automatically loads the library file every time it is invoked. Depending on which
board is being used, a different library file will be required. IC may be configured to load
different library files as its default; IC will automatically load the correct library for the
board you’re using at the moment.
To understand better how the library functions work, study of the library file source
code is recommended; e.g., the main library file for the AX-11 is named lib_hb.ic same
the Handyboard.
For convenience, commonly a description of commonly used library functions follows.
4.1 Commonly Used IC Library Functionsstart_button();
Returns 1 if STRAT button is pressed, otherwise 0.
stop_button();Returns 1 if STOP button is pressed, otherwise 0.
digital();Returns 0 if the switch attached to the port is open and returns 1 if the switch is
closed. Digital ports are numbered 7 to 15. Typically used for bumpers or limit switches.
analog();Returns the analog value of the port (a value in the range 0 to 255). Analog ports
on the AX-11 board are numbered 2 to 6 and 16 to 31. Light sensors and range sensors are
examples of sensors you would use in analog ports.
knob();Returns an int between 0 and 255 depending on knob position.
76Robo-11 : Interactive C Robot kit Activity book
sleep(<float_secs>);Waits specified number of seconds.
beep();Causes a beep sound.
tone(<float_frequency>, <float_secs>)Plays at specified frequency for specified time (seconds).
printf(<string>, <arg1>, <arg2>, ... );Prints <string>. If the string contains % codes then the <args> after the string will be
printed in place of the % codes in the format specified by the code.
%d prints a decimal number.
%f prints a floating point number.
%c prints a character
%b prints an integer in binary
%x prints an integer in hexadecimal.
motor(<motor_#>, <speed>)Controls the motors.
<motor_#> is an integer between 0 and 3
<speed> is an integer between -100 and 100 where 0 means the motor is off
and negative numbers run the motor in the reverse direction.
fd(<motor_#>);Turns on the motor specified (direction is determined by plug orientation.
bk(<motor_#>);Turns on the motor specified in the opposite direction from fd.
off(<motor_#>);Turns off the motor specified.
ao();Turns all motor ports off.
Robo-11 : Interactive C Robot kit Activity book77
4.2 ProcessesProcesses work in parallel. Each process, once it is started, will continue until it fin-
ishes or until it is killed by another process using the kill_process(<process_id)>); statement.
Each process that is active gets 50ms of processing time. Then the process is paused
temporarily and the next process gets its share of time. This continues until all the active
process have gotten a slice of time, then it all repeats again. From the user’s standpoint it
appears that all the active processes are running in parallel.
Processes can communicate with one another by reading and modifying global
variables. The globals can be used as semaphores so that one process can signal an-
other. Process IDs may also be stored in globals so that one process can kill another when
needed.
Up to 4 processes initiated by the start_process() library function can be active at
any time.
The library functions for controlling processes are:
start_process(<function_name>(<arg1>, <arg2>, . . .));Start_process returns an integer that is the <process_id> and starts the function
<function_name> as a separate process.
defer();When placed in a function that is used as a process this will cause that process to
give up the remainder of its time slice whenever defer is called.
kill_process(<process_id>);This will terminate the process specified by the <process_id>.
78Robo-11 : Interactive C Robot kit Activity book
4.3 EncodersThe enable_encoder() library function is used to start a process which updates the
transition count for the encoder specified. The encoder library functions are designed for
sensors connected to (digital) ports 7,8,12 and 13. The corresponding <encoder#> values
are 0,1,2 and 3. Every enabled encoder uses a lot of the AX-11’s processor — so don’t
enable an encoder unless you are going to use it, and never put an enable statement
inside of a loop.
enable_encoder(<encoder#>);Turns on the specified encoder (either 0,1,2, or 3 which are plugged into digital
ports 7, 8, 12, 13 respectively). This should be done only once - never enable an already
enabled encoder. If an encoder is not enabled, read_encoder will always return 0.
disable_encoder(<encoder#>)Turns off the specified encoder.
reset_encoder(<encoder#>)Sets the specified encoder value to 0.
read_encoder(<encoder#>)Returns an int that is the current value of the specified encoder.
Robo-11 : Interactive C Robot kit Activity book79
4.4 Basic experiment4.4.1 Controlling the DC Motors
To Control the DC Motors, Please ensure that the moors are connected to the MIII
Main board before programming.
4.4.1.1 Procedure(1) Connect the DC Motors to M-0 and M-1 channel on the AX-11 Board.
(2) Make sure the Interactive C Program is opened. Select a NEW Program or con-
tinue with your existing Program.
(3) The Following Sample Code, “DC-CODE” in Listing 3-1, shows how you can control
the DC Motors.
(4) After you have typed / inserted the code, click on the RUN MAIN button.
(5) Observe the Motor Indicator on the LCD Screen.
80Robo-11 : Interactive C Robot kit Activity book
/* Example for drive motor *//*Hardware configuration - Motor left connected to DC Motor channel M-0 - Motor right connected to DC Motor channel M-1*/void main()
while(1) // Infinite loop
motor(0,50); // Motor0 forward at 50% of maximum powermotor(1,50); // Motor1 forward at 50% of maximum powersleep(2.0); // Delay 2 sec
motor(0,-80); // Motor0 backward at 80% of maximum powermotor(1,-80); // Motor1 backward at 80% of maximum powersleep(2.0); // Delay 2 sec
4.4.1.2 Results
Observe and you will see the following:
- GREEN LED Lights Up.
- Motor Turns in 1 direction for 2 Seconds
- RED LED Lights Up
- Motor Turns in faster by 30% in another direction for 2 Seconds
This Operation continues in an endless loop.
Robo-11 : Interactive C Robot kit Activity book81
4.4.2 Controlling RC-Servo MotorsThe Set of servo motors provided in the package can also be programmed to be
run with the main board. The main board’s capability can allow up to 6 servo motors.
In Interactive C, we can use 2 commands. They are
init_expbd_servos();
Represents ON or OFF servo driver circuit : 1 for ON, 0 for OFF
servo = ;
Represents the board servo number, from 0 to 5.
4.4.2.1 Procedure
(1) Connect the RC Servo motor to Channel 0 on the main board. BE CAREFUL OFTHE COLOR CODE.
- WHITE GOES TO S
- RED to +
- BLACK to -
(2) Make sure the Interactive C Program is opened. Select a NEW Program.
(3) The Following Sample Code, “SERVO-CODE” in Listing 3-2, shows how you can
control the Servo Motors.
(4) After you have typed / inserted the code, click on the “RUN MAIN” button.
(5) Observe the Servo Motor’s Operations.
82Robo-11 : Interactive C Robot kit Activity book
/* Servo motor test*//*Hardware configuration - servo motor connected to ch-0*/void main()
int i=600; // Declare and define servo drive valueinit_expbd_servos(1); // Enable servo motor driverwhile(!stop_button()) // Check STOP switch pressed
servo4 = i; // Drive servo motor ch-4 with servo drive valuesleep(1.0); // Delay 1 seci+=100; // Increase value step = 100if(i>4200) // Check angle>180 deg
i=600; // Set to origin
init_expbd_servos(1); // Disable servo motor driver
Robo-11 : Interactive C Robot kit Activity book83
4.4.3 Controlling the SWITCH SensorThe Main Board allows expandability of up to 9 Digital Inputs.
(1) Connect the Switch sensor to DI-15 ( Digital Input 15) on the Main Board.
(2) Make sure the Interactive C Program is opened. Select a NEW Program.
(3) The Following Sample Code, “SWITCH-CODE”
(4) After you have typed / inserted the code, click on the “RUN MAIN” button.
(5) Observe the LCD Screen on the Main Board.
!
/* Hardware configuration - Touch sensor connected to DI-11 */void main()
int result; // Declare keep input from touch sensorwhile(1) // Infinite loop
result = digital(11); // Keep value from DI-11 channelif(result==1) // Check Touch sensor pressed
printf(“Your press!\n”); // Display message for pressedbeep(); // Sound beepsleep(1.0); // Delay 1 second for display message
else
printf(“—————\n”); // Display when Touch sensor not pressedsleep(0.1); // Delay 0.1 second for display message
!
!!!!!
!
84Robo-11 : Interactive C Robot kit Activity book
/*Light Sensor test *//* Hardware configuration - Light Sensor connected to AI-2 */void main()
int value; // Declare keep input from touch sensor
value = analog(2); // Keep value from AI-2 channelprintf(“Light = %d\n”,value); // Display Reflect valuesleep(0.1); // Delay 0.1 second for display
!
4.4.4 Light DetectionThe Main Board allows 21 Analog INPUTS for analog sensors which converts physi-
cal signals to DC Volts. Light sensors convert physical Light density into DC Voltage. If it is
dark, it’s lower in voltage. If it is Bright, it’s higher in voltage which may exceed 5V.
4.4.4.1 Procedure(1) Connect the Light Sensor to AI-2 (Analog Input 2)
(2) Make sure the Interactive C Program is opened. Select a NEW Program.
(3) The Following Sample Code, “LIGHT-CODE”
(4) After you have typed / inserted the code, click on the “RUN MAIN” button.
(5) Try these in LIGHT and DARK surroundings.
(6) Observe the LCD Screen on the Main Board.
"
Robo-11 : Interactive C Robot kit Activity book85
4.4.5 GP2D120 ReadingsThe GP2D120 Module sensors are also Analog and therefore use the same ports as
the light sensors. The GP2D120 is not included in AX-11 activity board.
/* GP2D120 test*//*Hardware configuration*/#define base -19float dis_table[118]= /*distance value*//*ADC value*/32.0,/*19*/ 30.1,/*20*/ 29.5,/*21*/ 28.6,/*22*/ 27.5,/*23*/26.1,/*24*/ 25.3,/*25*/ 24.5,/*26*/ 23.7,/*27*/ 23.2,/*28*/22.3,/*29*/ 22.0,/*30*/ 21.1,/*31*/ 20.5,/*32*/ 20.0,/*33*/19.3,/*34*/ 19.1,/*35*/ 18.4,/*36*/ 17.9,/*37*/ 17.5,/*38*/17.1,/*39*/ 16.5,/*40*/ 16.2,/*41*/ 15.8,/*42*/ 15.6,/*43*/15.5,/*44*/ 15.3,/*45*/ 14.8,/*46*/ 14.2,/*47*/ 13.8,/*48*/13.6,/*49*/ 13.3,/*50*/ 13.1,/*51*/ 12.8,/*52*/ 12.6,/*53*/12.4,/*54*/ 12.2,/*55*/ 12.0,/*56*/ 11.8,/*57*/ 11.7,/*58*/11.6,/*59*/ 11.6,/*60*/ 11.5,/*61*/ 11.4,/*62*/ 11.3,/*63*/10.85,/*64*/ 10.6,/*65*/ 10.3,/*66*/ 10.2,/*67*/ 10.0,/*68*/9.8,/*69*/ 9.7,/*70*/ 9.5,/*71*/ 9.3,/*72*/ 9.2,/*73*/9.0,/*74*/ 8.9,/*75*/ 8.8,/*76*/ 8.6,/*77*/ 8.4,/*78*/8.3,/*79*/ 8.2,/*80*/ 8.0,/*81*/ 7.85,/*82*/ 7.7,/*83*/7.6,/*84*/ 7.5,/*85*/ 7.3,/*86*/ 7.2,/*87*/ 7.15,/*88*/7.1,/*89*/ 7.0,/*90*/ 6.9,/*91*/ 6.8,/*92*/ 6.7,/*93*/6.6,/*94*/ 6.5,/*95*/ 6.4,/*96*/ 6.35,/*97*/ 6.3,/*98*/6.2,/*99*/ 6.15,/*100*/ 6.1,/*101*/ 6.0,/*102*/ 5.9,/*103*/5.85,/*104*/ 5.8,/*105*/ 5.7,/*106*/ 5.65,/*107*/ 5.6,/*108*/5.55,/*109*/ 5.45,/*110*/ 5.4,/*111*/ 5.4,/*112*/ 5.3,/*113*/5.2,/*114*/ 5.1,/*115*/ 5.0,/*116*/ 5.0,/*117*/ 4.9,/*118*/4.9,/*119*/ 4.8,/*120*/ 4.8,/*121*/ 4.7,/*122*/ 4.7,/*123*/4.6,/*124*/ 4.6,/*125*/ 4.5,/*126*/ 4.5,/*127*/ 4.4,/*128*/4.4,/*129*/ 4.3,/*130*/ 4.3,/*131*/ 4.2,/*132*/ 4.2,/*133*/4.1,/*134*/ 4.1,/*135*/ 4.0/*136*/;void main()
int an; // Keep analog value from sensorwhile(1) // Infinite loop
an = analog(6); // Read analog value from sensorif(an>=19 && an<=136 ) // Distance interval 10-80 cm
printf(“dis %f cm adc=%d \n”,dis_table[an+base],an);// Show distance value
else
printf(“ Out of Range adc = %d\n”,an); // Show mesage out of Range
sleep(1.0); // Delay before read new cycle
#
86Robo-11 : Interactive C Robot kit Activity book
4.4.5.1 Procedure
(1) Connect the GP2D120 Sensor to AI-6.
(2) Make sure the Interactive C Program is opened. Select a NEW Program or con-
tinue with your existing Program.
(3) The Following Sample Code, “GP2D120-CODE”
(4) After you have typed / inserted the code, click on the “RUN MAIN” button.
(5) Place an object in-front of the sensor.
(6) Observe the LCD Screen on the Main Board.
(7) Move the object nearer and further from the sensor and observe the LCD Screen
again.
!!!!!
!
!$%
!$&!$'
Robo-11 : Interactive C Robot kit Activity book87
This robot was further developed from the Robo-11 Standard by adding switches that
will detect obstacles via collision. The switch can also be used to control how it operates.
The Robo-11 Attacker uses a switch to enable digital communication with the sen-
sor. 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.
5.1 The heart is Switch/Touch sensorThe switch sensor has the circuit diagram according to Figure 5-1. If the switch is not
pressed, DATA will have a logic value of “1” due to the resistor R2 that is connected to +V.
Once the switch is pressed, DATA will be connected to ground, and will result in a logic
value “0”. The flow of current will then light LED1.
Therefore, 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 two results, it is considered to be a digital input compo-
nent. Therefore, in connecting it to the AX-11 board, it must be connected to the digital
input terminals D1 which has 9 channels altogether, DI-10 to DI-15 and IN-7 to IN-9.
Chapter 5Robo-11 Attacker
88Robo-11 : Interactive C Robot kit Activity book
In addition, it can also use the LED display on the switch 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 the logic “0” or “1” being sent. When logic “0” is
sent, the LED will light (This method of use is not recommended for beginners)
5.2 Buiding the Robo-11 Attacker robotThe steps are presented in this chapter as the construction procedure for making
the Robo-11 Attacker. You can develop from Robo-11 Standard. The new components ofin this robot making are 2 of ZX-01 Switch/Touch sensors.
1. Consturct the Touch sensor structure. Attach the Swticch sensor with a right angle joinerby using 3x10mm. screws and 3mm. nut according to the figure below. Do them for 2 sets.
2. Connect an Obtuse joiner to the 5-hole Straight joiner at in front of the Robo-11 Stan-dard. Next, connect the Touch sensor structure from last step to the end of the obtusejoiner. Do them both sides.
Robo-11 : Interactive C Robot kit Activity book89
3. 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.
4. 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 Listing 5-1 and download it to the Robo-11 Attacker.
5. Place the Robo-11 Attacker on the floor and then turn on the POWER switch.
The LCD screen displays the message .
6. Press START button on the AX-11.
The robot will move forward. At the same time, the display screen will show the
message .
When the robot runs into an obstacle with the left touch sensor :
The robot will move backwards for 0.5 seconds and turn right for 0.5 sec-
onds. Then it will continue to move forward.
When the robot runs into an obstacle with the right touch sensor :
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 button is pressed.
90Robo-11 : Interactive C Robot kit Activity book
/* Example for object detection by Touch sensor#define pow 70 /*Configuration power drive motor*/void main()
int obj_left,obj_right; // For keep result detect objectprintf("Press Start!\n"); // Display messagestart_press(); // Wait until START button pressedprintf("Robot Move...\n"); // Show running messagewhile(!stop_button()) // Infinite loop
obj_left = digital(15); // Keep left sensor detectionobj_right = digital(10); // Keep right sensor detection
if(obj_left==0 && obj_right==0) // Both sensor do not detect anything
run_fd(0.1); // Forward 0.1 secondelse if(obj_left==0 && obj_right==1) // Right sensor detect object only
run_bk(0.5); // Backward 0.5 secturn_left(0.5); // Turn left 0.5 sec
else if(obj_left==1 && obj_right==0) // Left sensor detect object only
run_bk(0.5); // Backward 0.5 secondturn_right(0.5); // Turn right 0.5 second
else if(obj_left==1 && obj_right==1)// Both sensor detect object
run_bk(0.5); // Backward 0.5 secondturn_right(1.0); // Turn right 1.0 second
ao(); // Off motor all channelbeep(); // Sound alarmprintf("Stop...\n"); // Show ending message
void turn_left(float spin_time)
motor(0,-pow); // Motor0 backward with pow valuemotor(1,pow); // Motor1 forward with pow valuesleep(spin_time); // Delay set by parameter spin_time
void turn_right(float spin_time)
motor(0,pow); // Motor0 forward with pow valuemotor(1,-pow); // Motor1 backward with pow valuesleep(spin_time); // Delay set by parameter spin_time
void run_fd(float delay)
motor(0,pow); // Motor0 forward with pow valuemotor(1,pow); // Motor1 forward with pow valuesleep(delay); // Delay set by parameter delay
void run_bk(float delay)
motor(0,-pow); // Motor0 backward with pow valuemotor(1,-pow); // Motor1 backward with pow valuesleep(delay); // Delay set by parameter delay
Robo-11 : Interactive C Robot kit Activity book91
The Robo-11 Ranger is another example of analog interfacing 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.
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. This
robot model is different from Robo-11 Attacker. This model will detect the object with
TOUCHLESS by Infrared distance sensor; GP2D120.
6.1 GP2D120 : 4 to 30cm. Infrared distance sensorOne of the special sensors in robotics is the Infrared Distance sensor. Some people
call it the IR Ranger. With the GP2D120 module, it adds the distance measuring and Ob-
stacle detection using infrared light feature to your robot. Your Robot can avoid obstacles
without having to make any physical contact.
Chapter 6Robo-11 Ranger
!
! !
!"!
92Robo-11 : Interactive C Robot kit Activity book
6.1.1 GP2D120 features Uses Infrared light reflection to measure range
Can measure a range from 4 to 30 cm.
4. 5 to 5 V power supply and 33mA electric current
The output voltage range is 0.4 to 2.4V when supplied by +5V
GP2D120 Infrared Ranger module has 3 terminals: Power input (Vcc), Ground (GND)
and Voltage output (Vout). To read the voltage values from the GP2D120, you must wait
till after the acknowledgement period which is around 32 to 52.9 ms.
The output voltage of GP2D120 at a range of 30 cm and +5V power supply is be-
tween 0.25 to 0.55V, with the mean being 0.4V. At the range of 4 cm., the output voltage
will change at 2.25V± 0.3V.
6.1.2 How the IR Ranger Module worksMeasuring range can be done in many ways. The easiest to understand is through
ultra sonic where sound waves are sent to the object and the time it takes to reflect back
is measured. This is because sounds waves do not travel fast, and can be measured by
present day equipment. However, in the case of infrared light, the time it takes to hit an
obstacle and reflect back can not be measured because infrared light travels fast. No
measurement equipment is available yet. Therefore, the following theory must be used.
The infrared light is sent out from a transmitter to the object in front, by passing
through a condense lens so that the light intensity is focused on a certain point. Refrac-
tion occurs once the light hits the surface of the object. Part of the refracted light will be
sent back to the receiver end, in which another lens will combine these lights and. deter-
mine the point of impact. The light will then be passed on to an array of photo-transistors.
The position in which the light falls can be used to calculate the distance (L) from the
transmitter to the obstacle using the following formula:
Robo-11 : Interactive C Robot kit Activity book93
L F
A X=
Therefore, L equals
F AL
X
×=
Thus, the distance value from the phototransistors will be sent to the Signal Evalua-
tion Module before it is changed to voltage, resulting in a change of voltage according
to the measured distance.
94Robo-11 : Interactive C Robot kit Activity book
#$ %& !"!'(!)
*"! ))
#$ %& !""+")
'(!)%,-,!*)!!"
)!!"
6.1.3 Reading GP2D120 with A/D converterThe GP2D120’s output voltage will change acoording to the detection distance.
For example, Vout 0.5V is equal 26cm. distance and Vout 2V is equal 6cm. distance. The
table 5-1 shows the summary of GP2D120’s Vout and Distance relation.
For interfacing with A/D converter module within microcontroller, the result is raw
data from the A/D conversion. The user will need to use the software to convert the raw
data to the exact distance. You can calculate the approximate distance from the formular
below.
−
+=
Thus, R as Distance in Centimetre unit
V as Digital data from A/D conversion
6.2 Buiding the Robo-11 Ranger robotThe steps are presented in this chapter as the construction procedure for making
the Robo-11 Ranger; the intelligent robot that detect the obstacle by touchlessing. Youcan learn about analog sensor interfacing with Interactive C and get the analog to digi-tal conversion data to control the robot movement.
Robo-11 : Interactive C Robot kit Activity book95
1. Attach a GP2D120 module with a Right angle joiner as shown in the figure below by
3x10mm. screw and 3mm. nut.
2. Next, insert a straight joiner to the end of angled joiners.
3. Using the Robo-11 Standard robot, at the front of robot, insert a 3x10mm. screw through
the forth hole position from right of the upper plate and 3mm. nut from top side as shown
in the figure below. Do not tighten.
96Robo-11 : Interactive C Robot kit Activity book
4. Next, Insert the GP2D120 structure from step 2 between a screw and nut. Tighten the
screw to fix all together.
5. 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 ob-
stacles at a distance without having to make any contact with the object.
Robo-11 : Interactive C Robot kit Activity book97
!"
#$#
/* 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 70 /* Set 50% motor power */
void main()
float result;printf("Press Start!\n"); // Show begining messagestart_press(); // Wait START button pressedprintf("Robot Move...\n"); // Show running messagewhile(!stop_button()) // Infinite loop
result = distance(); // Get distance valueif (result <= 20.0 && result != -1.0 )
// Check distance <=20 ? if TRUE escape
run_bk(1.0); // Backword 1 secondturn_left(0.5); // Turn left 0.5 second
else
run_fd(0.1); // Forward 0.1 second
ao(); // Off all motorbeep(); // Sound alarmprintf("Stop...\n"); // Show ending message
void turn_left(float spin_time)
motor(0,-pow); // Motor0 backward with pow valuemotor(1,pow); // Motor1 forward with pow valuesleep(spin_time); // Delay set by parameter spin_time
void turn_right(float spin_time)
motor(0,pow); // Motor0 forward with pow valuemotor(1,-pow); // Motor1 backward with pow valuesleep(spin_time); // Delay set by parameter spin_time
void run_fd(float delay)
motor(0,pow); // Motor0 forward with pow valuemotor(1,pow); // Motor1 forward with pow valuesleep(delay); // Delay set by parameter delay
void run_bk(float delay)
motor(0,-pow); // Motor0 backward with pow valuemotor(1,-pow); // Motor1 backward with pow valuesleep(delay); // Delay set by parameter delay
98Robo-11 : Interactive C Robot kit Activity book
6. In writing the program to test the Robo-11 Ranger robot, we emphasize on the commu-
nication 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 con-
tact. Type in the Listing 6-1 code and download it to the Robo-11 Ranger.
7. Place the Robo-11 Ranger on the floor and then turn on the POWER switch.
The LCD screen displays the message .
8. Press START button on the AX-11.
The robot will move forward. At the same time, the display screen will show the
message .
9. Try to place any object at the front of the robot and see its operation.
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.
Robo-11 : Interactive C Robot kit Activity book99
This robot was further developed from the Robo-11 Standard by adding Infrared
reflector sensors to detect and move along a line. This chapter presents 2 models of Line
tracking robot with 2 and 3 sensors.
7.1 The Infrared reflector : Line tracking sensorThe 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-transis-
tors 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.
The figure 7-1 shows the photo and schematic diagram of the Infrared reflector
sensor board. An infrared LED in the sensor will continually receive voltage from a +V
power supply. A 510 Ω resistor is connected to limit electric current. The infrared receiver
uses a phototransistor in a parallel line with a 10 kΩ resistor.
If the phototransistor does not receive any infrared light, it will not induce any cur-
rent. Therefore the OUT terminal will have approximately 0V voltage. The value read from
input channel AI on the AX-11 also be approximately 0.
Chapter 7Robo-11 Liner
100Robo-11 : Interactive C Robot kit Activity book
The amount of electric current that flows through the circuit once the phototransistor
receives infrared light depends on the intensity of the light, which varies according to the
reflection distance. The TCRT5000 IR Reflector sensor can be used for a distance of 0.5 to
1.5 centimeters. The terminal OUT will have a voltage ranging from 0.5 to 5V. The value
read from the AX-11 via the input AI will be from 10 to 255.
7.2 Robo-11 Liner-I robot7.2.1 Building
The steps are presented in this chapter as the construction procedure for makingthe Robo-11 Liner-I ; the line tracking robot and learns about line tracking senario pro-gramming with 2 sensors.
1. Using the Robo-11 standard robot, remove the AX-11 and the upper plate from robot
chasis.
2. Insert a 3x15mm. screw through the center hole of ZX-03 Infrared reflector sensor board
and 2 pieces of 3mm. spacer. Make 2 sets.
Robo-11 : Interactive C Robot kit Activity book101
3. Turn the robot chasis upside down. Attach one Infrared reflector sensor to the third hole
of the 5-hole Straight joiner at the front of Robo-11 chasis. Tighten with 3mm.nut. Attach
another one sensor to another joiner.
4. Replace the top structure that has the AX-11 board
on it back onto the bottom part. Then connect all motro
cable to MOTOR output same Robo-11 Standrad.
5. Connect the left IR Reflector Sensor (looking down
from the top) to terminal Al-31 and the right one to ter-
minal Al-17 of the AX-11.
The Robo-11 Liner-I is now complete and ready tosearch and detect lines.
102Robo-11 : Interactive C Robot kit Activity book
!"
"!# $%&
7.2.2 Robo-11 Liner-I robot testing1. After the Robo-11 Liner-I robot has been put together, we will then write a test program
to test the operation of the Robo-11 Liner-I by having it detect a black line and move
backwards and change directions once it detects the line. Type in the Listing 7-1 and
download it to the Robo-11 Liner-1 robot.
/* Example for Robo-11 Liner-I : 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 70 /*Configuration power drive motor 50% */#define ref 80 /*Configuration analog reference 70 */
int left=0,right=0; // For keep input analog valuevoid main(void)
ao(); //while(!stop_button()) // wait for push stop button between process
printf("Press start!\n"); // Show message for drive Robotwhile(!start_button()); // Wait for push start button to runprintf(" Track Line\n"); // Show message for workingwhile(!stop_button()) // Wait for push stop button between process
left = analog(31); // Read status left sensorright = analog(17); // Read status right sensor
if((left>ref)&&(right>ref)) //check out line
run_fd(0.01); // Direct forwardelse if((left<ref)&&(right>ref)) // check left sensor in line
turn_right(1.5); // Turn right 1.5 secondelse if((left>ref)&&(right<ref)) // check right sensor in line
turn_left(1.5); // Turn left 1.5 secondelse if((left<ref)&&(right<ref)) //check 2 sensor in line
turn_left(1.5); // Turn left 1.5 second
printf("Stop..\n"); // Show off all motor messageao(); // Off all motor for endingbeep(); // Sound beep for ending
Robo-11 : Interactive C Robot kit Activity book103
void turn_left(float spin_time)
motor(0,-pow); // Motor0 backward for pow define valuemotor(1,pow); // Motor1 forward for pow define valuesleep(spin_time); // Delay set by parameter spin_time
void turn_right(float spin_time)
motor(0,pow); // Motor0 forward for pow define valuemotor(1,-pow); // Motor1 backward for pow define valuesleep(spin_time); // Delay set by parameter spin_time
void run_fd(float delay)
motor(0,pow); // Motor0 forward for pow define valuemotor(1,pow); // Motor1 forward for pow define valuesleep(delay); // Delay set by parameter delay
void run_bk(float delay)
motor(0,-pow); // Motor0 backward for pow define valuemotor(1,-pow); // Motor1 backward for pow define valuesleep(delay); // Delay set by parameter delay
!"
"!# $%&
2. Create the test field by cutting two 20 cm. long and 1 inch wide black tape and plac-
ing it 50 cm. apart on a flat surface.
3. Place the Robo-11 Liner-I on the floor and then turn on the POWER switch.
The LCD screen displays the message .
4. Press START button on the AX-11.
The robot will move forward, while using the IR Reflector sensors to detect the
black line. The robot will immediately change directions if it detects a black line, the di-
rection 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 Liner-I 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 ref 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.
104Robo-11 : Interactive C Robot kit Activity book
7.3 Robo-11 Liner-II robot7.3.1 Construction
Develop from Robo-11 Liner-I robot, with adding a Infrared reflector sensor. Thesteps are presented following as the construction procedure for making the Robo-11 Liner-II. With 3 line tracking sensors help the robot to track the line with more condition andcomplex.
1. Make the third Infrared reflector sensor structure. Insert a 3x15mm. screw through the
Infrared reflector sensor board and 3mm. spacer.
2. Attach the Infrared reflector with screw from previous step with the 3-hole Staright joiner
at first hole in the left.
!
Robo-11 : Interactive C Robot kit Activity book105
3. At the Robo-11 Liner-I robot, turn the robot chasis upside down. Insert a 3x10mm. screw
through a center hole position of the lower plate and the 3mm. nut from top side as
shown in the photo below. Do not tighten.
4. Insert the third of Infrared reflector structure from step 2 between the plate and nut.
Tighten a screw with nut.
"
106Robo-11 : Interactive C Robot kit Activity book
5. Replace the upper plate with the AX-11 board back onto the bottom plate. Tighten
with 3 of Thumb screws. Then connect the left IR Reflector Sensor (looking down from the
top) to terminal Al-31, the middle one to terminal AI-25 and the right one to terminal Al-17
of the AX-11.
The Robo-11 Liner-II is now complete and ready to search and detect lines.
7.3.2 Conditions in testing the Line SensorThe 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:
void main()
while(1) // Endless loop
printf(“L=%dM=%d R=%d\n”,analog(31),analog(25),analog(17));// Reading all sensors
sleep(0.1); // Display delay
The test results in the 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.
Robo-11 : Interactive C Robot kit Activity book107
7.3.3 When the Robot MovesScenario 1 : Robot moves along the line
Results of all sensors are as following:
!
Robo-11Liner-II
'
'
(
%)&
($
%)$*&
(
%)&
When the robot operates in this scenario, the robot must be controlled so that it
moves forward and delays briefly.
108Robo-11 : Interactive C Robot kit Activity book
Scenario 2 : The robot moves rightwards away of the line
Results of all sensors are as following:
"
"
!
Robo-11Liner-II
'
'
(
%)&
(
%)&
($
%)$*&
Robo-11Liner-II
'
'
(
%)&
(
%)&
($
%)$*&
When the robot operates in this scenario, the robot must be controlled so that it
turns left slowly and delays briefly.
Robo-11 : Interactive C Robot kit Activity book109
Scenario 3 : : The robot moves leftwards away of the line
Results of all sensors are as following:
"
"
!
Robo-11
Liner-II
'
'
(
%)
&
($
%)$
*&
(
%)
&
Robo-11
Liner-II
'
'
(
%)
&
($
%)$
*&
(
%)
&
When the robot operates in this scenario, the robot must be controlled so that it
turns right slowly and delays briefly.
110Robo-11 : Interactive C Robot kit Activity book
Scenario 4 : : The robot meet a n intersection
Results of all sensors are as following:
!
Robo-11Liner-II
'
'
(
%)&
($
%)$*&
(
%)&
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.
Robo-11 : Interactive C Robot kit Activity book111
7.3.4 Robo-11 Liner-II robot testing1. After the Robo-11 Liner-II has been put together, we will next write a test program to test
the operation of the Robo-11 Liner-II by having it detect and move forward along a black
line. Type in the Listing 7-2 code and download it to the Robo-11 Liner-II robot.
2. Turn-off power and remove the download cable.
3. Place the Robo-11 Liner-II over the black line on the floor (provided in the set) and then
turn on the POWER switch.
The LCD screen displays the message .
4. Press START on the AX-11.
The robot will move forward. At the same time, the display screen will show the
message .
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 Liner-II 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 Liner-I. It also depends on choosing the appropriate speed level. If it moves too
fast, it may swing out of its course.
112Robo-11 : Interactive C Robot kit Activity book
/* Example for Robot track line Hardware configuration - Motor left connected to DC Motor chanel M-0 - Motor right connected to DC Motor chanel M-1 */
#define pow 70 /*Configuration power drive motor*/#define ref 80 /*Configuration analog reference */int left=0,right=0,mid=0; // Keep input analog valuevoid main(void)
ao();while(!stop_button()) // wait STOP button pressed in process
printf("Press start!\n"); // Show begining messagewhile(!start_button()); // Wait START button pressed to runprintf(" Track Line\n"); // Show working messagewhile(!stop_button()) // Wait STOP button pressed in process
left = analog(31); // Read left sensor datamid = analog(25); // Read central sensor dataright = analog(17); // Read right sensor dataif((left>ref)&&(mid<ref)&&(right>ref)) // Check in line
run_fd(0.01); // Direct forwardelse if((left<ref)&&(mid>ref)&&(right>ref)) // Check over right
turn_left(0.1); // Turn left for backing to lineelse if((left>ref)&&(mid<ref)&&(right<ref)) // Check in line
turn_right(0.3); // Turn right for backing to lineelse if((left>ref)&&(mid>ref)&&(right<ref)) // Check over left
turn_right(0.1); // Turn right for backing to lineelse if((left<ref)&&(mid<ref)&&(right>ref)) // Check cross line
turn_left(0.3); // Turn left for backing to lineelse if((left<ref)&&(mid>ref)&&(right<ref)) // Check cross line
turn_left(0.3); // Turn left for backing to lineelse // If out of condition
run_fd(0.01); // Direct forward
printf("Stop..\n"); // Show finish messageao(); // Off all motor for ending programbeep(); // Sound beep for ending program
$ !"
"!# %&
Robo-11 : Interactive C Robot kit Activity book113
$ !"
"!# %&
void turn_left(float spin_time)
motor(0,-pow); // Motor0 backward with pow valuemotor(1,pow); // Motor1 forward with pow valuesleep(spin_time); // Delay set by parameter spin_time
void turn_right(float spin_time)
motor(0,pow); // Motor0 forward with pow valuemotor(1,-pow); // Motor1 backward with pow valuesleep(spin_time); // Delay set by parameter spin_time
void run_fd(float delay)
motor(0,pow); // Motor0 forward with pow valuemotor(1,pow); // Motor1 forward with pow valuesleep(delay); // Delay set by parameter delay
void run_bk(float delay)
motor(0,-pow); // Motor0 backward with pow valuemotor(1,-pow); // Motor1 backward with pow valuesleep(delay); // Delay set by parameter delay
114Robo-11 : Interactive C Robot kit Activity book
Robo-11 : Interactive C Robot kit Activity book115
This robot was further developed from the Robo-11 Standard by adding sensors
and components to measure the movement distance. The user can control the robot to
move within a specified distance more accurately.
8.1 About the Code Wheel Reflector Sensor Used with the 18 black and white color tab code wheel sticker; each color mak-
ing a 20 degree angle.
The output is a pulse signal which can be connected directly to a microcontroller.
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 NOT gates.
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 the
wheel will give 9 pulses and 18 signals.
Chapter 8Robo-11 SmartMover
116Robo-11 : Interactive C Robot kit Activity book
8.2 Building Robo-11 SmartMover robot1. Construct the Code wheel sensor structure. Attach a 30mm. Hexagonal standoff withthe Code wheel sensor board at the hole near output terminal on the component side.Tighen with a 3x10mm. screw. Next, attach a angled joiner with another end of Hexago-nal standoff by 3x10mm. screw too. Make 2 sets.
2. Using the Robo-11 standard robot, remove the AX-11 and the upper plate from robot
chasis.
Robo-11 : Interactive C Robot kit Activity book117
3. Remove all track wheels from robot chasis. Attach the Code wheel sensor structure on
the bottom plate of robot chasis by using 3x10mm. screw and 3mm. nut at the position is
shown in the photo below. Adjust the sensor module to inside the main sprocket in best
position that the wheel can turn freely.
118Robo-11 : Interactive C Robot kit Activity book
4. Attach the second Code wheel sensor stucture on the robot chasis for the right wheel
with same method.
5. Place the track wheels over the supporting wheels on both sides of the robot. Make
sure that both wheels are aligned with one another.
Robo-11 : Interactive C Robot kit Activity book119
6. Replace the upper plate with the AX-11 board back onto the bottom plate. Tighten
with 3 of Thumb screws. Connect the left signal cable from the ZX-21 Code wheel sensor
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.
8.3 Measuring distance with the Encoder WheelSensor
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.
120Robo-11 : Interactive C Robot kit Activity book
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.
The ZX-21 Code Wheel sensor 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.
8.4 Encoder_lib.ic Library8.4.1 Sourcecode
To make it convenient in using the ZX-21 Code Wheel sensor 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.
Listing 8-1 is sourcecode of Encoder_lib.ic library file for Interactive C programming.
/*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 channelint RIGHT =0; // Define for encoder right side channelint FORWARD = 1; // Define for drive robot forwardint BACKWARD = 2; // Define for drive robot backwardint SPIN_LEFT = 3; // Define for drive robot spin rightint SPIN_RIGHT = 4; // Define for drive robot spin leftint TURN_LEFT = 5; // Define for drive robot turn leftint TURN_RIGHT = 6; // Define for drive robot turn right
int POWER = 70; // 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)
Robo-11 : Interactive C Robot kit Activity book121
//-------------- Function for initial Encoder before working ----------//void encoder_init() enable_encoder(LEFT); // Enanble 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
//-------------- Function for read total step -------------------------//float total_step() return(STEP); // Return Global step count
//-------------- Function for read total distance ---------------------//float total_dist() return(STEP*0.61); // Return Global distance count
//-------------- Function for clear total step count ------------------//void clear_dist_all() STEP = 0.0; // Clear Global step count value//-------------- Function for count step by reference ------------------//void count_step(int sel_move,int step,int sel_count)
int flag=0,left,right;
reset_encoder_all(); // Reset twice Encoder
if(sel_move==FORWARD) // Condition forwardFD();
else if(sel_move==BACKWARD) // Condition backwardBK();
else if(sel_move==SPIN_LEFT) // Condition spin leftS_LEFT();
else if(sel_move==SPIN_RIGHT) // Condition spin rightS_RIGHT();
else if(sel_move==TURN_LEFT) // Condition turn leftT_LEFT();
else if(sel_move==TURN_RIGHT) // Condition turn rightT_RIGHT();
while(!flag) // Loop for check count step
left = read_step(LEFT); // Read step leftright = read_step(RIGHT); // Read step rightif(sel_count==LEFT && left>=step) // Encoder left side complete?
flag = 1; // Set flag when count completeelse if(sel_count==RIGHT && right>=step) // Encoder right side complete?
flag = 1; // Set flag when count complete
ao(); // All off motor
122Robo-11 : Interactive C Robot kit Activity book
if(sel_move==FORWARD || sel_move==BACKWARD) // Condition update Global step count
STEP = STEP + (float)read_step(sel_count);// Update step count if drive robot forward or backward
reset_encoder_all(); // Reset twice Encoder
//-------------- Function for count distance by reference -------------//void count_dist(int a,int b,int c)
count_step(a,(b*100)/61,c); // Calculate distance to step count// and drive robot in this result
//-------------- Function for drive robot forward ---------------------//void FD()
motor(0,POWER); // Motor 0 forwardmotor(1,POWER); // Motor 1 forward
//-------------- Function for drive robot backward ---------------------//void BK()
motor(0,-POWER); // Motor 0 backwardmotor(1,-POWER); // Motor 1 backward
//-------------- Function for drive robot spin left ---------------------//void S_LEFT()
motor(0,-POWER); // Motor 0 backwardmotor(1,POWER); // Motor 1 forward
//-------------- Function for drive robot spin right ---------------------//void S_RIGHT()
motor(0,POWER); // Motor 0 forwardmotor(1,-POWER); // Motor 1 backward
//-------------- Function for drive robot turn left ---------------------//void T_LEFT()
off(0); // Motor 0 breakmotor(1,POWER); // Motor 1 forward
//-------------- Function for drive robot turn right ---------------------//void T_RIGHT()
off(1); // Motor 1 breakmotor(0,POWER); // Motor 0 forward
Robo-11 : Interactive C Robot kit Activity book123
8.4.2 Explanations of the functionsTwo 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 pro-
gram, and within the main function, the user must call the encoder_init function in order
to be able to start using both encoder wheels.
1. reset_encoder_all
Used to clear the count values from the encoder wheel sensor and start
again.
Function Format
void reset_encoder_all ()
2. encoder_init
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
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.
124Robo-11 : Interactive C Robot kit Activity book
4. Total_stepUsed to read the cumulative values from the encoder wheel sensor by mea-
suring 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_distUsed 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
Used to clear the cumulative count.
Function format
void clear_dist_all()
7. count_step
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
Robo-11 : Interactive C Robot kit Activity book125
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 sensor
Right choose the right encoder wheel sensor
8. count_dist
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)
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
Used to drive the robot forward
function format
void FD()
10. BK
Used to drive the robot backwards
function format
void BK()
126Robo-11 : Interactive C Robot kit Activity book
11. S_Left
Used to make the robot to rotate left
Function format
void S_LEFT()
12. S_Right
Used to make the robot to rotate right
Function format
void s_right()
13. T_Left
Used to make the robot turn left
Function format
T_LEFT ()
14. T_RIGHT
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.
8.5 Robo-11 SmartMover TestingThe 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 robot’s turns
and changes of direction more accurate.
Robo-11 : Interactive C Robot kit Activity book127
8.5.1 60 cm-mover : Drive the Robo-11 SmartMover forwardfor 60 centimeters1. Type in the Listing 8-2 and download it into the Robo-11 SmartMover.
2. Place the Robo-11 SmartMover on the floor and then turn on the POWER switch.
The LCD screen displays the message .
3. Press START button on the AX-11.
The robot will move forward 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.
#use "encoder_lib.ic"/*Include Library file encoder_lib.ic */void main()
encoder_init(); // Initial EncoderPOWER = 60; // Set power at 60%printf("Press Start!\n"); // Display message for wait press start buttonwhile(1) // Infinite loop
while(!start_button()); // Wait for start button pressprintf("\n"); // Clear LCD displaycount_dist(FORWARD,60,RIGHT); // Robot forward 60 cm
// reference by Encoder right sideprintf("STEP %f\n",total_dist()); // Display step count
!"#"$%"& ' &
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 Code Wheel sensor. Then initiate the encoderwheel sensor by using the function encoder_init, followed by defining the motor power to 50% of itsmaximum power.
Next, a message appears on the LCD awaiting the START switch to be pressed. The robot willthen move forward for a distance of 60 centimeters and stops. The robot will display the cumulativedistance 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.
128Robo-11 : Interactive C Robot kit Activity book
8.5.2 U-mover: Driving the Robo-11 SmartMover in a U-Shape1. Type in the Listing 8-3 and download it into the Robo-11 SmartMover.
2. Place the Robo-11 SmartMover on the floor and then turn on the POWER switch.
The LCD screen displays the message .
3. Press START button on the AX-11.
The robot will move forward 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 topview, he will see that the robot’s 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.
/*Hardware configuration - Encoder sensor left connected to IN-8 - Encoder sensor right connected to IN-7 - Motor left connected to DC Motor chanel M-0 - Motor right connected to DC Motor chanel M-1*/#use "encoder_lib.ic"/* Include library encoder_lib.ic*/void main()
encoder_init(); // Initial encoderPOWER = 72; // Set power 72%printf("Press Start!\n"); // Display messagewhile(1) // Infinite loop
start_press(); // Wait for press STARTprintf("Run...\n"); // Display message for runningcount_dist(FORWARD,30,RIGHT); // Forward 30 cm referance by right encodercount_step(SPIN_RIGHT,10,RIGHT); // Spin right 10 step
// referance by right encodercount_dist(BACKWARD,30,LEFT); // Backward 30 cm.
// reference by left encoderprintf("Stop...\n"); // Display message for stop
(
!"#"$%"& ' &
Robo-11 : Interactive C Robot kit Activity book129
130Robo-11 : Interactive C Robot kit Activity book
!"#$%&
!"#
$% & & $
%%$ ! '
% & ! %%% %
(% %% % %$'% &
&%% !)% & %
* &%%$ &)% +
! % $%%
$ !, &%%$ +
& % &%-
% %& %$%%* $ !
& % &%
'%% &* %,%. %&/
0 % /
% & %%
1% 0&'# $$$0" & $
($)* & %2&$