Sunteți pe pagina 1din 175

1

SPINNINGLEDBALL
EmbeddedMicrocontroller
Group1

FinalReport

Submittedto
TheFacultyofOperationCatapultLXXXVIII
RoseHulmanInstituteofTechnology
TerreHaute,Indiana

2
by

Group1

AlecArmstrong OlentangyLibertyHighSchool
Powell,Ohio
TimKuhnen R.L.PaschalHighSchool
FortWorth,Texas
BanksHunter AviationHighSchool
Seattle,Washington

July27,2010

Introduction(Goals)

Humanityhasalwaysbeenfascinatedbylight.Sincethecreationofthelightbulbin1878we
havefilledourworldwithlights.Wecontinuetothisdaytocreatelightinmanydifferentforms.Just
lookatTimesSquareinNewYorkCity,whichisenthrallingbecauseitscoveredinlights.Weuselights
foravarietyofentertainmentpurposes.Somelightscanmakestrangeeffects,likeblacklights.
3
Lightsareusedveryoftenatparties,butnotregularlights.Insteadtherearecoloredlight,
flashinglights,andblacklights.Lightsareusedtomakepartiesseembetterandmorefunwithallofthe
crazylightsgoingoff.Havingspontaneouslightshelpsusgetawayfromourusuallyrepetitivelifestyle.
WedecidedtomaketheSpinningLEDBallbecauseourgoalwastocreateanentertaining
projectusingathreedimensionalLEDlightshow.Thistypeofprojecthasneverbeenattemptedyetat
OperationCatapult,sowehadtodesigneverythingweusedfromscratch.

UsersGuide

TheSpinningLEDBallisafast,complexmachine.Itcanbedangerousthough,sobeverycareful
whenitisrunningandDONOTputanythinginthespinnerwhileitisrunning.Doingsowillcause
damagetoyourselfand/orthemachine.Therearetwoswitchesandtwodialsonthemachine.Toturnit
on,simplyplugthemicrocontrollerintowallpower.ThiswillturnontheLEDsbutwillonlygivepowerto
themotors,notturnthemon.Oneswitchturnsonthetopmotor,andanotherchangesitsdirection.
ThefirstdialcontrolshowmanytimestheLEDflashespersecond.Theseconddialcontrolshowfastthe
firstmotorspins.Tocontrolthemorepowerfulmotor,wehadtouseapowersupplybecausebatteries
dontsupplyanywherenearenoughcurrenttodriveit.Thismeansthattopowerthelargermotoryou
needtoconnectandturnonapowersupply,itwilldrawabout5.5Ampsat3.5Voltswhichisasafe
maximumspeedtorunitat,anyfastercouldgetdangerous.

Hardware

TheSpinningLEDBallwascreatedbyfirstmountingthreepowerfulRGBLEDsonanacrylicbase
thatisattachedtoashaftpoweredbytheinnermotor.Thismotorandshaftarethenmountedona
largerframewhichitselfismountedonanothershaft.Thesecondshaftispoweredbyalargermotor
whichislocatedbeneaththevisiblepartoftheapparatus.Poweristransmittedfromthe
microcontrollerandACconverterviabrushcontactsmountedaroundbothshafts.Becausetheshafts
arerotatingindependentlyandpowerneedstobetransmittedacrossthemwhiletheyspin,traditional
formsofwiringarentapplicable.Weneededtocomeupwithasolutiontotransmitpoweracrossa
rotatingsurface,andhadanideasimilartoslidingcontactswhichwecallbrushcontacts.Thesecontacts
consistofconductivebrusheswhichpressagainstaninsulatedcoppersurfacewrappedaroundthe
shaft.Theoutershaftrequiresfivecontacts,oneforeachLED,onefortheinnermotor,andonefora
commonground.Theinnershaftonlyrequiresthreecontacts,oneforeachLED,becauseweusedthe
metalshaftitselfasthecommongroundcontacttoconservespace.Thesecontactsareseparatedby
4
lasercutacrylicwashersonthesmallershaft,andthecoppertapecontactsonthelargershaftare
wrappedaroundnonconductiveelectricaltapewhichpreventsthemfromshorting.Theentiresystemis
controlledviaaprogrammableMicrochipPICmicrocontrollerandanaccompanyingdevelopmentboard
whichreadsuserinputviapotentiometersandswitchestocontrolthespeedsofthemotorsandthe
on/offstatesofeachindividualLEDaswellastheirblinkspeeds.Theprogrammablenatureofthe
microcontrollermeansthatwecanalsoloadcontrolsontoitsRAMandhaveapresetlightshow.

Software

ThesoftwareforourprojectwasdesignedtoregulatemotorcontrolandcontroltheLEDs.To
dosoweusedamotorcontrolchipthatcancontrolspeed,directionofspin,andon/offpowerbyusing
threepins.ThethreepinsforthemotorwereL1,L2,andPWM1.Usingthediagrambelow,inputfor
eachpinwillresultindifferentmotoraction.

ENABLEL1L2Result

LLLOFF
LLHOFF
LHLOFF
LHHOFF
HLLBRAKE
HLHFORWARD
HHLBACKWARD
HHHBRAKE
PWMLLPULSEBRK
5
PWMLHFWDSPD
PWMHLBCKSPD
PWMHHPULSEBRK

Tocontroltheoutputfromthemaincontrolboardtothemotorcontrolchipforeachpin,L1,L2,
orPWM1(PulseWidthModulation),wecreatedtwoswitchesandadialtogivethemaincontrolchip
directionstosenddifferentsignalsout.Thefirstswitchwesetupwasadigitalon/offswitch.Whenthis
gaveanoutputof0itwouldturnL1andL2tothesamevalue,eitherbothoneorbothzero.Thenext
switchweusedwasadirectionalcontrolswitchforthemotor.Whenthemotorpowerswitchhadan
outputofone,themaincontrolchipwouldoutputeitheronlyL1witha1(on)oronlyL2witha1to
regulatewhichdirectionthemotorturnsasshownbythecodebelow.

if(Motor1Power==1)
{
if(MotorDirection1==1)
{
L1=0;
L2=1;
}

}
if(Motor1Power==1)
{
if(MotorDirection1==0)
{
L1=1;
L2=0;
}
6
}
if(Motor1Power==0)
{
L1=0;
L2=0;
}

ThelastpartofthecontrolwasthePWM1pinwhichismeanttocontrolthespeed.ThePWM1
pinonthemotorcontrolchiptakesDCcurrentthatneededtochangevalue,sotochangethesignaltoit
fromadigitaloutput,weusedsquarewaveDCcurrentfromthemaincontrolchip.Thissquarewave
wasregulatedbysendingthroughapotentiometerananalogsignal.Themaincontrolchipwouldthen
convertthisanalogsignalintoasquarewaveforoutputtothemotorcontrolchip.
Theprogramandcircuitrywassetuptosupporttwomotorsthroughthisdesign,butwefound
thatthelargermotorneededmorecurrentthanthemotorcontrolchipwouldallow,soitwouldntrun.
InsteadweusedalaboratoryDCpowersupplytoregulatethebottommotor.

Testing

Continuoustestingplayedamajorpartinourproject.Thefirsttestwasonthefirstmotoralone.
Wethenputtheshaftonthemotorandmeasuredhowfastitspun.Furtheronweattachedtheacrylic
baseandsomesampleLEDstocheckifitwasbalanced.Wethenmovedontomakingthecopper
contactsontheshaftandtestingtoseeifthecontactsworked.Fromtherewestartedtobuildtheframe
forthefirstmotor.Whenweattacheditwenoticedthatthebrusheshaddifficultlywithcontinuously
touchingthecontacts.Whilewewerebrainstormingforasolution,wealsodiscoveredthattheframe
wasoffbalanced.Ourgroupjustsimplyaddedenoughwashersontheothersidetobalanceoutthe
weight.Comingbacktothebrushes,wedecidedtousemoredurablecopperwiresthatwerealsoheld
inplacebyasmallacrylicframe.
TogetthepoweruptothefirstmotorandtheLEDsweputwiresthroughthesecondshaft
whichwaspoweredbyanothercontactsource,exceptthistimeweusedcoppertapetohavea
smoothercontact.AroundthistimeoursuperbrightLEDshadcomeinthemail,andsoweattached
themandlearnedthattheyuseddifferentamountsofcurrents.Knowingthat,weuseddifferent
resistorsoffofthesameenergysourcetogettherightcurrent.
7
Atthistimewestartedtohitsomeprogrammingissues.Someproblemswerewiththepinsand
whatoutput/inputtheyarecompatiblewitheitherdigitaloranalog.Moreover,wehadtrouble
programmingourswitchesanddials.

Conclusion(Analysis+Discussion)

Sincewestartedthisproject,weknewthatitwouldbeahugesuccess.Itseemedalittle
complexatthebeginning,buteverythingturnedoutnicelyintheend.Wehadhopedthatwecould
controlthesecondmotorbutwecouldntbecausethemotorcontrolchipdidntallowenoughcurrent
forthemotor.Eventhoughwedidntgetthatmotorcontroltowork,wethinkthattheLEDballisstill
prettycool.

Balancing Robot
Embedded Microcontrollers Group 2

Final Report




Submitted to
The Faculty of Operation Catapult LXXXVIII
Rose-Hulman Institute of Technology
Terre Haute, Indiana

8





By
Group 02
Charles Baechler
Ryan Thwaites

July 27, 2010
Introduction
The Segway is a revolutionary device that uses gyro sensors and accelerometers to stay
balanced despite only have two wheels. Using this bi-cycled design, the Segway revolutionizes
transportation and is a feasible alternative to walking.
However, this new mode of transportation is expensive. With some Segway models over
one thousand dollars in price, it is easy to see why Segway sightings are rare and most robots and
cars have at least three or four wheels.
There is no doubt that using a gyro sensor and accelerometer to keep a machine balanced
is expensive, since using these items in our robot would have cost more than twice our allotted
forty dollar budget. Using our high intelligence, we came up with a far more economically
feasible solution by substituting pricey equipment with cheaper hardware, such as a distance
sensor. Using this system, we set out to create our robot. If the robot turns in one direction, the
distance between the sensor and the ground will change and a motor will turn to adjust the
position of the robot accordingly.
Users guide
The robot is so simple and easy to use that even a catamonkey can use it. To turn on the
machine, simply set the robot on the ground and flip the switch on the top of the casing. For the
users convenience, we even labeled which side is on and which side is off.
Sandy Spring, Maryland
Senoia, Georgia
Sherwood High School
Landmark Christian Sschool
9
In order to perform maintenance and battery replacement, access to the interior of the robot is
necessary The top of the casing is secured via Velcro to allow easy access to the inside of the
robot.
The machine requires four AA batteries for use and the battery casing would need to be
removed from the interior of the robot to allow room to take the batteries out. The battery casing
can easily be removed and returned to its secure location in the casing because it is mounted
inside using Velcro.
As the robot wobbles back and forth, the distance sensor mounted outside of the casing
will record different distances from the ground. If the robot falls right, the distance recorded will
be shorter and will be longer if the robot falls backwards. Based on the distance recorded, the
wheels will turn to counteract the tipping of the robot. If the robot falls forwards, the wheels will
turn forwards. If the robot falls backwards, the wheels will spin backwards.
The robot will always work best on a flat surface and was tested on a beige-colored floor.
In theory, the robot should be able to operate on any colored floor. The floor must also not be
slanted, for this will change distance variables the robot records and the wheels will spin even if
balance is maintained.
Hardware
The initial design of the balancing robot boasted a cylindrical casing made from a small
piece of PVC pipe. Much to our dismay however, not all of the components needed would fit
into such a small space. We also aspired to place a flashing light onto the top of the robot purely
for aesthetic purposes. However, this addition to the robot will make it too top-heavy and thus
would fall over more easil0y, and the idea was thrown out.
Much of the hardware for the balancing robot was custom designed and made to fit our
specifications. Items like this includes the casing, which is made from thick wooden sheets.
The gears were also custom designed and made using a laser cutter that can be operated using a
computer and uses machinery to create the parts. The gears are fitted onto the driveshaft of the
motor and the axel that is driven by the motor. In order to generate more speed, the gear on the
motor is significantly larger than the gear on the axel. The metal rod that serves as our axel was
also made from scrap from the supply room. It was the correct diameter to fit the pre-made
wheels and axel gear.
Some of the materials were taken from other projects and easily available products.
Materials like this includes the two wheels taken from a remote controlled car which have the
correct diameter and thickness that we were looking for. To add more traction to the wheel, we
lined the outer edge of it with rubber bands to serve as a tire with more friction. The metal rods
used to fasten the motor to the casing was also salvaged from the remote controlled car.
10
Since an ordinary servo motor took too long to change direction and respond to the quick
changes in signal, we used a modified servo motor that did not include the electrical feedback
which regulates its accuracy. Using a standard servo motor, the robot would not be able to react
fast enough to the changes in distance recorded.
Our distance sensor was also premade. It uses an infrared beam which is flashed on a flat
surface. The beam is then reflected back into the receiver that sits next to the transmitter. Using
this infrared beam, distance is recorded as a specific voltage. Depending on the distance the
sensor records, the robot receives valuable information that helps maintain its balance.
The main board connects all of the components together. We soldered a battery pack into
the voltage and ground pins on the board. This provided power to the entire board. We then
connected the infrared sensor to another pin and to the power and ground where the batteries are.
The motor had to be connected to a motor control board and it is connected to the main board.
The motor control board is connected to the main board by three pins: L3, L4, and E. The L pins
act as directional controllers and the E pin controls whether the motor is on or off. Finally, the
power runs through a switch which controls whether the robot will run or not.
Software
The basis of the software provided by Dr. Song and was later calibrated so that the
wheels turn into the correct direction and stop when the robot is level with the ground. We first
adjusted the software to guarantee that the wheels turn in the proper direction. We then altered
the software to end the motor stuttering we have been experiencing.
At first we wrote our program to run a servo motor. It used a signal to control the
direction of the motor and a pulse length to change the speed of the motor. The servo started
stuttering so we had to change to a DC motor. A DC motor is controlled by a square wave DC
current provided by a power source. To achieve this with a battery pack, we had to use a DC
motor control board. We rewrote the software with this in mind and changed all the previously
used servo commands to work with the new control board. We needed to control the board and
this was achieved by using pins and programming these pins into the software. The DC motor
responds to 1 and 0 for on and off. This controls the direction of the motor. The board in return
sends the signal to the motor and enables the whole robot to move. The signal changes on or off
depending on the voltage reading from the infrared sensor.
The sensor reports different voltages depending on the distance from the ground. We
programmed an upper and lower bound for the voltage readings. If the voltages passed out of the
given range, the motors would adjust and the robot would maintain its balance. We had to test
the robot to find the right values for each bound and we eventually found them and put them into
the software.
Testing
11
Our first form of testing included using a breadboard to check our circuitry. After
installing all of the components to the bread board via wiring, we checked to make sure that the
motor was running properly and that our distance sensor was generating measurements properly.
We used these measurements for our main program.
Regardless of our efforts, we were not able to fully reach the testing stage of our robot.
Most of our testing includes testing the distance at which the sensor will trigger a change in the
direction at which the wheels turn. This was accomplished by simply waving a hand in front of
the sensor and moving it back and forth. Based on our findings, we would then adjust the
software accordingly. At times, we were also able to place the robot on the ground and closely
monitor it to guarantee that it will not fall over.
Conclusion
At the beginning of our project, we were both hopeful that we would be able to create a
robot to complete one simple task within two and a half weeks. As those two and a half weeks
passed, we quickly learned that a seemingly simple task was near the impossible. Building a
robot that is able to balance itself for under forty dollars is a large leap from one that costs more
than one thousand dollars to balance itself. However, it does not change the fact that our robot
has had embarrassing results. After two and a half weeks of building, we have not even been
able to properly test our robot. Currently, our robot will not work at all after adding a new part.
The robot is stubborn and often refuses to acknowledge changes made in the programming to
adjust the height at which the motor will move and in which direction. Calibrating the distance
was also impossible and the sensor is not accurate enough to detect the slightest change in
direction, the sensor, on average, must move at least one inch either away or from the ground in
order for the motor to change. On top of that, the robot will often fall before the wheels can even
adjust, it is impossible for the bottom of the robot to maneuver underneath the top half fast
enough to prevent tipping over.

12

13


Front view of the robot.

14












Flowchart Depicting the actions of the balancing robot.
15

Schematics for the wiring.
















16


// PIC16F877A file: ServoSensor.c
// Generate Servo control square wave with Timer0 interrupt.
//Check Sony IR distance sensor
#include <pic.h>
// crystal frequency: 20MHz
#if defined(_16F877A)
__CONFIG(HS & WDTDIS & PWRTEN & LVPDIS);
#endif
void Timer0_Initialization(void);
void interrupt ServoDriver(void);
void ATD_initialization(void);
void Get_Voltage(unsigned int *Voltage);
#define ServoControlPin RC2
#define ServoControlPinDirection TRISC2
#define L3Pin RC0
#define L3PinDirection TRISC0
#define L4Pin RC1
#define L4PinDirection TRISC1
// interrupt duration
#define INITIAL_COUNT 200 // 128 microseconds per interrupt at 8MHz
// pulse width to control rotation of a motor
#define Neutral 35 // 1.5ms
#define ZeroDegree 70 //1.1ms or less
#define Degree180 25 // 2.3 ms, 1.75ms or more
// pulse period
#define PULSE_PERIOD 200 //11.5ms period
#define upperbound 400
#define lowerbound 390
unsigned int period, pulsewidth, PULSELENGTH;
void main(void)
{
unsigned char i, count;
unsigned int Voltage;
ServoControlPinDirection = 0; //Servo Control Pin is output
L3PinDirection = 0;
L4PinDirection = 0;
Timer0_Initialization();
period = PULSE_PERIOD;
//ServoControlPin=1;
pulsewidth=ZeroDegree;
ATD_initialization();
count=1;
PULSELENGTH = 150;
//L3Pin = 0;
17
//L4Pin = 1;
//while(1);
while(1)
{
Get_Voltage(&Voltage);
if(period==0) {
if(Voltage<lowerbound)
{
L4Pin = 0;
L3Pin = 1; //backward
}
else if (Voltage >upperbound)
{
// PULSELENGTH = ZeroDegree;
L4Pin = 1;
L3Pin = 0; //forward
}
else
{
//PULSELENGTH = ZeroDegree;
L4Pin = 0;
L3Pin = 0;
}
}
}
while(1); //just hold cpu here

}
// end of main()
//Initialize Timer0 for interrupt to generate servo control signal
void Timer0_Initialization(void) {
//Timer0 Interrupt initialization
T0CS = 0; // Set prescaler to Timer0
PSA=0; // interrupt source connected to prescaler
PS2=0;
PS1=0;
PS0=0;
// Timer0 interrupt
T0IF=0;
T0IE=1;
TMR0=INITIAL_COUNT; // interrupt occurs every 10 microseconds
GIE = 1; // turn on global interrupt flag
}//end of Timer0_Initialization()
// Interrupt service routine to generate servo conttrol signal
void interrupt ServoDriver(void)
{
18
if(T0IF==1) { // interrupt internal is
if (period!=0) period = period --;
else {
period = PULSE_PERIOD; //initialize period
pulsewidth=PULSELENGTH; //initialize pulse
ServoControlPin=1; //start pulse
}
if (pulsewidth!=0) pulsewidth--;
else ServoControlPin=0; //end pulse
TMR0=INITIAL_COUNT;
T0IF=0;
}
} //end of ServoDriver()
//end of ServoDriver.c

MazeNavigator
EmbeddedMicrocontrollerGroup3

FinalReport

19

BrandonSchirmer InglemoorHighSchool
Redmond,Washington
EricNewhall HammondHighSchool
Columbia,Maryland

September3,2010

20

Introduction

Inmacroscopiccreatures,theabilitytomoveisusuallyfoundalongsidetheabilitytosee.Thisis
becausethesetwoabilitiescomplementeachother.Whatisfoundinnatureisoftenimitatedinmans
creations.Duetothis,anyrobotwhichisabletomoveisalsoabletousesenseitssurroundings,usinga
varietyofdifferenttechnologies.Acommonlyusedsensoristheultrasonic,whichisusedtodetermine
distancefromanobject,andinfrared,whichcanbeusedtodeterminedistance,temperature,andlarge
differencesinthecolorofanobject.Usingthesesensorsitallowsrobotstointeractwiththeir
environmentandperformavarietyofusefultasks.Onesuchtaskisvirtualmappingwhichallowsrobots
tomovethroughanenvironmentandprovidedatabacktotheuser.

UsersGuide

AfterthepowersupplyispluggedintothePICmicrocontroller,thenavigatorwillwaitforafew
secondsbeforeitbeginstooperateandattemptstoescapethemaze.Thisdelayiscausedbyforcing
themicrocontrollertocyclethroughseveralnestedforloops.However,initsprogramithasa
hardcodedstartingposition,whichmustbechangedifitisstartingfromadifferentsquareand/orfacing
adifferentdirection.Additionally,thesizeofthemazemustbechangedinthesourcecodeto
accommodatedifferentsizedgrids.

StructureandDesign

Mostpartswerescavengedfrompreviousgroups.Servomountsweretakenfromanold
projectandthenoseconewastakenfromanotheroldprojectandsandeddown.Otherwiseallthe
woodcomponentsweredesignedandcutspecificallyforthisproject.
21
Thenavigatorusesthreewheels.Thetworearwheelshaverubbertiresandareattachedto
theirownservomotor.Inthefront,thereisanOmniwheel,whichallowsthemazenavigatortoturn
andmoveforwardwithasmallamountoffriction.Omniwheelshavesmallerwheelsembedded
perpendiculartodirectionofthemainwheel.Thesesecondarywheelsspinindependentlyofthemain
wheelallowingthewheeltomoveinanydirection.DuetothesmallamountoffrictiontheOmniwheel
contributesregardlessofdirection,theaxisofrotationissimplythemidpointofalinedrawnbetween
theaxelsofthetwoservopoweredwheels.
IRsensorsareplacedunderthenoseandunderthewingtips,whichextent8.5fromtheaxisof
rotationforthispurpose.Thewallswhichholdthewingsandtheneckhaveholeswhichallowthewires
unobstructedaccessbetweenthemaincircuitboardandthesensors.

Hardware

Themazenavigatorshardwarewasentirelyscratchbuiltfrombasiccomponents,suchaswire,
resistors,andinfraredLEDs.Thesecomponentsweremountedontoonemaincircuitboardwhich
controlsthesensorsandservosandthreesmallerboardswhichcontainedthecomponentsfortheinfra
redsensors.
Therobotispoweredbya9voltbattery.Thebatteryprovidesenoughpowerforbothservos
andallthreeinfraredsensorstorunsimultaneously.Thevoltageiscontrolledthroughtwoseparate
voltageregulators.ThefirstregulatorisintegratedintothePICmicrocontrollerandreducesthevoltage
to5V.Thispowerisusedforthethreeinfraredsensorswhichruninparallel.Thenanothervoltage
regulatorwasbuiltandmountedtothemaincircuitboard.Thisregulatorreducedvoltagedownto6V
andwasusedtorunthetwoservomotorsinparallel.
ThethreeinfraredsensorsusedbythenavigatoraremadefromaninfraredLEDandan
infraredreceiver.TheIRsensorworksbyemittingIRlight,andmeasuringandamountofIRlightthat
reflectsback.Themorereflectivethesurfacebelowis,themoreresistancethesensorprovideswhich
reducestheamountofvoltagethatcontinuesalongthecircuit.Thecutoffbetweenonandoffis2.5
volts.AsawhitepieceofpaperreflectsIRlightmuchbetterthanablackpieceofpaper,alowvoltage
fromasensormeansthatawhitesquareisbeneaththesensorwhereasahighvoltagefromasensor
meansthatablacksquareisbeneaththesensor.Typically,therangeofvaluesforthesensorsis.05V
forwhiteand4Vforblack.Thesensorsareplacedinseveralperfboardswhichhangupsidedown4.5
fromtheground.Eachperfboardisplaced8.5fromtheaxisofrotation,theyarepointedtotheleft,
front,andright,withboththeleftandrightperfboardforminga90withtheaxisofrotationandfront
perfboard.Withthisconfigurationthenavigatorcandetectthecolorofthegridsquaresofthemaze
thatareinfrontofitandtoeithersideofit.
22
InordertocommunicatewiththesensorsandtheservomotorsspecificI/Oportsareusedon
thePICmicrocontroller.TheservomotorscommunicatedwiththemicrocontrollerviaPWMcables.
Thesesupplebothapowersourceandgroundbutalsohaveasignalwireconnectedtoanoutputpin.
Byoutputtingsquarewavefunctionswithvaryingwavelengthstheservosspeedanddirectioncanbe
controlled.Theservoexpectstoseeapulsegeneratedevery20milliseconds.Thelengthofthispulse
determineshowfartheservowillrotate(0180degrees).Anormalservoismechanicallynotcapableof
turninganyfartherduetoamechanicalstopbuiltontothemainoutputgear.Insteadofnormalservos
themotorsthatwereusedontherobotweremodifiedsothattheycouldrotatefreelyprovidedthat
thecorrectsignalwasoutputted.
Theservosuseproportionalcontrolinthewaytheymove.Theamountofpowerappliedtothe
motorisproportionaltothedistanceitneedstotravel.Becauseofthiswhentheshaftneedstoturna
largedistancethemotorwillrunatfullspeed.However,ifitonlyneedstoturnasmallamountthenthe
motorwillrunataslowerspeed.

Software

ThePICmicrocontrollerisprogrammedintheCprogramminglanguageusingtheMPLabIDE.
TheClanguageallowsforprecisecontrolofthewaythatthemicrocontrollermanagesmemory,
programflow,andinterrupts.TheefficiencyoftheHITECHCcomplierallowsforthelimitedphysical
memorytostoreandruncomplexcomputerprograms.
Inordertosuccessfullyescapethemazetherobotmustbeabletomapitsownlocationanduse
amethodtonavigatethegrid.Theprograminitializesatwodimensionalintegerarraytostorethe
virtuallayoutofthemaze.Thearrayis9x9witheachspacerepresentingablackorwhitepieceofpaper
onthefloor.Onesarespacesthatareblackorclosedandzeroesarespacesthatarewhiteoropen.The
arraystartsasallknownwhichisrepresentedbythenumberfive.Astherobotmovesandscansthe
differentspacesofthearrayarefilledinwiththeinformationgatheredfromtheinfraredsensors.
Additionally,therobotsxandycoordinatesarestoredsothattherobotisabletodeterminewhereitis
inrelationtothegrid.
Thepatternthattherobotusestomovethroughthemazereliesonitpickingandfollowinga
walluntilitreachesanescapepoint.Inthiscasetherobotalwaysfollowsthelefthandwall.Itdoesthis
byscanningthesquarestotheleftandrightandthesquareinfrontofit.Thenifthesquaretotheleftis
opentherobotwillturnleftandmoveforward.Otherwiseifthesquareinfrontofitisopentherobot
willmoveforward.Ifneithertheleftorfrontsquaresareopentherobotwillchecktherightsquareand
turnandmoverightifitisopen.Finallyifallthreesquaresareclosedtherobotwillturnaround.Using
thissimpleprocesstherobotcanescapeanymazewithanexitontheouterperimeter.
23
Toturnandmovetherobotmustmanageandoutputsquarewavestotheservomotors.The
squarewavesarecreatedfromaperiodicinterruptfunction.Every0.1millisecondstheinterrupt
serviceroutineorISRisentered.ThisISRfirstschedulesthenextinterrupttooccurandclearsan
interruptflag.Ifthisinterruptflagisnotclearedinsidetheinterruptroutine,thenthePICwillbe
immediatelyinterruptedagainuponreturnfromthisinterruptroutinewithoutwaitingtherequired1
millisecond.Thentheinterruptcountersarecheckedtoseeiftheyarebelowthevaluesetforthepulse
widthofthesquarewave.Ifthevalueisgreaterthanthepulsewidththenthecorrespondingoutput
pinissettozerowhenpreviouslyitwasatone.Theinterruptcounterarethenwrappedbacktozero
whenthecounterreaches200(20milliseconds)whichallowsforthenextsquarewavetobecreated.
Usingthisinterruptmultipleservomotorscanbecontrolledatthesametimebycomparingthe
interruptcountertomultiplepulsewidthvariables.

Testing

Toensurethefullfunctionalityofthenavigatoritwasimportanttosystematicallytesteach
physicalandsoftwarecomponentindividually.Thefirstcomponenttestedwastheinfraredsensor.
Thesethreesensorswereeachbuiltonabreadboardandsuppliedpower. Thentheirvoltagewas
measuredusingavoltmeterwhenwhiteandblackpiecesofpaperwereshowntoit.Afterthecorrect
voltageswerereceivedthesensorsweresolderedtothethreesmallcircuitboards.
Next,theservoshadtobetestedtoensuretheyhadbeenmodifiedcorrectly.Usingan
oscilloscopedifferentsquarewavepatternsweregenerated.Thepulsewidth,frequency,and
amplitudeofthewaveswereadjusteduntileachoftheservosturnedcorrectly.Thenwiththat
informationtheprogramcouldeffectivecontrolthespeedanddirectionofmovementoftheservo
motors.
Nowwithboththesensorsandmotorsitwaspossibletoassembletherobotschassisandbegin
testingsoftware.Themostimportantandperhapsmostdifficultpartoftestingwasensuringthatthe
robotmoveinaquantifiedmanner.Sincetherobotmovedthroughagriditneededtomoveexactly
onegridspacepermoveandonlyturnat90degreeangles.Byadjustingthetimethattheinterruptthat
generatesthesquarewavefortheservosranfor,thedistancewasadjusteduntilitwasexactly8.5
inches.Similarlythetimewasadjustedsothatitwouldturn90degree.However,anadditional
problemwaskeepingtherobotdrivingstrait.Thetwoservosweremountedonoppositesidessothey
neededdifferentpulsewidthstodrivebeabletobothturnthesameway.Becauseofthisthepulse
widthwereadjusteduntilbothservosturnedatthesamespeedinthesamedirection.

Conclusion

24
Afteralongperiodofdebuggingbothhardwareandsoftwareissuestherobotwasableto
successfullycompleteamaze.Themainproblemswerewiringtheinfraredsensors.Twoofthesensors
wouldworkfinebutonewouldnot.Buttheproblemwasnotthesensoritwaswiththewiring.No
matterwhatsensorwastestedtheonesetofwireswouldcauseittofail.Afterreplacingseveralwires
andcomponentstheissueswerestillnotfixed.TheproblemwasonlyresolvedwhentheI/Oportsthe
sensorswerewiredintowerechanged.ForsomereasontheRC0andRC6portswouldnotworkwhen
portsRC1RC5would.OncethesensorswererewiredintodifferentI/Oportstheproblemwasresolved.
Forthatpointonwardstherewereveryfewproblems.Therobotwasabletopassseveralsmallscale
testsuntilfinallyitwastestedonthefullscaleandsucceededthegoalsthathadbeenset.

25

CircuitDiagrams

26

Code

27
#include<pic.h>

#ifdefined(_16F877A) //configurationbits
__CONFIG(HS&WDTDIS&PWRTEN&LVPDIS&UNPROTECT);
#endif

voidinterruptinterrupt_scv_rtn();
voidmove(void);
voidturn(int);
voidscan(void);

unsignedcharpulse_width1,pulse_width2,interrupt_cntr;

#defineMotor1RC0
#defineMotor2RC1

#defineSensorIn1RB2
#defineSensorIn2RB4
#defineSensorIn3RB3
#defineSensorIn4RB6

unsignedcharRobotX=1;
unsignedcharRobotY=0;

unsignedcharFacingDirection=3;//1=N,2=E,3=s,4=w

unsignedcharboard[9][9]={{5,0,5,5,5,5,5,5,5},
28
{5,5,5,5,5,5,5,5,5},
{5,5,5,5,5,5,5,5,5},
{5,5,5,5,5,5,5,5,5},
{5,5,5,5,5,5,5,5,5},
{5,5,5,5,5,5,5,5,5},
{5,5,5,5,5,5,5,5,5},
{5,5,5,5,5,5,5,5,5},
{5,5,5,5,5,5,5,5,5}};

voidmain(void){

TRISC1=0;TRISC0=0;
TRISB=0b11111111;

T0CS=0;
PSA=0;

PS2=0;
PS1=0;
PS0=0;

RB0=0;

PCFG3=0; PCFG2=1; PCFG1=1; PCFG0=0;
ADCON1=0b10000110;

TMR0=256250;
29
T0IF=0;
T0IE=0;

GIE=1;
interrupt_cntr=0;


for(inti=0;i<30000;i++){
for(intii=0;ii<20;ii++){
//wait
}
}

while(RobotX!=8){
scan();
}

move();

while(1){
//waitatend
}


}

voidinterruptinterrupt_scv_rtn(){
30
TMR0=256250;
T0IF=0;

if(interrupt_cntr<pulse_width1){
Motor1=1;
}else{
Motor1=0;
}

if(interrupt_cntr<pulse_width2){
Motor2=1;
}else{
Motor2=0;
}

interrupt_cntr++;

if(interrupt_cntr==200){
interrupt_cntr=0;
}


}

voidmove(void){
pulse_width1=12;
pulse_width2=30;
31

T0IE=1;

for(inti=0;i<30000;i++){
for(intii=0;ii<10;ii++){
//wait
}
}

T0IE=0;

if(FacingDirection==1){
RobotX;
}elseif(FacingDirection==2){
RobotY++;
}elseif(FacingDirection==3){
RobotX++;
}elseif(FacingDirection==4){
RobotY;
}

for(inti=0;i<30000;i++){
//wait
}
}

//1==left,0==right
32
voidturn(intd){
if(d==1){

pulse_width1=15;
pulse_width2=15;

T0IE=1;

for(inti=0;i<26000;i++){
for(intii=0;ii<12;ii++){
//wait
}
}

T0IE=0;
}elseif(d==0){

pulse_width1=10;
pulse_width2=10;

T0IE=1;

for(inti=0;i<26500;i++){
for(intii=0;ii<8;ii++){
//wait
}
}
33

T0IE=0;
}

for(inti=0;i<30000;i++){
//wait
}
}

voidscan(void){


for(inti=0;i<30000;i++){
//wait
}

if(SensorIn1==0){
turn(1);
move();
}elseif(SensorIn2==0){
move();
}elseif(SensorIn3==0){
turn(0);
move();
}else{
turn(0);
turn(0);
34
move();
}

EMBEDDEDMICROCONTROLLERS
ProjectNameCARnage

FinalReport

Submittedto
TheFacultyofOperationCatapultLXXXVIII
RoseHulmanInstituteofTechnology
TerreHaute,Indiana

35
By
Group4

SamuelBuercklin RobinsonHighSchool
Robinson,Illinois
BenGaddy PlainfieldHighSchool
Plainfield,Indiana
RayMontgomery TerreHauteSouthVigoHighSchool
TerreHaute,Indiana

July26,2010

Introduction

Embeddedmicrocontrollersareveryusefuldevicesimplementedinmanyformsofmodern
technology.Microcontrollerssmall,programmablecomputersusedtocontrollargerelectronicpieces
ofequipmenthavenearlyendlesscapabilities.Rangingfromcontrollingasimplerobotsrotating
motiontotheselfguidedsteeringofafullsizedvehicle,microcontrollersbecomeveryusefulin
36
remotelycontrollingdevices.Thisprojectservedasaveryeducationalserviceinlearningabout
microcontrollersandhowtheywork.

ComparisonofMicrocontrollerstoComputers

Theadvantageofmicrocontrollersoverfullsizedcomputersisgroundedheavilyinthesize
factor:amicrocontrollercanbestoredinasmallarea,yetstillcontrolthecomponentsarounditto
performaspecifictask.FullsizedcomputerscannotfitintoanLEDsignorachildrensgame.
Microcontrollers,however,servethepurposeofcontrollingaspecific,dedicatedcircuitwellwhilestill
maintainingthephysicalconstraintsofthecontainer.
Computershavesuperiorhardwareandflexibilityintermsofuse.Acomputercanbeusedto
typeareport,switchovertoanentertainmentcenter,andthenbeusedtochecktheweatherforthe
nextdayallwithinanhour.Thehardwareisbuiltwiththiswidevarietyoftasksinmind,andmultiple
programscanberunonthesamemachine.
Microcontrollers,bycomparison,arededicatedtoonepurpose.Amicrocontrollercanperform
simplearithmeticinapocketcalculator,oritcanscrollthesalesofthedayforasandwichbusinessto
thepublic.Themicrocontrollercannot,however,performbothactionswithoutbeingtakenapart,
reprogrammed,andoutfittedwithitsnewperipherals.Withouttheversatilityofadesktoporlaptop
computer,themicrocontrollerperformssingulartaskswithnoeasyalternatives.Theremovalof
versatilitycutsdownonsize,andmakesthemveryefficienttouseforadedicatedpurpose.
Inessence,computersareinteractedwithbytheworld,whileamicrocontrollerisusedto
interactwiththeworld.Computersareintendedforuseastoolstocompleteothertasksthatahuman
cannotefficientlyorfeasiblydoonitsown.Amicrocontrollercompensatesforthesimplicityofits
purposebyperformingitsactionsquickly,simply,andwithoutaproblemcomplicatedbythe
complexitiesofcomputers.

37

SpecificUsesofMicrocontrollers

Asstatedpreviously,microcontrollerscanonlybeutilizedforonededicatedtask.However,this
doesnotrequirethetaskbesimple.Amicrocontrollercantellavehicletoparkitself;obviouslya
difficulttaskforevenalargecomputer.Itcouldalsobeusedinamissilesremotetrackingsystemto
propelittoanothercountryandtargetaspecificareathousandsofmilesaway.Theuses,whilelimited
withinasingledevice,arelimitlesstotheprogrammerofthedevice.
Duetotheverysmallsizeofamicrocontroller,itcanbeimplementedeffectivelywherelarger
piecesofequipmentcannotbeused.Forexample,ifoneweretobebuildingadevicethathadto
performthetaskofgeneratingacomplexfunctionintheformofagraphonanLCDscreen,butneeded
tofitinthebackpocketofacollegestudent,onewouldrequireacomputersmallenoughtofitinside.
Microcontrollerscouldbeused,forwhiletheycannotdoanythingmorethangeneratesaidgraph,they
canperformthattaskinanefficientmanner,whileretainingthesmallsizeofthedevice.

ProjectIdeas

Whenbeginningtogeneratedesignsforthemicrocontrollerproject,ourgroupwasabletostray
frompopulardesignchoices,makingtheprojectsmallerandmorecompactthanexpected.Duetothe
microcontrollersunusuallysmallsize,wewereabletodothis.Thegroupsabilitytostrayfrompopular
beliefsfordesignconstraintsmadeitpossibletoproduceafinalproductthatisoverallmore
aestheticallypleasingthanonewouldexpectinacarthathascapabilitiestobecomeautonomous.
Whenthegroupwaspresentedwiththeproblemofcreatingapieceoftechnologydrivenbya
microcontroller,whichmeantcompletelyhandsfreefromtheuser,theideaofaremotelyoperated
vehiclecametomind.Theideathatonecouldoperatearemotecontrolledvehicleuntilsomething
interrupteditspath,causingittobecomeautonomousanddriveitselfusingthemicrocontroller,
soundedfascinating.
38
Oneideathathadbeendonebeforewasaturretmountedonaslightlymobilevehicle.The
vehicledidnotappeartobehumancontrolledhowever,whichseemedlikealargedrawbackindesign.
Thus,ourvehiclewouldhavetobecapableofmovingfreely,oratleastbetterthantheturretwehad
seenbefore.
OurfinalideasculminatedintheideaofCARnage.CARnagewouldbeacarcapableofhuman
controlwithrelativefreedom,untilanobjectwascloseenough.Thenthevehiclewouldfireaprojectile
attheobject,andasanaddedfeatureuniquetoCARnage,itwouldramthetargetandthenreturn
controltotheuser.

Design

Whendesigningthisuniquepieceofequipment,simplytakingonthetaskfromscratchseemed
toodauntingforourgrouptotackleinatimeperiodasshortasthetwoandahalfweeksweweregiven
tocompletetheproject.Asanalternativetosimplybuildingfromthegroundup,ourgroupdecidedto
utilizeprebuiltparts,thoseofwhichhaddesignsalreadyunderstoodbythegroupandtherefore
unnecessarytoreplicateratherthanpurchase.WesettledonanR/Ccarwhichwascontrolledviaa
remotewithantenna,andamotorpowereddisklauncher.
First,theR/Ccarwasstrippeddowntoasimpleplasticmoldedbase,aremotecontrolled
circuitboard,andtwoaxelswithwheels.Theshellofthecarwasputasidetobelaterutilizedbythe
groupforaestheticpurposes.Next,thegroupmovedontothedisklauncher,disassemblingthatdevice
aswell,andinstallinganew,higheroutputmotorandmodifyingmovingpartsinthedevicetoimprove
stability.Also,thehandlecontainingthemechanicalswitchonthedevicewasrippedoutandreplaced
withaservo,whichwouldlaterbecontrolledelectronicallyviathemicrocontroller.
Oncethebaseoftheprojecthadbeendisassembledandreassembledaccordingtoourdesign
specifications,ourgroupbegantoprogramthemicrocontroller.Whendoingso,wemadesurethatall
39
ofthebatteries,sensors,wires,andotherexternaldevicesneededcouldbeeasilyhousedwithinthe
shellofthecar,makingamuchmorecompactandnicerlookingdevice.

Hardware

Ourdesigncalledformultipleeasytolocatepiecesthatallservedanimportantroleinthe
completionofourproject.ForemostistheMicrochipPICboard,morespecificallyaPIC16F87XA.The
carisaremotecontrol,1:16scalecarwepulledthechassisoutofandmodifiedbyreroutingthepinson
theremotereceiver.TofindthedistanceweuseaPing)))ultrasonicsensor.Wepurchasedadisk
shooterthroughtheinternetthathasamechanicalswitchtomoveadiskontoamotorthataccelerates
thedisk.Toreplacethemechanicalswitchweattachedaservomotortothegunthatwouldpressthe
switchforusautomatically.Weusedamotorcontrollertoshiftcontrolbetweenboththeregularmotor
onthecarandtheservoonthediskshooter.


CircuitSchematic
40
Programming

Themicrocontrollerweusedforthisprojectwasdistributedwithprogramminglibrariesandan
IDEfortheCprogramminglanguage.Cisalowerlevellanguagethanmanyprogramminglanguages
availabletoday,meaningthesyntaxofitisnotveryuserfriendlyandsomeextramemorymanagement
maybenecessary.Thesetradeoffs,however,arenotdonewithoutabenefit.Becauseofthenatureof
CcomparedtoC++orJava,Cisaveryefficientlanguagewithlessexcesscodegeneratedthatwould
wasteclockcyclesontheminimalprocessorthemicrocontrollerhas.
Ourprogramrunsthroughthemainmethod,whichinitializesallofthecomponentsandenters
intoanendlessloopthatexecutesthebodyoftheprogram.Theloopcallsasubroutinethatsignalsthe
ultrasonicsensortofindthedistancetowhateverisinfrontofit.Ifthedistanceisunderacertain
threshold,anothersubroutineiscalledfromthemainmethod.
ThisnextsubroutineswitchescontroltothePICboardfromtheuser,lockingouttheusers
remote.Aseparatemethodiscalledagaintofirethediskshooter,duetothecomplexityoftheservo
motor.Multiplepulsewidthsareusedtopositiontheservomotorintwodifferentpositions,withthe
subroutinetorepositiontheservousingasingleargumentthatdeterminesthepulsewidth.
Afterfiringthediskshooter,theprogramsetsthecarmotortorununtiloneoftwothings
happens.Eitherthetimersettostopthemotorreachesitsendorthepininterruptiscalled.Ineither
case,thereversesubroutineiscalled,whichsimplydrivesthecarbackwardsadistancesotheusercan
safelycontrolthecaragainwithoutitenteringintoanotherroundofdiskshooter.
Oncethecarhasbackedupadistanceandreturnedcontroltotheuser,theloopinthemain
methodisenteredintoagain.Thisloopisthecycleofourprogram,withallinitializationoccurring
beforetheloop.

ProgramFlowChart



41

FinalProduct

Theresultsoftheprojectsignificantlyvaryfromwhatourgroupinitiallyplanned.Theprogram
hadbugswhichneededconstantfixing,andavastnumberofpartshadeitherbrokenorfailedtoserve
theirpurpose.Also,majordesignchangesneededtobemade.However,thefinalproduct,while
differentfromthegroupsexpectations,wasgreatlysuccessful.
ThecarisabletobecontrolledbyanR/Ccontroller,andonceitseesanobject,correctlyenters
asubroutineinitsprogramwhichcausesittoshootaprojectileandmoveforwardtowardthetarget.
Problemswiththepushbuttonmountedtothefrontofthecarpersisted,buttheprojectasawhole
remainedasuccess.


FutureApplications

Whilemicrocontrollerswillmostlikelyneverbeasversatileasfullsizedcomputers,theycanstill
beusedtooperateadedicatedprogramwithmoreconvenienceinthesenseofsizeandoperating
powerthananyotherdevice.Forthisreason,microcontrollershavethecapabilitytobeutilizedinmany
futurepiecesoftechnology.Wherecomputersaretoolargeandclunkytobeimplemented,
microcontrollerswilltaketheirplace.Whethertheobjectbeingcontrolledisassmallandsomewhat
unimportantasachildrenstoy,toanairforcedronecapableofendingawar,microcontrollerswill
serveadedicatedpurpose.

42
Code

//Operation Catapult, Session 2, 2010


//Embedded Microcontrollers, Group 4, CARnage
//Written by: Sam Buercklin, Ben Gaddy, and Raymond Montgomery
//Date started: July 15, 2010
//Date Finished:

//RC Car and mounted disc shooter
//Car is remote controlled, until an ultrasonic sensor detects a target within a range threshold
//After detecting a target, it will override user control doing:
//Firing the gun, ramming the target until it trips a pushbutton sensor, and then turn around
//After turning around, the user takes control again and it reverts to searching for a new target

#include <pic.h>

#if defined(_16F84)
__CONFIG(HS & WDTDIS & PWRTEN & MPEDIS);
#endif
#if defined (_16F877) || defined (_16F877A)
__CONFIG(HS & WDTDIS & PWRTEN & LVPDIS);
#endif

#define driveForward RD2
#define driveReverse RD3
#define enableMovement RD4
#define activateMotorPIC RA3
#define servoMotor RD6

#define ServoControlPin RD6
#define ServoControlPinDirection TRISC2

// interrupt duration
43
#define INITIAL_COUNT 200 // 128 microseconds per interrupt at 8MHz
// pulse width to control rotation of a motor
#define Neutral 35 // 1.5ms
#define ZeroDegree 25 //1.1ms or less
#define Degree180 70 // 2.3 ms, 1.75ms or more
//#define Degree30 40
// pulse period
#define PULSE_PERIOD 400 //11.5ms period
#define upperbound 500
#define lowerbound 200

unsigned int period, pulsewidth, PULSELENGTH;

unsigned char reversed;

void interrupt hit(void);
void GoAutomatic(void);
unsigned int GetDistance(void);
void Reverse(void); //in case the pushbutton isn't pressed.
void DelayTime(unsigned int);
void Timer0_Initialization(void);
void MoveServo(unsigned int moveWidth);
void FireGun(void);

void main(void)
{
unsigned long int a;
MoveServo(20);
Timer0_Initialization();
ADCON1=0b00000110;
TRISA = 0b00000000;
TRISD = 0b00000000;
activateMotorPIC = 1; //1 is off, 0 is on
driveForward = 0;
44
driveReverse = 0;
TRISB = 0b00010000;
enableMovement = 1;
RBIF = 0;
INTCON = 0b10001000;
for (;;)
{
a = GetDistance();
if (a < 45)
{
GoAutomatic();
}
}
}

void interrupt hit()
{

if(T0IF==1) { // interrupt internal is
if (period!=0) period = period --;
else {
period = PULSE_PERIOD; //initialize period
pulsewidth=PULSELENGTH; //initialize pulse
ServoControlPin=1; //start pulse
}
if (pulsewidth!=0) pulsewidth--;
else ServoControlPin=0; //end pulse
TMR0=INITIAL_COUNT;
T0IF=0;
}
}

void GoAutomatic()
{
45
reversed = 0;
activateMotorPIC = 0;
DelayTime(200);
FireGun();
FireGun();
DelayTime(200);
driveReverse = 0;
driveForward = 1;
DelayTime(165);
if (reversed==0)
Reverse();
}

void Reverse()
{
driveForward = 0;
driveReverse = 0;
DelayTime(525);
driveReverse = 1;
driveForward = 0;
DelayTime(185);
driveReverse = 0;
activateMotorPIC = 1;
reversed = 1;
}

void MoveServo(unsigned int moveWidth)
{
unsigned int Voltage;
ServoControlPinDirection = 0; //Servo Control Pin is output
Timer0_Initialization();
period = PULSE_PERIOD;
ServoControlPin=1;
PULSELENGTH = moveWidth;
46
}

void Timer0_Initialization(void) {

T0CS = 0;
PSA=0;
PS2=0;
PS1=0;
PS0=0;

T0IF=0;
T0IE=1;
TMR0=INITIAL_COUNT; // interrupt occurs every 10 microseconds
GIE = 1; // turn on global interrupt flag
}

void FireGun(void)
{
MoveServo(0);
DelayTime(100);
MoveServo(20);
DelayTime(100);
MoveServo(0);
}

void DelayTime(unsigned int count)
{
unsigned int a;
for (a = 0; a < (count * count); a++);
}
#define TriggerAndEchoPin RC2
#define PinDirection TRISC2 //needs to be switched from input to output, etc.
#define TenMicroSecond 50
#define TenMilliSecond 200
47
#define Frequency 20
#define SpeedOfSound 35
#define Timer1ClockPeriod 0.2

unsigned int GetDistance()
{
unsigned int FirstEdge, SecondEdge;
unsigned long int distance, Count; //counts of two rising edges
unsigned char Ones, Tens, Hundreds;

TMR1ON = 1; //turn on Timer 1
TMR1CS = 0; //internal clock (Fosc/4)
TRISE=0;
TRISC=0b11111011;
PinDirection = 0; //output to start sending ultrasonic sound
TRISC=0b11111011;
TriggerAndEchoPin = 0;
DelayTime(TenMicroSecond);
TriggerAndEchoPin = 1; //generate a pulse
DelayTime(TenMicroSecond); //minimum pulse width
TriggerAndEchoPin = 0; //turn off the pulse to start sending sound
PinDirection = 1; //switch to input to receive echo
TRISC=0b11111111;
CCP1IF = 0;
CCP1CON = 0b00000101; //input capture on every rising edge
//wait for rising edge
while(CCP1IF==0){}; //waiting for rising edge
FirstEdge = CCPR1H;
FirstEdge = FirstEdge<<8;
FirstEdge = FirstEdge+CCPR1L;
CCP1IF = 0;
CCP1CON = 0b00000100; //input capture on every falling edge
DelayTime(TenMicroSecond); //minimum pulse width
while(CCP1IF==0){}; //waiting for falling edge
48
SecondEdge = CCPR1H;
SecondEdge = SecondEdge<<8;
SecondEdge = SecondEdge+CCPR1L;
CCP1IF = 0;
if(FirstEdge < SecondEdge)
Count = SecondEdge-FirstEdge;
else {
Count = -FirstEdge;
Count = Count+SecondEdge;
}
distance = Count*Timer1ClockPeriod;
distance = distance >>1;
distance = distance*SpeedOfSound;
return distance = distance>>10;
}

LEDTicTacToeGame

FinalReport

Submittedto
TheFacultyofOperationCatapultLXXXVIII
RoseHulmanInstituteofTechnology
49
TerreHaute,Indiana

By
Group5

GrahamHarvey BiotechnologyHighSchool
Ocean,NewJersey
MichaelRoyappa Homeschool
Pensacola,Florida
NicholasLopezCanelas TheLatinSchoolofChicago
Chicago,Illinois

July19,2010
50
Abstract:
Tictactoeisagameusuallyplayedbytwoplayersonasheetofpaper.Theobjectofthegame
istomarkthreesquaresinarowona3x3squaregrid.Thegoalofthisprojectwastomakean
electronicLEDtictactoeboardusingmicrocontrollertechnology.AnLEDisaLightEmittingDiode,
whichisacomponentthatemitslightofaspecificwavelengthwhenforwardbiasedat10mAcurrent.
Thebasicgoalsofmicrocontrollertechnologyaretoincreaseandimproveknowledgeaboutthe
technology,andtobuildprojectsthatcanbettersenseandrespondtostimuliintheenvironment.The
LEDtictactoeboardthatiscreatedasaproductofthisprojecthashelpedtoimproveour
understandingofmicrocontrollertechnology,whiledecreasingthequantityofpaperthatweusein
playingtictactoe.
Toaccomplishtheseobjectives,ninetricolorLEDswereusedtomakethe3x3squaregrid.
ThesetricolorLEDscanemitred,green,andbluelight;however,onlyredandbluelightswereused.
Ninepushbuttonswerealsoconnected.Themicrocontrollerturnstheinputofthepushbuttonsinto
outputthroughtheLEDs.Whenoneplayerpushesabutton,thecorrespondingLEDemitsredlight.
Whenthesecondplayerpushesadifferentbutton,thecorrespondingLEDemitsbluelight.Thisarrayof
LEDscreatesatictactoeboardthatcanbeplayedbytwodifferentplayers.
51
Introduction:
Tictactoeisagameplayedbetweentwoplayersona3x3squaregrid,usuallydrawnonpaper.
Theobjectofthegameistomarkthreesquaresinarowonthegrid.Themarkscanbevertical,
horizontal,ordiagonal.Theplayerstaketurns,traditionallydrawingandXoranOastheir
respectivemarks.ThepurposeofthisprojectwastomakeanelectronicLEDtictactoeboardusing
microcontrollertechnology,whileimprovingourunderstandingofmicrocontrollertechnology.Tomake
thisboard,multiplecircuitswerebuilttobecontrolledbysoftwarethatwasprogrammedontothe
microcontroller.
AnLEDisaLightEmittingDiode,whichisacomponentthatfunctionsasadiodewhilealso
emittinglight.Adiodeonlyallowscurrenttopasswhenitisforwardbiased.AnLEDdoesthesame
function,whilealsoemittinglightofacertainwavelength.TheLEDsthatwereusedweretricolorLEDs
thatcanemitred,green,andbluelight.TheseLEDsare5mmindiameter.EachLEDhasonecommon
ground,whichgivesitfourleads.
ThemicrocontrollerthatwasusedismanufacturedbyMicrochip.ItisaPIC,orPeripheral
InterfaceController,modelnumberPIC16F877A.AnMPLABIDEwasusedtowriteandcompilethe
software,andanICD2interfacedevicewasusedtoprogramthemicrocontroller.Themicrocontroller
usesanACtoDCconvertertoprovidepower.Itsoutputishighat5V,andlowat0V.Apushbutton
beingdepressedistheinput,andtheLEDslightingupistheoutput.
Resistorsarecommonlyusedasvoltagedividerstoreducethecurrentinacircuit.Aresistor
consistsofapieceofthinwirethatistightlywoundaroundacore.Resistorsareusedinmanycircuit
applicationstoprotectthecomponentsfrombeingdestroyedbyalargercurrentthantheycanhandle.
IntheLEDtictactoeboard,resistorswereusedtoprotecttheLEDsfrombeingblownout.
Whilecreatingprojectslikethisone,itiscommontoencounterproblemsinthehardwareand
softwarethatmustbefixed.Theseproblemsarecalledbugs.Debuggingistheprocessoffindingand
fixingtheseproblems.Ittakestimetodebugaprojectcompletely.Thequantityofproblemsthatare
encountereddependsonthequalityofthework.Carelessmistakesinthesoftwareormistakesin
solderingcaneasilycauseproblemsthatmustbefixed.
Thistictactoeboardwascreatednotonlytohelpimproveourunderstandingof
microcontrollertechnology,butalsotoconservepaperandtobringanewinteractiveedgetoa
traditionalgame.Theboardisreusable,soitisnolongernecessarytowastepaperplayinggames.The
LEDsalsoofferavisualappealthatissuperiortothetraditionalXandO.

MaterialsandMethods:
ThematerialsusedwereaPIC16F877Amicrocontroller,anMPLABICD2interfacedevice,a
computerwiththeMPLABsoftwareinstalled,aperforatedboard,nine100resistors,ninetricolor
LEDs,ninenormallyopenpushbuttons,sixsixteenpinchips,wires,connectorpins,asolderingiron,
52
solder,adigitalmultimeter,asquareboxwithnotop,andanacrylictoptothewoodbox.These
materialswereallprovidedbytheRoseHulmanInstituteofTechnology.
ThetictactoeboardwasmadeusingtricoloredLEDsmountedonaperforatedcircuitboard.
Todothis,nineLEDsweresolderedtoaperforatedboard.Ninepushbuttons,whichturnedtheir
respectiveLEDeithergreenorblue,werealsosolderedtotheboard.TheseLEDsarecontrolledbythe
microcontroller.Thepushbuttonswereconnectedtothemicrocontrollerlikeakeypad,asshownin
Figure1.ThemicrocontrollerwasprogrammedtolightupthecorrectlycoloredLEDwhenthe
correspondingbuttonwaspushed:redforthefirstplayerandblueforthesecondplayer.
ThepushbuttonsandLEDswereconnectedasshowninAppendixI.EachLEDhasfourleads:
oneforred,oneforgreen,oneforblue,andoneforground.Alltheredleadswereconnectedbywires
toaninepinconnector,whichwasinturnlinkedtothemicrocontroller.Thesamewasdonewiththe
greenandbluecolors.Inaddition,ineveryrowofLEDs,thegroundpinswereconnectedtoonewire.
Therefore,therewerethreegroundwireswhichwereconnectedtothemaingroundonthePICboard.
ThecircuitdiagramsareincludedinAppendixI.TheprogramusedisincludedinAppendixII.
Thebox,madeofwood,wascutjustlargeenoughtofitthecircuitboards,5inchesx5inchesx
2.75inches.Theacrylictophadninecircularholeswithasixmillimeterdiameterandninesquareholes
cutintoitbyalasercutter.Thesquareholesweremadetofitthepushbuttonsandthecircularholes
wereforeachLED.

Figure1:KeypadDesign

RB1
SW5
SW2
SW7 SW9
RB0
SW1
SW4 SW6
SW8
RB5
RB6
RB2
SW3
RB4
53
UsersGuide:
Theboardmustbepluggedintoanoutlettouseit.Playeroneisautomaticallyassignedthe
colorredforhisorherLEDs.Playertwoisassignedthecolorblue.Theplayerstaketurnsselectingan
LEDtolightupandpressingitscorrespondingpushbutton.Theobjectofthegameistogetthreelights
ofthesamecolorinarow.Thislineoflightscanbeahorizontal,verticalordiagonalline.Onceaplayer
getsthreeinarow,oralltheLEDsarelitwithoutoneplayergettingthreeinarow,theplayersmay
choosetoresettheboardtoplayagain.

Results:
TheLEDTicTacToeGamewastestedasitwasbuilt.Theresultsoftheinitialtestingshowed
thatthegamedidnotworkasexpected.DifferentLEDsturnedoninwhatseemedlikenopattern.The
grouptriedtolookforhardwareandsoftwareproblemsintheproject.Theseproblemsweredifficultto
findandfix.ThefacultyofOperationCatapultwasofgreatassistanceinhelpingtofixtheproject.
Eventually,thehardwareandsoftwarewerecompletelydebugged.

Discussion:
ThepurposeofthisprojectwastobuildanLEDTicTacToeGamewhileimprovingour
understandingofmicrocontrollertechnology.Thispurposewasaccomplishedsuccessfully.Theinitial
testingshowedthattherewerehardwareandsoftwareproblems.Alloftheseproblemswere
eventuallyresolved.Thegrouplearnedagreatdealaboutdigitalelectronicsandmicrocontroller
technology.
Asstatedpreviously,variousproblemswereencounteredwhiletryingtobuildaworkingtictac
toegame.Theshortcircuits,coldjoints,andotherhardwareproblemscausedmanyofourdifficulties.
Ashortcircuitoccurswhentwoelectricalconductorsaretouchingwhentheyshouldnotbetouching.
Thisallowscurrenttoflowthroughtheminawaythatisnotintended,changingtheoutputtobe
somethingotherthanwhatwasexpected.Acoldjointoccurswhenajointbetweentwoelectrical
conductorsissoldered,butthesoldereithersolidifiesbeforeagoodconnectionisformedoritbreaks
offofoneoftheconductors.
Anotherhardwareproblemthatwasencounteredwasafaultypushbutton.Thepushbuttons
usedhadbeenrecycledfromearlierprojects,andoneofthemwasnotworkingcorrectly.This
pushbuttoncausedashortcircuitinthekeypad(Figure1),changingtheoutputofmostofthe
pushbuttons.Afterthispushbuttonwasidentifiedasfaultyandreplaced,allofthepushbuttonsworked
properly.
54
Onceallofthehardwarewasbuiltandfixed,thesoftwareneededtobewrittenanddebugged.
Theprofessorprovidedtheoriginalprogram.Itwouldshowifeachpushbuttonwouldlightupthe
correctLED,butitwouldnotmakeagameoftictactoepossible.Theprogramhadtobemodifiedto
sendthesignaltothecorrectleadofeachLEDwhenaspecificpushbuttonwaspressed.
Asagroup,welearnedhowdifficultitistosuccessfullydesignandbuildausableprojectusinga
microcontroller,duetohardwareandsoftwareproblems.Ittakestimetoidentifytheissuesanddebug
thehardwareandsoftwaresotheycanworktogetherinaproject.Wealsolearnedtheimportanceof
workingwithateamtogetajobdone.Itisnecessarytoworkinateamtoexpectresultswithina
certainperiodoftime.Itisalsomucheasiertoworkwithateamwhenallideasarepresentedand
discussedtruthfully,insteadofnotdiscussingtheideas.Thegroupmustalsogetalongandbeableto
worktogether.
Toimprovethisprojectinthefuture,anewLEDtictactoegamecouldbecreatedwithmore
LEDs.TheLEDscouldbeprogrammedtoturnonmultiplecolorsatonce,makingmorecolorspossible.
Additionally,anLCDscreencouldbeaddedtotheprojecttodisplayvariousmessages,suchasthe
winnerofthegameoftictactoeorthescorebetweentwoplayers.Also,withmoreLEDs,itwouldbe
possibletoprogrammoregamesontothemicrocontroller,suchasConnectFourorcheckers.Thiscould
bedonebyaddingtothesoftware.Theplayerswouldthenbeabletochoosebetweengamesviathe
LCDscreen.TheseimprovementswouldgreatlyenhancethisLEDgame.
55
AppendixI
G
R3
100 Ohm
B
R9
100 Ohm
R4
100 Ohm
R7
100 Ohm
R1
100 Ohm
LED4
R
R6
100 Ohm
R
R
LED1 LED2
B
J 1
SIPSOC-10
1
2
3
4
5
6
7
8
9 G
R
B
R2
100 Ohm
B
G
LED6
G
R R
B
G
R5
100 Ohm
G
R8
100 Ohm
R
LED7
R
LED5
J 2
SIPSOC-10
123456789
B
LED8
G
G
R
Bl ue Pi ns
B
B
Gr een
Pi ns
LED3
J 3
SIPSOC-10
1
2
3
4
5
6
7
8
9
LED9
B
Red Pi ns
G

Figure2:LEDschematic
56
RC3
( SCLK)
U4
74HC595
9
1
0
1
3
1
4
1
1
1
2
1
5
1234567
8
16
S
D
O
C
L
R
G S
D
I
S
R
C
L
K
R
C
L
K
Q
A
Q
B
Q
C
Q
D
Q
E
Q
F
Q
G
Q
H
GND
5V
J 4
Blue Connector
1 2 3 4 5 6 7 8 9
5V
U4
74HC595
9
1
0
1
3
1
4
1
1
1
2
1
5
1234567
8
16
S
D
O
C
L
R
G S
D
I
S
R
C
L
K
R
C
L
K
Q
A
Q
B
Q
C
Q
D
Q
E
Q
F
Q
G
Q
H
GND
5V
5V
RC5
( SDO)
RD3
5V
5V

Figure3:Blueconnectorschematic
5V
J 4
Green Connector
1 2 3 4 5 6 7 8 9
RC5
( SDO)
U4
74HC595
9
1
0
1
3
1
4
1
1
1
2
1
5
1234567
8
16
S
D
O
C
L
R
G S
D
I
S
R
C
L
K
R
C
L
K
Q
A
Q
B
Q
C
Q
D
Q
E
Q
F
Q
G
Q
H
GND
5V
RD4
5V
5V
5V
RC3
( SCLK)
U4
74HC595
9
1
0
1
3
1
4
1
1
1
2
1
5
1234567
8
16
S
D
O
C
L
R
G S
D
I
S
R
C
L
K
R
C
L
K
Q
A
Q
B
Q
C
Q
D
Q
E
Q
F
Q
G
Q
H
GND
5V

57
Figure4:Greenconnectorschematic
J 4
Red Connector
1 2 3 4 5 6 7 8 9
RC5
( SDO)
U4
74HC595
9
1
0
1
3
1
4
1
1
1
2
1
5
1234567
8
16
S
D
O
C
L
R
G S
D
I
S
R
C
L
K
R
C
L
K
Q
A
Q
B
Q
C
Q
D
Q
E
Q
F
Q
G
Q
H
GND
5V
RD2
5V
U4
74HC595
9
1
0
1
3
1
4
1
1
1
2
1
5
1234567
8
16
S
D
O
C
L
R
G S
D
I
S
R
C
L
K
R
C
L
K
Q
A
Q
B
Q
C
Q
D
Q
E
Q
F
Q
G
Q
H
GND
5V
5V
5V
RC3
( SCLK)
5V

Figure5:Redconnectorschematic
RB6
SW7
RB0
SW6 SW4 SW5
RB5
SW9 SW8
RB1
RB4
SW1
RB2
SW2 SW3

Figure6:KeypadSchematic
58
59
AppendixII

/******************************************************************
*DESCRIPTION:SPIexampleforPIC16F887A
*for74HC164and74HC5958bitserialinparalleloutputshiftregister
*SerialDataOut(SDO)=RC5
*StorageRegisterClock=RC0 //for74HC595
*SerialClock(SCK)=RC3
*SOURCE:LEDTicTacToe.c
*Date:July21,2010
*AUTHOR:MichaelRoyappaandJianJianSong
******************************************************************/
#include<pic.h>

#ifdefined(_16F877A)
__CONFIG(HS&WDTDIS&PWRTEN&LVPDIS);
#endif
#defineUpdateRedRD2
#defineUpdateRedDirectionTRISD2=0
#defineUpdateBlueRD3
#defineUpdateBlueDirectionTRISD3=0
#defineUpdateGreenRD4
#defineUpdateGreenDirectionTRISD4=0
#defineKeypadPORTB
#defineKeypadDirectionTRISB=0b01110000
60

voidInitialize_SPI(void);
voidinterruptwave_generator(void);
voidsquarewave_initialization(void);
voidsquarewave(void);
voidTurnOffAll(void);
voidTurnOnAll(void);
voidinterruptServiceInterrupts(void);
voidKeyPadInitialization(void);
unsignedcharScanKeyPad(void);
voidCheckLEDs(void);
voidDelayTime(unsignedintcount);
voidUpdateLEDs(void);

#defineDelayCount500
constunsignedcharDisplaySingleLED[10][2]={{0b00000000,0b00000000},
{0b00000000,0b00000001},{0b00000000,0b00000010},{0b00000000,0b00000100},
{0b00000000,0b00001000},{0b00000000,0b00010000},{0b00000000,0b01000000},
{0b00000000,0b01000000},{0b00000000,0b10000000},{0b00000001,0b00000000},
};
constunsignedintpositions[9]={0b0000000000000001,0b0000000000000010,0b0000000000000100,
0b0000000000001000,0b0000000000010000,0b0000000000100000,
0b0000000001000000,
0b0000000010000000,0b0000000100000000};
unsignedintPlayer1=0,Player2=0;
unsignedcharKeyFound; //KeyNumberfound
61

voidmain(){
unsignedchari;
unsignedcharPlayedKeys[9];

// squarewave_initialization();
UpdateRedDirection;
UpdateBlueDirection;
UpdateGreenDirection;
Initialize_SPI();
KeyPadInitialization();
TurnOffAll();
// GIE=1;//turnonglobalinterruptflag
KeyFound=0;
//CheckLEDs();
for(i=0;i<10;i++)PlayedKeys[i]=0;

for(i=0;i<10;i++){
if((i%2)==0){ //firstplayer
KeyFound=ScanKeyPad();
while((KeyFound==9)||(PlayedKeys[KeyFound]==1))
KeyFound=ScanKeyPad();
PlayedKeys[KeyFound]=1;
Player1=Player1|positions[KeyFound];
UpdateLEDs();
62
}
if((i%2)==1){ //secondplayer
KeyFound=ScanKeyPad();
while((KeyFound==9)||(PlayedKeys[KeyFound]==1))
KeyFound=ScanKeyPad();
PlayedKeys[KeyFound]=1;
Player2=Player2|positions[KeyFound];
UpdateLEDs();
}
}

while(1);
}

voidUpdateLEDs(void){
TurnOffAll();
SSPIF=0;
SSPBUF=Player1;
while(SSPIF==0){};
SSPIF=0;
SSPBUF=Player1>>8;
while(SSPIF==0){};
UpdateRed=0;
UpdateRed=1;

63
SSPIF=0;
SSPBUF=Player2;
while(SSPIF==0){};
SSPIF=0;
SSPBUF=Player2>>8;
while(SSPIF==0){};
UpdateBlue=0;
UpdateBlue=1;
}

voidTurnOffAll(void){
SSPIF=0;
SSPBUF=DisplaySingleLED[0][1];
while(SSPIF==0){};
SSPIF=0;
SSPBUF=DisplaySingleLED[0][0];
while(SSPIF==0){};
UpdateRed=0;
UpdateRed=1;
UpdateBlue=0;
UpdateBlue=1;
UpdateGreen=0;
UpdateGreen=1;
}

64
voidTurnOnAll(void){
SSPIF=0;
SSPBUF=0b11111111;
while(SSPIF==0){};
SSPIF=0;
SSPBUF=0b11111111;
while(SSPIF==0){};
UpdateRed=0;
UpdateRed=1;
UpdateBlue=0;
UpdateBlue=1;
UpdateGreen=0;
UpdateGreen=1;
}

voidInitialize_SPI(void){
CKE=1; //risingedgetriggering
CKP=0; //idlestateisalowlevel
SSPEN=1; //enableserialport
SMP=0;
//SPImastermode,clock=Fosc/4
SSPM3=0; SSPM2=0; SSPM1=1; SSPM0=0;
TRISC3=0; //RC3isclock
TRISC5=0; //RC5isdataoutput

65
} //endofinitialize_SPI()

voidinterruptwave_generator(void){
if(T0IF==1)squarewave();
if(RBIF==1){
// KeyFound=ScanKeyPad();
RBIF=0;
Keypad=0b00000000;
}
}//endofinterruptwave_generator()

voidKeyPadInitialization(void){
KeypadDirection;
RBPU=0; //PORTBpullupenabled
RBIE=1; //enableRBchangeinterrupt
RBIF=0;
Keypad=0b00000000;
}

//searchfromkey1to9
unsignedcharKeyPatterns[]={0b01100110,0b01100101,0b01100011,
0b01010110,0b01010101,0b01010011,
0b00110110,0b00110101,0b00110011};

unsignedcharScanKeyPad(void){
66
unsignedchari,ReadKeypad;
for(i=0;i<9;i++){
Keypad=KeyPatterns[i];
DelayTime(10);
ReadKeypad=Keypad;
if(ReadKeypad==KeyPatterns[i])break;
}
returni;
}
61

Photosensitive Collision Evasion System


(P.C.E.S.)
EmbeddedMicrocontrollerGroup6

FinalReport

67
Submittedto
TheFacultyofOperationCatapultLXXXVIII
RoseHulmanInstituteofTechnology
TerreHaute,Indiana

By
Group3
AdamSinger ConantHighSchool
Schaumburg,Illinois
BrandonCox GreenfieldCentralHighSchool
Greenfield,Indiana
MarkMorrison GrosseIleHighSchool
GrosseIle,Michigan

July28th,2010

68

62
Introduction
Sincetheearly20thcentury,automobilesafetyhasbeenamajorconcerntopedestrians,
governmentofficialsanddriversalike.Mostsolutionstodrivingrelatedfatalitiesandinjurieshavebeen
tofortifyvehiclesandrequiredrivingcertification.Onlyrecently,however,hasatechnologysurfacedto
permanentlysolvetheissue:autonomousmotion.Autonomousmotiontakesdrivingoutofthehandsof
peopleandgivesittorobots.Robotsarenotcapableofdoinganythingbutwhattheyreprogrammedto
do,anddonottireormakeotherhumanmistakes,soeyestrain,fatigue,intoxication,andother
distractionscanbecompletelyeliminated.
Withinthepast10years,therehasbeenamassivedrivetotheadvanceofautonomousmotion.
TheDefenseAdvancedResearchProjectsAgency(D.A.R.P.A.)hasbeenamajorcontributortothispush,
foundingautonomousmotioncontestssuchastheD.A.R.P.A.GrandChallenge,whichchallengespeople
tocreateautonomousmotionvehiclesthatcansafelytravelinurbanandoffroadenvironments.Some
entriestotheD.A.R.P.A.GrandChallengeentrieshaveusedtechnologiesrangingfrom3Dimagingwith
GPS,tolasers,toradar.TheP.C.E.S.,however,usesinfraredsensorstodetectandavoidobjects.

UserGuide
TheoperationoftheP.C.E.S.requiresverylittleinitialinput.Toturniton,simplyplugthe
batterypackintothebatterypackinputonthebodyoftheP.C.E.S.Oncepowerisapplied,theP.C.E.S.
willmoveforwarduntilanobjectisdetectedbyoneoftheinfraredsensors,atwhichpointitwillchange
itsdirectiontoavoidthatobject.Toturnitoff,unplugthebatterypack.

Design
Initially,manyideasfloatedaroundastowhatwouldbethe2.5weekintensiveproject.They
rangedfromautosentries,tospinningaxes,toselfparkingcars.However,theautonomouscarideawas
sparkedbyacombinationofseeingthebodyofapreviousprojectwithasimilarpurpose,andanonline
videoofanautonomouscarracingthroughaforest.Whilethevideoprovidedfuelforthefirethatisthe
P.C.E.S.,thepreviousprojectprovidedageneraldesign.Theprojectusedacenteredservoaxisin
69
roughlythesamespotasintheP.C.E.S.,andgavebirthtotheideaforusingaswivelchair'swheelsfor
stabilityasopposedtoanotherservo,thusdecreasingtheoverallcostoftheproject.

Hardware
Initially,ahandmadewoodenbodyandwoodenbracketswerecreated.However,duetoa
generallackofpriorexperiencewithwoodworkingandcraftsmanship,thebodyandbracketscracked
whenscrewswereturnedin.Toimprovetheoverallqualityofthebody,multiviewdrawingswere
createdthatpreciselyshowedthedimensionsofthebodyandbracket.Thedrawingwasgiventoa
technician,whothencutoutandconstructedthefigureswithexcellentprecision.
ThebodyoftheP.C.E.S.consistedofeightparts:thebase,twoservobrackets,twoswivelwheel
mountsandthethreeinfraredsensormounts.Thebaseisasolid,hexagonalpieceof10x11x0.5acrylic
with26threadedholesinit:10fortheswivel
63
wheels,4fortheservobrackets,2fortheLEDs,4forthePICboardand6fortheinfraredsensor
mounts.
Initially,therewasadebatebetweenusingaservoandusingastandardDCmotor.The
argumentforusingaDCmotorwasthattheyweremuchsimplertohookup,astheyonlyneeded
groundandVccpinstooperate,andcouldhavegearsattachedtoslowdownorspeedupthemotor.
However,theservoswereeventuallyselectedforbeingreversiblewithoutchangingpinoutput,aswell
asgreatercontroloverspeed.After
selection,theservoswerescrewedintoUshapedpiecesofacrylic,whichwerescrewedintothebase.
However,sincetheaxelsoftheservosarentcentered,theservobracketshadtobeoffsettoputthe
axelatthecenterofthebase.
Tokeepbalance,2nonmotorizedwheelsfromswivelchairsweretightlypushedintoa1x1x1
woodenmount,whichwasscrewedintothebase.Thepurposeofthemountwastokeeptheswivel
wheelslevelwiththeservowheels.
TheinfraredsensorsarepotentiallythemostcrucialcomponentsoftheP.C.E.S.Eachsensor
consistsofaninfraredsenderandaninfraredreceiver.Thesenderconsistentlysendsinfraredlightthat
reachesuptothreefeet.Whenanobjectiswithinthisrange,thelightreflectsoffoftheobjecttothe
infraredreceiver.Thedistancefromtheobjecttothereceiveriscalculatedbythedelaybetween
sendingandreceivingtheinfraredlight.

Circuitry
70
Astheprojectproceeded,itwasnecessarytocontinuetosoldermoreandmorecomponentsto
thecircuitboardinordertoallowthesoftwaretobetterinterfacewithphysicalcomponents.Initially,all
ourconnectionsweremadedirectlytotheprogrammablecircuitboard,butsinceitisimpossibleto
soldertothisboard,weeventuallybegansolderingtoaconnecteddaughterboard.Wecouldplugand
unplugthisdaughterboardfreelyfromthemaincircuitboard,andasithadnocircuitryinitiallyonit,we
couldtestvariouscomponentsveryeasily.
Thefirstadditionwemadewasthatofavoltageregulatorandtheconnectionofaplugfora
batterytoplugdirectlyinto.Theplugwasnecessarytosupplypowertothedaughterboard,butthis
powerwasattoohighofavoltagefortherestofthecomponents.Whileitislikelythecomponents
couldhavewithstoodthisextravoltage,itwouldhavegreatlyshortenedtheirlife,andwecouldhave
hadsomecomponentsdestroythemselvesonthespot.Tosolvethisproblemweusedavoltage
regulatorcircuit,whichbroughtallthevoltageontheboardtosixvolts,whichwasacceptableforallthe
components.Whilethemainboardhadavoltageregulatoraswell,itwasinsufficienttosupplyboththe
motorsatonce.However,welaterlearnedthattheplugwasunnecessary,aswecouldconnecttothe
mainboardandbypassitsvoltageregulatortouseoursinstead.
Afterthevoltageregulator,wesolderedinthemotorconnections.Thiswasrelativelyeasy,as
theywerejustafewpinsthathadtobeconnectedtotheboard,sothattheservomotorscouldbe
pluggedinandunpluggedfreely.Atthesametime,wesolderedinthreeconnectionsfortheinfrared
sensors.Thesewereclampsdesignedforopenwires.Wewereinstructedbythelabassistantstouse
theseconnectors.However,aftercompletingthissolderingprocess,wewereinformedthattherewere
nomoreofthe
64
connectorswehadbeeninstructedtouse,sowerehadtogobackandsolderinsomepins,aswellas
usingelectricaltapetoconnecttheseabnormalconnectorstotheinfraredsensors.
Theboardwasnotmodifiedforafairamountoftimeafterthis,untilwedecidedtoputonLEDs
forlightingeffects.Thiswasverysimple,withmostoftheconnectionsalreadymade.Wesolderedon
tworesistorsandeightpins,butsincewecoulduseacompletelydifferentportforthesepins,the
processwasverysimpleandveryfast.
Therewerenotmanymajorissuesencounteredontheproject,althoughthememberworking
onthecircuitboardchangedfairlyearlyon.Therewereseveralcasesofsolderseepingthroughthe
holesinthecircuitboardaroundwirestotheothersideoftheboard,duetowhatseemstobeavery
smalldiameteronthecircuitboardsholes.Therewerealsoafewinstancesofbeingburnedduetoheat
transferthroughwires.

Software
71
Thefirststepinprogrammingthemicrocontrollertodrivethevehiclewastogettheservo
motorsturningusingcodeinsteadofafunctiongenerator.Servosrequireasquarewavetorun,andthis
squarewavedetermineswhichdirectionitturns.Severalsampleprogramsandservotestprograms
weretriedbeforeonewasfoundthatgeneratedtheappropriatewave.Evenafterwehadaprogram
thatdrovetheservo,muchtimewasspentoptimizingittorunsmoothlywithoutstoppingorjerking.
Afteroneservowasrunningsmoothly,connectingthesecondandhavingthemdrivetogether
shouldhavebeenquitesimple,butwedidnotforeseesomeproblems.Whenweattachedthesecond
servo,thefirststoppedworking.Forsomereason,wecouldnotindividuallydefinetwopinsonthe
sameportatthesametime,sowefirstputanegligiblepauseinbetween,butlaterlearnedthatwe
couldsettheentireportatonce.
Oncetheservoswerefinallyworking,wecouldstartlookingforinputfromtheinfraredsensors.
First,thedistancefromthesensorwascalculatedfromthevoltagethatthesensorreturned.Some
difficultieswereexperiencedwiththevariablewatcherinthedebugger,soinsteadofcheckingtoseeif
thedistancewascorrect,wejustusedthedistancetocontrolthepulsewidthofourtwosquarewaves,
andineffect,thedirectionofthetwoservos.Afairlylargeamountoftimewasspentlearningaboutthe
sensorsandmicrocontrollerandcalibratingthedistancesversusdirectionoftheservos.
Oncethefirstsensorwasworking,itwasfairlysimpletoconnecttheothertwo.Intheprogram,
wefoundthesensorthatwasclosesttoanobject,andthenturnedawayfromthatside.Dependingon
howcloseitis,itwilleitherstoponewheelorturnitbackwardstoturnevensharper.Afterallthree
sensorswerefunctional,wedecidedtoaddalittlemoreintelligencetowhereitturned.Insteadofjust
turningleftwhenthefrontwasclosest,itwouldturnawayfromthesidethatwassecondclosest.Ifit
wascomingtowardanobjectonanangle,itwouldturnawayfromit,insteadofturningalltheway
aroundbeforegettingaroundit.
Later,wedecidedtoaddLEDstothevehicletomakeitlookalittlemorespectacular.Turning
theLEDsonandoffwasverysimple,sowegotmulticoloredonesandchangedthecolordependingon
whichdirectionthevehiclewasturning.Todothis,wesimplychangedthecolorsatthesametimewe
changedthedirectionoftheservos.

65
Testing

Part1.) Thefirsttestsconsistedofgettingtheservostowork.Thiswasextremelydifficult,sincewedid
notknowwhatpulsewidththeservooperatedat.Extensiveresearchwasdoneonthepartnumberfor
aweekuntiltheexactpulsewidthwasfound.Then,thepulsewidthforreversingtheservowasfound.

72
Part2.) Onceaworkingservowasconnectedtothemicrocontroller,anadditionalservowasconnected
intandem.Weexperimentedwithgettingthesetwoservosworkingsimultaneouslyforaconsiderable
amountoftime.

Part3.)Thenextstepwastogetoneoftheinfraredsensorsintoaworkingstate.Usingsomecodegiven
tousbyourmentor,wemanagedtogettheinputworkinginafairamountoftime.Thenotablechange
thiscausedwasaresortingoftheportnumbers.Themotorsswitchedplugstooneport,whilethethree
sensorsswitchedtotheoriginalport.

Part4.) Thetandemservoswerethenconnectedtoasingleinfraredsensorthroughsoftware.Thecode
wasdesignedtoreversethedirectionoftheservoswheneveranobjectwentinfrontoftheinfrared
sensor.Thetestingworkedquickly.

Part5.) Withthisworkingadvancement,wecouldfinallymountthemicrocontroller,withabattery,on
thebaseforinitialtesting.Althoughitonlyhadonesensor,therobotshowedthatitwascapableof
avoidingmostobstacles.

Part6.)Nowthatwehadonefunctionalsensorandamovingrobot,wecouldproceedtoutilizationof
allthreeofthesensors.Wepredictedthiswouldgosmoothly,butwefoundthatsuchan
implementationcausedmanyconflictingsignalsfromthesensors.Whiletherobotwascapableof
avoidingobstacles,itwasveryjerkyinitspath,andthiswasveryhardonthemicrocontroller.

Part7.)Therobotwiththreesensorsrequiredsomesmoothingandoptimizationinthesoftwarebefore
itwasfullyfunctional.Thefrontalsensorwaschangedtoincorporateinputfromtheothertwosensors
beforemakingadecision,andtherapidtwitchingwasgreatlydecreased.

Part8.)ThefinalmodificationwetestedwasthatoftheLEDsweattachedtothemicrocontrollerfor
aestheticeffects.Weworkedongettingthemtochangecolorsdependentonwhichdirectionthe
vehiclewastravelingorturningin.Thisaddedsomegoodlightingtothevehicle.Theacrylicbaseand
bracketshelpedtransferthelightthroughoutthevehicletoaddaninterestingeffect.Wealsofinally
fasteneddownallthepartsofthevehicle,asthemaskingtapeweinitiallyusedbegantogiveway.

Conclusion
73
TheP.C.E.S.waseffectivelyasuccess.Itcanindefinitelyrunwithoutacollision,whichwasthe
initialgoaloftheproject.However,duetotimeconstraints,thesecondary
66
goaloftheproject,pathfollowing,wasnotreached.Itwasquicklyrealizedthatthiswasan
unreasonablegoalwithgiventime,soinsteadofattemptingtousetechnologythatwouldntget
finished,thecollisionavoidancesystemwasperfected.
Throughoperationcatapult,group06learnedalotaboutdigitalelectronics,theusefulnessof
teammatesandtechnicians,theuseofinterfacingsoftwareand,mostofall,thepowerofingenuity.

74

75

76

77

78

#include<pic.h>

#ifdefined(_16F877A)
__CONFIG(HS&WDTDIS&PWRTEN&LVPDIS&UNPROTECT);
#endif

voidinterruptinterrupt_svc_rtn();

intinterrupt_cntr,PulseWidth,PulseWidth2;
unsignedlongi=0;

unsignedintlastdirec=0,newdirec=0,pause=0;
//intcw=25,ccw=5;
unsignedintVoltage;

voidATD_initializationF(void);
voidATD_initializationR(void);
voidATD_initializationL(void);
voidGet_Voltage(unsignedint*Voltage);
unsignedlongintDistanceF=0,DistanceR=0,DistanceL=0;

voidmain(void)
{
unsignedinti;
TRISE=0b00000000;
TRISB=0b00000000;

T0CS=0;
79
PSA=0;

PS2=0;
PS1=0;
PS0=0;
TMR0=6;
T0IF=0;
T0IE=1;
GIE=1;
/*
//LED'S:
RB5=0;//Red
RB6=1;//Blue
RB7=1;//Green
//
RB1=0;//Red
RB2=1;//Blue
RB3=1;//Green
/////////////////\\\\\\\\\\\\\\
*/
//B1Red,B2Blue,B3Green,B5Red,B6Blue,B7Green

interrupt_cntr=0;

while(1)
{

ATD_initializationF();
Get_Voltage(&Voltage);
DistanceF=10*500/Voltage;

80
ATD_initializationR();
Get_Voltage(&Voltage);
DistanceR=10*500/Voltage;

ATD_initializationL();
Get_Voltage(&Voltage);
DistanceL=10*500/Voltage;
}
}

voidinterruptinterrupt_svc_rtn()
{
TMR0=6;
T0IF=0;

if(interrupt_cntr<PulseWidth){
RE0=1;
}else{
RE0=0;
}

if(interrupt_cntr<PulseWidth2){
RE1=1;
}else{
RE1=0;
}

interrupt_cntr++;
if(interrupt_cntr==200&&pause!=0)
{
interrupt_cntr=0;
81
pause;
}
elseif(interrupt_cntr==200)
{
interrupt_cntr=0;

if(DistanceF<DistanceR&&DistanceR<DistanceL)
{
if(DistanceF<45&&DistanceF>=35)
{
PulseWidth=25;
PulseWidth2=0;
RB7=1;RB6=0;RB5=0;
RB3=1;RB2=0;RB1=0;
newdirec=1;
}
elseif(DistanceF<35)
{
PulseWidth=25;
PulseWidth2=25;
RB7=1;RB6=0;RB5=0;
RB3=1;RB2=0;RB1=0;
newdirec=2;
}
else
{
PulseWidth=25;
PulseWidth2=5;
RB7=0;RB6=1;RB5=0;
RB3=0;RB2=1;RB1=0;
newdirec=3;
82
}
}
elseif(DistanceF<DistanceL&&DistanceL<DistanceR)
{
if(DistanceF<45&&DistanceF>=35)
{
PulseWidth=0;
PulseWidth2=25;
RB7=0;RB6=0;RB5=1;
RB3=0;RB2=0;RB1=1;
newdirec=4;
}
elseif(DistanceF<35)
{
PulseWidth=5;
PulseWidth2=5;
RB7=0;RB6=0;RB5=1;
RB3=0;RB2=0;RB1=1;
newdirec=5;
}
else
{
PulseWidth=25;
PulseWidth2=5;
RB7=0;RB6=1;RB5=0;
RB3=0;RB2=1;RB1=0;
newdirec=6;
}
}
elseif(DistanceR<DistanceL)//Risleast
{
83
if(DistanceR<45&&DistanceR>=35)
{
PulseWidth=25;
PulseWidth2=0;
RB7=1;RB6=0;RB5=0;
RB3=1;RB2=0;RB1=0;
newdirec=7;
}
elseif(DistanceR<35)
{
PulseWidth=25;
PulseWidth2=25;
RB7=1;RB6=0;RB5=0;
RB3=1;RB2=0;RB1=0;
newdirec=8;
}
else
{
PulseWidth=25;
PulseWidth2=5;
RB7=0;RB6=1;RB5=0;
RB3=0;RB2=1;RB1=0;
newdirec=9;
}

else//Lisleast
{
if(DistanceL<45&&DistanceL>=35)
{
84
PulseWidth=0;
PulseWidth2=5;
RB7=0;RB6=0;RB5=1;
RB3=0;RB2=0;RB1=1;
newdirec=10;
}
elseif(DistanceL<35)
{
PulseWidth=5;
PulseWidth2=5;
RB7=0;RB6=0;RB5=1;
RB3=0;RB2=0;RB1=1;
newdirec=11;
}
else
{
PulseWidth=25;
PulseWidth2=5;
RB7=0;RB6=1;RB5=0;
RB3=0;RB2=1;RB1=0;
newdirec=12;
}
}
if(newdirec!=lastdirec)pause=10;
lastdirec=newdirec;
}
}

voidATD_initializationF(void){
//initializechannelRA0
//rightjustified; Fosc/2, GNDandVDD
85

ADCS1=0;
ADCS0=0;//Fosc/2
ADON=1;//ADCisenabled
ADFM=1;//rightjustified
PCFG3=0; PCFG2=0;PCFG1=1;PCFG0=0; //RAareanalog,REdigital
CHS2=0;CHS1=0;CHS0=0; //chooseRA0
} //endATD_initialization

voidATD_initializationR(void){
//initializechannelRA0
//rightjustified; Fosc/2, GNDandVDD

ADCS1=0;
ADCS0=0;//Fosc/2
ADON=1;//ADCisenabled
ADFM=1;//rightjustified
PCFG3=0; PCFG2=0;PCFG1=1;PCFG0=0; //RAareanalog,REdigital
CHS2=0;CHS1=0;CHS0=1; //chooseRA1
} //endATD_initialization

voidATD_initializationL(void){
//initializechannelRA0
//rightjustified; Fosc/2, GNDandVDD

ADCS1=0;
ADCS0=0;//Fosc/2
ADON=1;//ADCisenabled
ADFM=1;//rightjustified
PCFG3=0; PCFG2=0;PCFG1=1;PCFG0=0; //RAareanalog,REdigital
CHS2=0;CHS1=1;CHS0=0; //chooseRA2
86
} //endATD_initialization

//getchannelnumberandreturnvoltagefromthechannel
voidGet_Voltage(unsignedint*Voltage){
ADIF=0; //willbesetatcompletion
GODONE=1;
while(GODONE==1){continue;}; //waituntilconversionisover
*Voltage=(unsignedint)ADRESH;
*Voltage=(*Voltage)<<8;
*Voltage=*Voltage+(unsignedint)ADRESL;
} //endGet_Voltage()

KensDreamHouse
TheHomewiththePerfectSecurity
EmbeddedMicrocontrollerGroupVII

FinalReport

Submittedto
TheFacultyofOperationCatapultLXXXVIII
RoseHulmanInstituteofTechnology
87
TerreHaute,Indiana

By
Group7
88

BryceAidukaitus IndianaAcademyforMath,
Science,andHumanities
Muncie,Indiana
RichiePeterson PioneerHighSchool
AnnArbor,Michigan
MichaelPordesimo QuincySeniorHighSchool
Quincy,Illinois

July28
th
,2010
89

Introduction
Peopletodayofteninstallsecuritysystemsinhomes,vaults,etc.Anythingofvaluehassome
sortofsecurityprotectingitwhetheritsthepresidentoravaultfullofmoney.Securitysystemscan
consistofaplethoraofthingssuchasinfraredsensors,flashinglamps,andburglaralarms.Security
Systemscancostanywherefrom$100$1500dependingonwhatfeaturesareinstalled.Somepopular
featuresaresmokedetectors,mastercontrolpanels,talkingdevices,andkeypads.
Peopleoftenthinkthatasecuritysystemwouldbedifficulttoassemble.Thoughseemingly
complex,securitysystemsarefairlysimpletocreate.However,somebasicknowledgewithcircuitryis
required.Securitysystemscostsomuchmainlybecauseofmonthlycostsinmaintenanceandinitial
installations.Withtherightknowledgeandtools,apersoncoulddefinitelydoallofthisbythemselves.
KensDreamHomewasdesignedtoprovethatsuchasimplesystemisfeasibleandthattheaverage
personcancreateit.Ifanyoneattemptstoenterthedownscaledhomewhilethesystemisarmed,an
alarmwillsoundandLEDswillflashtoalertoneoftheintrusion.

UsersGuide

KensDreamHomeisaverysimpledevicetouse.Thefourbuttonkeypadonthefrontofthe
housearmsanddisarmsthesystem.Thedifferentkeycombinationscannotbechangedwithout
alteringthecode.KensDreamHomecanbepoweredbypluggingthemicrocontrollerintothewallor
byplugginga9.6vbatteryintothemicrocontroller.FouroftheLightEmittingDiodes(LED)arepowered
byaseparate3vpowersource.Theothertwolightsthatindicatewhetherthesystemisarmedor
unarmedarepoweredbythemicrocontroller.Thehouseitselfismadeofposterboard.Theroofis
removablesothatthemicrocontrollerandotherinternalcomponentsareeasilyaccessible.Thealarmis
triggeredbymotionthroughthedoororwindow.IfthealarminKensDreamHomeistriggered,the
armedandunarmedlightsonthefrontofthehousewillflash.AsirenwillalsosoundandfourLEDs
mountedinthecornersofthehousewillflashrapidly.Theonlywaytoturnoffthealarmistoenterthe
disarmcodeintothekeypad.

Hardware

AlmosteverythingforKensDreamHomewascustommade.Theonlythingthatwasnotmade
wastheALEPHXP5InfraredMotionSensor.TheoriginaldesignsofKensDreamHomeincludeda
motorizeddoorandgarage.Thesefeatureswerecutfromthedesignduetotimeconstraints.Another
90

featurethatwascutwasaflashinglamp.Thisobjectwastobeincludedupuntilthefinaltesting,but
the9.6vpinonthePIC16F877Acouldnotbecontrolled.Essentiallyitwouldbeimpossibletoturnthe
flashinglampoff.
Thedesignofthehouseonlyincludes:sixLEDs,anincandescentlamp,akeypad,asimplesiren,
ALEPHXP5InfraredMotionSensor,andtworeedswitches.Allofthesecomponentsarecontrolledby
thePIC16F877A.Thehouseitselfwasconstructedfromposterboardandhotglue.Originallyadoll
housewastobebought,butthebudgetcouldnotallowforone.Thusonewasdesignedandcreated.
KensDreamHomeiswiredwiththreesensors:theALEPHXP5motionsensorandtwo
magneticreedswitches.TheALEPHXP5ispluggedintopinRB0andreceivesitspowerfroma9.6v
batterypack.ThetworeedswitchesarepluggedintopinsRD0andRD1.Thereedswitchesare
concealedabovethedoorandwindowofKensDreamHome.Iftheconnectionbetweentheswitchand
themagnetisbrokenwhilethesystemisarmed,thealarmwillsoundandtheLEDswillflash.Thesame
thingwillhappenifthemotionsensordetectsanymotion.TheALEPHXP5hasabuiltinalarmbutisnt
implementedintothesystem.
KensDreamHousecanbepoweredbya9.6vbatteryorastandard12vwalloutlet.The
PIC16F877Ahasaregulatorbuiltintoitwhichchangesanyvoltagehigherthan5vinto5v.Almostall
peripheralsofthesystemcanbepoweredbythemicrocontrollerspowersourceexceptforthefour
LEDsmountedonthecornersofthehouse.IfthefourLEDswereimplementedintothesamecircuitas
themicrocontroller,thecircuitwouldbespreadtowidelyandtheLEDswouldshinedimly.Thusthey
areconnectedtoa3vbatterypowersourceandarecontrolledbyatransistorconnectedtothe
microcontroller.A10kiloohmresistorisplacedbetweenthetransistorandmicrocontrollertoreduce
thevoltage.TheLEDsareplacedinparallelinordertoavoidtheproblemoftheLEDsreceivingan
inefficientamountofamps.Thepushbuttonsofthekeypadareinparallelthroughtheirpowersource.
Eachpushbuttonhasa330ohmresistor.

Software

ThecodeforKensDreamHousewaswritteninCandcompiledusingHITECHCCompiler.The
codewasbasedoffofanearliertutorialprojectcalledLEDFlash.Theprogramwasalteredtofitthe
needsofKensDreamHouse.Inordertoidentifywhattheprogramneededtodo,aflowchartwasfirst
created,revised,andlatermodeledforpresentation.Thefirstgoal,accordingtotheflowchart,wasto
getthemicrocontrollertoacceptinputfromthepushbuttonsandarmordisarmthesystem.The
microcontrollereventuallyacceptedtheinputfromthepushbuttons,buterrorsoftenoccurredwhen
morethanonepushbuttonwasusedforthearmandunarmedcode.Forexample,afourdigitcode
presentedsignificantlygreaterdifficultyindebugging.
91

Beforethefinalprogramcouldbeconstructed,simpleprogramswereusedtotesteach
componentofthesystem.Thefinalprogramandmostofthesimpleprogramsincludedextensiveuseof
loopsandifstatements,inordertoidentifythecorrectinputsfromkeypads,motionsensors,andreed
switches.Themainprogramrevolvedaroundcheckingtheinputsofthesysteminaninfiniteforloop.
Anotherprogramwasruneachtimethemotionsensororreedswitchesweretriggeredwhilethe
securitysystemwasarmed.ThisalarmprograminvolvedflashingLEDsandabeeping,intentionally
irritatingsiren.
Inthesoftware,themotionsensoristreatedasasimpleswitch,alongwitheveryotherinput.
Everyinputandoutputwassettofunctiondigitallyandnearlyeveryoutputdevicecanbecontrolled
throughtheprogram.
Commentswereinsertedthroughouttheprograminordertohighlightthepurposesofitskey
features.FromacomputerandtheMPLABIDE,thesoftwaremaybeprogrammedveryquicklyinto
manyPICcontrollers,allowingformassproductionofthesesimplesecuritysystems.Thefinalized
programcontainedafourdigitcodeforarminganddisarmingthesystemasopposedtoouroriginal
planforafourdigitcodeduetothealargemagnitudeofdebuggingthatwouldnotfitwithinourtime
constraints.However,theprogrammaybeexpandedtoincludelongercodesinthefuture,orata
potentialcustomersrequestinafullsizemodel.
Testing

InordertotestdifferentaspectsofKensDreamHouse,severalversionsoftheprogramwere
created.Examplesofthisareeditingthecodetocausethearmedandunarmedlightstocomeonwith
thepushofabuttonorchangingthecodesothatthemotionsensorwouldlightupanLED.Severalof
thesetestswererunbeforeKensDreamHousewascompleted.Thetestingprocessbeganwiththe
testingofthekeypadandLEDlights.Thegoalwastoconfirmthatthemicrocontrollercouldreceive
inputfromthepushbuttonsandrespondaccordinglytotheinput.Theprogramwaseditedinorderto
conductthetestand,fortunately,itwassuccessful.Thenextthingtobetestedwasthegeneralsystem
andthemotionsensor.Thispresentedthemostproblems.Themotionsensorhadbeenremovedfrom
itsoutershellandseparatedfromitsinstructionmanuallongago,makingitverydifficulttointerpret
thefunctionofeachofitsleads,ortellwhetheritcouldfunctionproperlyatall.AQuorumA160
PassiveInfraredSensorwasconsideredforuse,butrequiredseparate,unavailableradioreceiversand
computersystems.Afterthemotionsensorwasfinallyconfigured,thereedswitcheswereincorporated
intothesystem.Theoriginalcircuitrywasfoundtobeincorrectandwasrevised,whilethelackofthe
plannedsidewindowremovedthepurposeofthesecondreedswitch.
Otherpreliminarytestswererunbeforeanyactualcomponentsofthesystemwerecompleted.
Suchtestsincludedtestingdifferentcircuits,powersources,andprograms.Forexample,beforethe
flashinglampwascutfromthedesign,manydifferentpowersourcesweretestedtoseeiftheycould
supplyanadequateamountofpowerforthelamptobeoperational.A9.6vbatterywasfirstusedand
workedsuccessfully.Later,a9vpinwasdiscoveredonthemicrocontroller,whichwasalsoableto
92

supplyenoughpowerfortheflashinglamp.Asstatedbefore,theflashinglampwaslatercutfromthe
designbecausethepincouldnotbecontrolledproperlybythemicrocontrollerandavailabletransistors
eithercouldnothandlethecurrentloadorprovideddebilitatinginternalresistance.Anotherexample
ofapreliminarytestwastoseeiffourLEDscouldbepoweredbytwo1.5vbatteries.Typically,oneLED
requires1.5vtoadequatelylightup.TheLEDswouldhavebeenpoweredthroughthemicrocontroller,
buttoomuchpowerwasalreadybeingallocatedtoothercomponentsofthesystem,thusnecessitating
analternatepowersource.ThefourLEDswereabletobepoweredby3vwheninseries,butthelights
shonetoodimly.Inresponsetothis,theLEDswereplacedinparallel.Thisworkedperfectly,butdid
notcooperatewiththecircuitusedandwereremovedfromthedesign.

Conclusion

KensDreamHousewasabletofulfillallofitspurposes.Duetotimeconstraints,manyofits
featureswerecutfromthefinaldesign;howeverKensDreamHouseisstillabletoprovideadequate
security,despitemissingsomeofthesespecialfeatures.ThebasicpurposeofKensDreamHousewas
todetectanintruderandalertpeopleoftheintrusion.KensDreamHouseisabletoaccomplishthis,
andthustheprojectisasuccess.BecauseofKensDreamHouse,itwasproventhatasecuritysystem
canbemadebyanaveragepersonwithbasicknowledgeincircuitryandprogramming.Apersoncan
definitelycreateasecuritysystemthemselvesinsteadofapersoncomingintoinstallitand
maintenanceitmonthly.Overall,KensDreamHousedoesntnecessarilyhavethebestsecurity,butit
getsthejobdone.Consideringthecriminaldeterringabilitiesofmerelyasignonthedoorandaloud
alarm,KensDreamsecuritysystemwoulddefinitelypayoffbothinmonthlypaymentsandhome
security.
93

/*
Ken'sHomeSecuritySystem
July14th,2010
CreatedbyBryceAidukaitis
Thisprogramarmsanddisarmsahomesecuritysystem.Whilearmed,amotionsensorandmagnetic
doorswitchmaytriggeranalarm,whichinvolvesabuzzerandflashinglights.Arming/disarminginvolve
theuseofa4buttonkeypadmountednearthefrontdoorofthehome.
*/

#include<pic.h>

#ifdefined(_16F917)
__CONFIG(UNPROTECT&INTCLK&MCLREN&FCMDIS&WDTDIS&PWRTEN);
#endif
#ifdefined(_16F877A) //configurationbits
__CONFIG(HS&WDTDIS&PWRTEN&LVPDIS&UNPROTECT);
#endif

//DeclareVariables

#definedelay30000

unsignedintCount;

//HardwareInterfacepins
94

//Inputs

#defineMotionSensorRB0

#defineKeypadOneRA1
#defineKeypadTwoRA2
#defineKeypadThreeRA3
#defineKeypadFourRA4

#defineReedSwitchOneRD0
#defineReedSwitchTwoRD1

//Outputs

#defineDoorMotorRC0
#defineLampRB5
#defineBuzzerRC2
#defineArmedLightRE0
#defineDisarmedLightRE1

//declarefunctions
voidalarm(void);

voidmain(void)
{
95

unsignedinti,j,k;
unsignedintOrder;
unsignedintCode;

ADCON1=0b00000110;
#ifdefined_16F877A
ADCON1=0B00000110;
#endif
#ifdefined_16F917
ANSO=0;
OSCCON=0b01110000;
#endif

TRISA0=1;//MakesRA0aninput,etc.
TRISA1=1;
TRISA2=1;
TRISA3=1;
TRISA4=1;
TRISB0=1;
TRISD0=1;
TRISD1=1;
TRISB5=0;//MakesRB5anoutput,etc.
TRISC0=0;
TRISC1=0;
TRISC2=0;
96

TRISE0=0;
TRISE1=0;

ArmedLight=0;//Setsinitiallightingconditions,setsalarmtobeunarmedatstartup
DisarmedLight=1;
Buzzer=0;
Lamp=1;

for(;;)//Continuescheckingkeypadforever
{

if(KeypadOne==0)
{

while(KeypadOne==0)
{
continue;
}

for(i=1;i<2;i=i)//Checksforseconddigitorincorrectseconddigitinkeycode
{
if(KeypadOne==0)
97

{
Buzzer=Buzzer+1;
i=2;
while(KeypadOne==0)
{
continue;
}
}
if(((KeypadFour==0)||(KeypadTwo==0))||(KeypadThree==0))
{
i=2;

while(((KeypadFour==0)||(KeypadTwo==0))||(KeypadThree==0))
{
continue;
}
}
}
}

if(KeypadTwo==0)
{

while(KeypadTwo==0)
{
98

continue;
}

for(i=1;i<2;i=i)
{
if(KeypadFour==0)
{
DisarmedLight=DisarmedLight+1;
ArmedLight=ArmedLight+1;

i=2;
while(KeypadFour==0)
{
continue;
}
}

if(((KeypadOne==0)||(KeypadTwo==0))||(KeypadThree==0))
{
i=2;

while(((KeypadOne==0)||(KeypadTwo==0))||(KeypadThree==0))
{
continue;
}
}
99

}

if(KeypadThree==0)
{

Lamp=Lamp+1;
DisarmedLight=DisarmedLight+1;
ArmedLight=ArmedLight+1;
while(KeypadThree==0)
{
continue;
}

if(KeypadFour==0)
{

while(KeypadFour==0)
{
continue;
100

}

if((MotionSensor==1)&&(ArmedLight==1))
{
alarm();

while((MotionSensor==1)&&(ArmedLight==1))
{
continue;
}

if((ReedSwitchTwo==1)&&(ArmedLight==1))
{
alarm();

while((ReedSwitchTwo==1)&&(ArmedLight==1))
{
continue;
}

101

}

}
}

voidalarm(void)//MakeslightingflashandsirenbeepcontinuouslyuntildisarmedbyKeypadOne
{
unsignedintalarm=1;
unsignedintk;

while(alarm==1)
{
Buzzer=Buzzer+1;
ArmedLight=ArmedLight+1;
DisarmedLight=DisarmedLight+1;
Lamp=Lamp+1;

for(k=1;k<delay;k++)
{
continue;
}

if(KeypadOne==0)
{
alarm=0;
102

Buzzer=1;
ArmedLight=1;
DisarmedLight=0;
Lamp=1;
while(KeypadOne==0)
{
continue;
}
}


Buzzer=Buzzer+1;
ArmedLight=ArmedLight+1;
DisarmedLight=DisarmedLight+1;
Lamp=Lamp+1;

for(k=1;k<delay;k++)
{
continue;
}

if(KeypadOne==0)
{
alarm=0;
DisarmedLight=1;
103

ArmedLight=0;
Lamp=0;
Buzzer=0;
while(KeypadOne==0)
{
continue;
}
}

}
}
104

105








Pac-Man


Final Report


Submitted to

106

The Faculty of Operation Catapult LXXXVIII

Rose-Hulman Institute of Technology

Terre Haute, Indiana







by

Group 9

Xiaolong Jin Huazhong University of Science &Technology
Wuhan, Hubei Province, China
Wes Byers Alexander Dawson School
Loveland, Colorado
Charlie Rhine Bend High School
Bend, Oregon
Chris Rai Seaholm High School
Birmingham, Michigan

July 27, 2010



Introduction

One of the major things that we realized was that when you really think about it, life is
like a video game. Life is like the ultimate role playing game. I mean when you are born, your
genes give you sets of advantages and disadvantages. Its like in castle crushers; when you first
start you have some points which you can use to boost your characters attack and defense. You
must make choices; you can make your characters attack statistic sky high, and leave the
defense at zero. Like in real life, you are making choices every day, and those choices you make
effect you in everything you do. Lets keep looking at this in the frame of a video game, for
instance if you were to give your character too little defense statistics, then you would die almost
instantly if you didnt attack them first. A better game to use as a frame for this next argument is
Pokmon. Think of any Pokmon game that you or someone you knew played. You start with a
Pokmon, and each has strengths and a weakness, which was the argument above. But after you
pick your starter, you have to raise it. This is connected to life; you are always preparing for
something, whether it is the test next week, or your future plans. And much like in the game, if
you dont prepare yourself enough to take on the challenge you fail, and have to start over.
Okay, so now you have your advantages and disadvantages, which you are building on by
107

training. After you train, and overcome obstacles you gain experience. Now in a game, that
experience would help you raise your statistics, so to speak. But in real life that experience helps
you develop and allow yourself to prepare for new obstacles. So its like a cycle, you could say
you keep trying to get ahead. So back to Pokmon, at the beginning of the game, you get a rival
to compete against. He is like a benchmark, so he is like the gatekeeper. If you beat him you
pass, if you lose you have to train harder. The point is that life and video games have a strong
connection, often times things that are happening in real life effect the video game. Such as in
Battlefield Bad Company two, where the focus is on the war the Middle East. Sadly, this is
where the video game v. life, fails. Because in the game there is a set point at which you are no
longer tested, when you beat the game. I mean, in life you eventually get tested less, but you are
pretty much always challenged. This relates to programming in many ways. One of the major
ways it relates is that when you are programming, you have all of the control. And when you
play the game you programmed, you know whats going on behind the scenes. You know how
everything works. So what does this have to do with Pac-Man?

Pac-Man

Well, whats the basic premise of Pac-Man? You are Pac-Man, and you go around eating
dots, to get points avoiding the ghosts until you can eat them, and you eat the fruit as a boost.
Then you go onto levels that regularly increase in difficulty. This relates to the introduction in a
lot of ways. First, when Pac-Man eats the dots, he has to eat all of the dots on the map to
advance to the next level. So, he has to meet this challenge, by eating all of the dots, to prove
he is worthy to advance to the next level. If he fails to collect all the dots in three lives, then he
must start again. The next relation is the ghosts. The ghosts are the obstacle, making it so that
Pac-Man has an obstacle to overcome. If he gets hit by a ghost he loses a life and this gives him
the competition. Next there are the power-ups that allow Pac-Man to eat the ghosts, and
obliterate his competition. Without this power-up Pac-Man has no way to get passed the ghosts.
And once he uses his power-up the ghosts respawn keeping the pressure on. The fruit just
provide him with a little point boost, think of it as extra credit. The last, relation is the increasing
difficulty as you go through the levels. This is the part where you are too good for level one so
they send you to a higher level to continue to test you. Pac-Man in that sense is quite unique. It
seems like just a simple arcade game, it doesnt have a simple connection to real life, like most
role playing games claim to have. But, isnt simple better? In a way Pac-Man is, pretty much the
bare bones of role playing video games. Nothing too fancy, and thats what makes it
entertaining. People enjoy simple things, things they dont have to work too hard to play or
obtain. That is probably why people enjoy playing Pac-Man so much, it has pretty simple
objectives: get dots, dont get hit by ghosts. And the programmer is making you choose.

The Love of Pac-Man

Besides the simplicity factor that we touched on earlier, there are many other reasons to
enjoy Pac-Man. The first one is for video games in general, you can do whatever you want, and
not get in serious trouble for it. It provides an escape, to everyday life. But Pac-Man is special
because it provides entertainment for all age groups, because it is an original game and has
continued to be popular through generations; it provides an escape for everyone. This was one
of the reasons why we chose to create Pac-Man. Since everyone knows what Pac-Man is and
108

since everyone has played it at some time or another it seemed like a great idea to re-create a
classic.

Why we chose to make Pac-Man

Besides making Pac-Man because it is so popular. We also chose it over our previous
idea, of snake, because we wanted a challenge, and thought we could learn more about python
and pygame then if we just made snake. We figured that if we could make Pac-Man it had a little
bit of everything in it, that we would get a good feel for the Python language.

What we did
if (self.loc[0] in [40,160,340,460]) and (self.loc[1] in [38,188,308,458]):
if self.loc[0] <= pacPostion[0] and self.loc[1] >= pacPostion[1]:
if random() <= 0.5:
if self.ghostBoard.canMove(self.posInBoard[0],self.posInBoard[1],self.loc[0],
self.loc[1], RIGHT):
return RIGHT
else:
return UP
How we did it
Lets first decipher the language. Self lets the object refer to itself. Self.loc gives the
object its location in terms of pixels. The brackets hold lists of points that tell the object its x and
y coordinate. The random statement lets the object randomly pick a path to follow. The number
after the random statement says that the object should pick a path every half second. The really
long line, the fourth line, tells the object if he can or cannot move that way. So the three lines
underneath tell the object to go right if you can. If you cant move up, the last line says, to go up
if you cant go right. This is called a method, it which is some code that allows an object to
perform an operation on its own. A couple terms to know, object oriented programming,
consists of objects which are interactions between data and objects. And that a class is a way to
create an object that has certain parameters/conditions that it always has with it throughout the
program. A field is like a file cabinet, it holds lists.
This code is for the ghosts in the game. This code tells the ghost that if it finds itself at
the x and y coordinates listed, the numbers listed in the first line, to choose a path to go on. And
the random function tells the ghosts to pick a random path every half a second. But the code also
says that since it would be in the bottom left corner of the board to choose to go either right or
left. The middle line of the code tells the ghosts that, pretty much, to go right if they can. The
three lines after that tell the ghost that if they cant move right then they should move up.
109

The different parts of code that are mainly used in this method are
self.ghostBoard.canMove, self.posInBoard, and self.loc. The reason for continually using the
self parameter is to be able to define the movements that the ghosts make. The field
self.posInBoard, and self.loc are defined as a ghosts position on the board. self.gostBoard is to
store the maze that the ghosts go through. This is a vital part of the function, because without this
part the ghosts would not be able to move and therefore we would not have a functioning game.
This would not have been possible to do without the help of classes and methods, both of which
are distinctly characteristic of object oriented programming languages such as Python and C++.
In the ghosts class, these parameters are location, screen, and random movement. Classes and
methods are essential in the art of game design and without this incredible concept known as
object oriented programming we would not be able to create the games we all know and love
today with the ease and time efficiency that we all take for granted today.
Accomplishments

Besides overcoming the lack of Python, and programming, experience we created a
working main menu that rivals the original Pac-Mans. We also successfully created a maze that
works around PYTHON which is our personal touch on the game, per say. After we got that
maze working we added in the dots that Pac-Man eats. After we got the maze and the main
menu down, we turned our attention to the Pac-Man character himself, and the ghosts. Pac-Man
was a real pain, we had to get him to move when we pressed the arrow keys, and we had to get
him to turn, so his mouth was facing the way he was going, so we can eat the dots, and we had to
get him to die when he hit a ghost. The ghosts also took us a good part of our work time. At
first we couldnt even get the ghosts to move, they would just stay in the corner. So we changed
them so they followed Pac-Man, and that was really unfair for the Pac-Man. So we decided to
make it so that three ghosts move randomly and have one follow Pac-Man. As if it wasnt
difficult enough, we then had to make it so that there was a score and that each dot was worth
one hundred points.

Game Extras [if we had time]

If we werent on a restricted time table, we wouldve added a lot more to our program
then we did. We wouldve had the time to add the fruit, that when eaten wouldve given Pac-
man a sort of power up. We wouldve also added a Mrs. Pac-Man to have a multiplayer, as if we
didnt have enough trouble getting Pac-Man to work. But more importantly we wouldve made
more mazes, so we could actually make the mazes harder to figure out.

Conclusion

Video games have so much in common with real life its frightening. And Pac-Man is a
perfect example for the reasons listed above. But, Pac-Man also taught us something about
programming. You have to do a lot of work for something very little, and learning a language in
a week doesnt help either. Throughout our experience in making Pac-Man we have come to
appreciate video games a lot more than we did before. This is an important project due to
learning the basics as well as some advanced topics of programming in a language such as
110

python, learning about what the structure of a program should look like in order to complete a
large task such as a game, and most of all learning how to think in a logical progression that
allows you to debug and create a program in a timely fashion.







PYPORTAL


Final Report


Submitted to

The Faculty of Operation Catapult LXXXVIII

Rose-Hulman Institute of Technology

Terre Haute, Indiana






By

Group 10

Nick Eyre Bellarmine College Preparatory
Los Altos, California
Lance Riechel Snohomish High School
Snohomish, Washington
Ethan Dale Upper Perkiomen High School
Barto, Pennsylvania

111

July 27, 2010




112

Introduction
PyPortal is a two-dimensional game based on the computer game, Portal. It is
programmed using Python, a high-level object orientated computer programming language that
can be used for a myriad of programming tasks. The goal of each level is to move a stick figure,
or character, to a yellow door that leads to the next level. The user is able to use the mouse
buttons to shoot two different kinds of portals at obstacles in the game. When deployed on
obstacles, the portals allow the character to teleport between them. If the user goes in to one
portal, he will come out of the other with his velocity conserved. There are many different types
of obstacles that we have created in order to allow for interesting and challenging game
scenarios. Furthermore, there are enemies who shoot deadly lasers at the character.

About Python

Python is a high-level object-oriented programming language which has a myriad of


practical purposes. Pythons syntax is much simpler and less verbose than the syntax of other
languages such as Java and C, and it has been said that creating a program in Python requires as
little as one-fourth the amount of code that the same program would require in Java.
Furthermore, Python is designed to have easily-readable code, making it very easy for beginners
to pick up the language. Python was designed from the start to be simpler and more fun to
program in than other languages, and was named after the British comedy series, Monty
Pythons Flying Circus.
PyPortals creation was also aided by Pygame, a Python graphics library intended for
game creation. Pygame simplifies many tasks associated with game development, such as
drawing shapes on the screen and performing crude collision detection between multiple
rectangles. Games made in Pygame are typically structured in a large loop, which runs
repetitively to draw graphics. Typically, the graphics are updated entirely each time the loop
runs.
pyPortal makes use of Pythons object-oriented programming features. Object-oriented
programming allows the programmer to create objects, intelligent bundles of functions and
information. Objects are modeled after classes, and contain methods, functions which perform
object-specific tasks. Furthermore, objects contain instance variables, which can contain object-
specific information. For example, if a circle object was created, methods could be made to
move the circle and the instance variables could keep track of circle position.

Obstacles

Before a character can be created, a level must be made for him to navigate. Levels in
pyPortal are constructed of obstacles, which limit the motion of the character and of portals.
These are accomplished in pyPortal by an obstacle class. Each level is made up of a list of
obstacle objects which each know their position and type.
113

pyPortal features several different types of obstacles. Standard gray obstacles serve as
the basic structure of levels. Characters can walk along them and can deploy portals on them.
Black obstacles feature the same, except that portals cannot be deployed on them. Red obstacles
or lava cannot be walked upon and portals cannot be deployed on them. Light blue mirror
obstacles can be walked upon and reflect portals just like a standard flat mirror. Although the
Portal game which pyPortal is based upon contains dark tiles, standard tiles and toxic waste
which performs similar to lava, mirrors are a new innovation unique to pyPortal, which was
conceptualized by the developers to add extra challenge and fun to levels in the game.

Character

The most important part of pyPortal is the character, a simple stick figure who navigates
the levels. The character in pyPortal is drawn with a series of lines and a circle. We did not use
an imported image because pygame is not good at handling image transparency and images can
potentially slow down a program tremendously. The area around the stick figure must be
transparent in order for the game to look clean and professional.
In pyPortal, the character is created as an object of the class Character. The character
object is intelligent and can remember information about its location, state and more. The
character in pyPortal is drawn from a reference point in the upper left hand corner of the figure.
By having a reference point, the task of moving the character is vastly simplified. By simply
moving the reference point, the entire character will be drawn in a new location relative to the
reference point. In addition to drawing the character, the character object keeps track of a
transparent rectangle drawn around the character. By creating a rectangle around the character, it
is easy to take advantage of pygames built-in collision detection features which can detect
collisions between different rectangles.
After drawing the character, the next task was to allow for the character to move. In the
main game loop, we wrote code to take input from the keyboard and move the character
accordingly from left to right. We next implemented gravity in the form of a constant increase in
the downward velocity of the character. The final movement to add to the character was the
jump, which is implemented by giving the character an upward velocity, which is slowly
decreased by the force of gravity, causing a realistic arcing jump motion.
The next challenge faced in the development of pyPortal was collision detection.
Collision detection is important so that the character is constrained onto the playing screen and
will not fall off of the bottom of the level. To accomplish this task, we use pygames rectangle
collision detection functions, which allows the program to test if multiple rectangles are
colliding. Because all of the obstacles on screen are rectangles, it is simple to check if the
invisible rectangle around the character is in contact with one of the obstacles. If the character is
in contact with an obstacle, the program detects this and prevents further movement in this
direction.
114

One problem that kept resurfacing during the creation of pyPortal is that the character and
portal projectiles sometimes had too much velocity and passed through obstacles so fast that the
computer could not detect it. To fix this issue, we placed a rectangle around the area that we
wanted the character to stay in. If the character or a projectile leaves the box, the program places
them back inside the box where they were before they exited, effectively preventing the
character from accidentally leaving the level.

Target

With a moving character, the next important step was to create a target on each level for
the character to reach. This is accomplished by drawing a yellow square at the end point of the
level. The program uses pygames collision detection functions to detect if the character reaches
the target. If he has reached it, the program loads the next level and proceeds.

Portals

Portals are one of the most important aspects of the game. When the user clicks
somewhere on the screen, the system shoots a projectile towards the click, which destroys itself
and creates a portal when it contacts an obstacle.
In order to make the portals shoot, we had to find a way to track the direction of a mouse
click relative to the characters position. The following equation gives a set of coordinates which
provide the direction to the click if they are added continuously to the characters position:
[(change in x)/(distance), (change in y)/(distance)]. The program is written to draw a small
square projectile in the center of the character, and then move it using the coordinates of the click
and the equation. It then travels until it collides with an obstacle. Then, if the obstacle allows it,
a portal is created. Orange portals are assigned to the right mouse button and blue portals are
assigned to the left mouse button. The program is written so that only one of each type of portal
can be drawn at a time. If the right mouse button is pressed twice in a row for example, the first
portal destroys itself and the second is drawn.
Once deployed, the most important aspect of portals is that they must move the character
between them. To do this, we programmed pyPortal to destroy the character when he went into a
portal and two portals were active on the screen. Then, the character is redrawn by the other
Portal.
When the character enters a portal, the program records the characters velocity towards
the portal. This way, when the character exits the other portal, the same velocity can be applied
to it. It is important to note that the velocity must be added to the correct variable of the
characters velocity. For example, if the character is exiting a portal on the ground, the velocity
must be set to the characters y velocity. If the portal is on the ceiling, the velocity must be set to
negative y velocity. For this to work, the program needs to know on which side of an obstacle a
115

portal is. To solve this, the portal objects are intelligent and know which side of an obstacle they
are placed on, allowing for intelligent portaling.

Enemies

To make pyPortal slightly more difficult, the game features enemies, which are laser-
wielding triangles that automatically track the characters motion. On levels with enemies, the
enemies start at a fixed point and constantly shoot slow-moving laser breams towards the
character. If the lasers collide with an obstacle, the laser is destroyed and re-draws. If it contacts
the character, the character is killed and the level must be re-started.
The enemies in pyPortal are accomplished by creating enemy objects which keep track of
their position, firing speed and current laser position. These enemy objects, when fed the
character location, determine the direction to the character and start to build a line in that
direction. With each new point added to the end of the line, the object performs intelligent
collision detection to detect if it is in collision with either the character or an obstacle so that it
can react accordingly.

Level Creation

One of the goals in the creation of pyPortal was to make level creation as simple and
quick as possible for the programmer. To accomplish this, levels are created as simple lists of
the objects that must be created to form a level. Each object is passed its location on screen,
measured in pixels from the upper left corner of a window.

Sample Level Generation Code:
obst acl es. append( Hor i zont al Obst acl e( [ 0, 0] , 1000) )
obst acl es. append( Ver t i cal Obst acl e( [ 0, 0] , 700) )
obst acl es. append( Ver t i cal Obst acl e( [ 980, 0] , 680) )
obst acl es. append( Hor i zont al Obst acl e( [ 0, 680] , 1000) )
char act er = Char act er ( [ 200, 55] )
t ar get = Tar get ( [ 980, 630] , 60)

The code shown above generates a simple level with four walls and a target. The first
four lines add four obstacles to a list of obstacles which is later passed to the program. Each
obstacle has a starting location and a size. The next line creates a character object at a specified
position. The final line creates the target which the character must reach to complete the level.

Conclusion

In conclusion, pyPortal proved to be an excellent and challenging challenge. For three
newcomers to Python, the first week of our project time was spent learning Pythons syntax and
familiarizing ourselves with the pygame library. After this, we spent a week and a half of heavy

developm
to 1200 l
code, ma
of the bu
find. In a
simplify,
sections o
improvem
O
project.
fun to pla
programm
on a prog

Appendi

T
pyPortal.

ment to creat
lines of code
any bugs aro
ugs that we c
addition to de
to produce
of the code t
ments can al
Overall, the c
All group m
ay video gam
ming experie
gramming pr
ix I: Sample
The sample le
.
te all of our c
e in several f
se and it wa
ould find in
ebugging co
the same eff
that could al
lways be ma
creation of py
members had
me in a short
ence, none o
roject or wor
e Level
evel shown b
O
code and to
files to achie
s necessary t
the program
ode, there we
fect with far
lso be trimm
de.
yPortal prov
a great time
t period of ti
of our group
rking on a ga
below demo
Operation
de-bug the p
ve all necess
to debug all
m, there are li
ere also some
fewer lines
med down; as
ved to be ver
e and worked
ime. Even fo
members ha
ame of this s
nstrates man

Pocket C

program. Ov
sary function
of these. A
ikely still so
e sections th
of code. No
s with all sof
ry education
d together to
for the group
ad prior expe
scale.
ny of the gam
Catapults
verall, our pr
ns. In writin
Although we
ome left that
hat we found
o doubt there
ftware progra
al and a grea
o create an in
p members w
erience work
me elements
rogram has c
ng all of this
have remove
we could no
d we could
e are also oth
ams,
at Catapult
nnovative an
with prior
king in a gro
s present in
116
close
s
ed all
ot
her
nd
oup

117


Submitted to
The Faculty of Operation Catapult LXXXVIII
Rose-Hulman Institute of Technology
Terre Haute, Indiana


By

Group 11

Paul Deaton McCallie School
Huntsville, AL
Robbie Gonzales Wolfe City High School
Wolfe City, TX
Daniel Lee Moundsview High School
Arden Hills, MN
Lindsey Watterson Southwestern MS/HS
Lexington, IN

July 27, 2010




Python is a computer programming language that is meant to simplify and make code
easier to read. It can be used for simple math and graphics or for the designing of games. It can
be filled with complicated code or made simple through the use of functions, objects, and
classes. In Python, classes are used to define objects and the functions or methods they are to
118

carry out. Objects are things that can be manipulated to carryout certain actions that are defined
in functions and methods. Functions and methods are used to define specific tasks or actions that
can be called on throughout the program. Classes, objects, and functions and methods are used
to simplify code since they enable the programmer to reuse certain areas of code without having
to completely rewrite that certain area of code. These can be called anywhere within the code as
long as specifications are met. This enables the programmer to write a multiple line code by
writing one line of code simplifying the complexity of the code and enabling it to run more
efficiently and smoothly. When programming it is useful to import modules, which contain
already defined classes and methods. Some of the ones used with Python include Zellegraphics
and Pygame.
Our project goal was to program a computer game using Python in order to improve our
programming skills and knowledge of the language. First we had to come up with an idea for
our project. We decided to replicate the game Pocket Tanks, but to change some features of it.
In Pocket Tanks there are at least two players. Each player controls a tank that shoots projectiles
at varying angles and levels of power. There are normally different weapons that the players can
choose. Each tank has a life bar located somewhere on the screen and sometimes a scoreboard
with each players score. The players choose their weapon, angle, power, and position of tank
and then take turns attacking each other. Normally the terrain upon which the tanks are located
involves a mountain or some other obstacle that the players must fire over in order to attack the
other. When the projectiles that are fired collide with the terrain and explode, parts of the terrain
are destroyed. The tanks are able to move, but are normally unable to climb out of the holes or
obstacles in the terrain. We decided to incorporate most of these features into our game:
Operation Pocket Catapults. Some of the features we decided to change involved the tanks and
projectiles. The first change we decided to make was to change the tanks to catapults. Instead of
having random projectiles that were simple circles or just simple shapes, we decided that we
would have our catapults throw images of our counselors heads at each other.
Once we had decided on the features that we would include in our game and the changes
that we would make, we began working. First we imported Pygame and a few other modules
that would be helpful and designed a screen for our program to run on. Next we divided up the
work among the group members. Two of us began looking for and cropping pictures of our
counselors and a catapult in paint. We also drew the catapults that were to be used in our game
in the paint program. The other two then divided up the work even more. One began
programming the main menu and the other the classes for all of our objects. On the main menu,
we imported a cropped photo of a catapult and one of our counselors. We placed these on the
main menu and then programmed the text for the main menu, which included the title of our
program and the text for a start and options button. Next we set the colors of and drew two
rectangles that went underneath the text for the start and options buttons. Then we drew in three
different arcs that went from the catapult image to the head of our counselor in order to make it
seem as if the head was being thrown. Next we programmed the two rectangles to change to a
119

lighter shade when the mouse scrolled over them. Afterwards, we enable the user to click on
either one of the two different rectangles so that a new screen would appear. If the start
rectangle was clicked, the program opened up the main game screen and the options rectangle
led to a new menu page with the options on it. After the buttons were enable the options page
was setup. We placed the same images from the main menu on the options menu. Then
programmed the text for the options page, including the title of the page, sound, music, number
of players, and the text for a back button. Then we drew two different rectangles to function as
buttons. Next we programmed the buttons so that the back button went back to the main menu
and the music button changed the volume.
The other person began programming classes and functions for our game. There were
two main classes that we programmed. One was for our catapults; the other, projectiles. In the
catapult class we defined specific functions for the catapults to carryout such as moving, firing,
drawing itself, and turning. Each one of these functions required certain information in order to
work. For example, the moving function required the x and y coordinates of the catapult and the
change in x and y. The fire function required an image, a projectile, an x and y coordinate for
the projectile, and the angle and power that the projectile was to be shot at. The projectile class
defined how the projectile would move, draw itself, and the hit box of the projectile. The
movement of the projectile involved the use of gravity. This caused the projectiles to move in a
parabola fashion instead of a straight line. Gravity was simple to implement and was
implemented by typing gravity into the movement function of he projectile and setting it equal to
1. Then gravity is added to the change in y. The gravity is added to the y instead of subtracted
since the origin coordinate is located in the upper left corner. Due to the location of the origin, y
goes down the screen and continually gets larger. If the gravity was subtracted instead, the
projectile would have an inverse gravity that pulled it towards the top of the screen.
Once the classes were defined, we began programming our main game. To start we set
up the screen. We found the image we wanted to use for the sky and edited it in paint. Then we
programmed it onto the screen. To begin our programming we started with just one catapult and
a green rectangle that we drew on the screen to function as the ground. Then we used our
catapult class to program the catapult that we had drawn in paint. First we drew the catapult so
that it would appear. After we had that working, we programmed the catapults movement. To
do this we had to get the catapult to respond to the left and right arrow keys. After the catapult
responded to the arrow keys, we limited how much they could move and how fast they would be
able to move. Slowing the catapults down involved the use of a sleep function that was imported
at the start of our program. Then we limited the catapult so that it could only move a hundred
pixels in each direction from its starting point. Next we programmed a limitation that kept the
catapults from moving off the screen. Once we had the movement working we programmed the
catapult image to flip when it changed directions. After we finished the movement, we
programmed the catapults ability to fire. This involved the ability to change the angle that the
catapult would shoot. The angle had been defined in the catapult class, but the player was unable
120

to change it within the game. First we drew a rectangle onto the screen that would display the
angle. Next we programmed text that printed Angle onto the box. Then we programmed text
that printed the angle in degrees beneath Angle. We programmed this text to change by five
degrees each time the up or down arrows were pressed. Next we limited the angle so that it
couldnt be below zero degrees or above ninety degrees. Next we programmed the power. First
we programmed text that printed Power onto the same rectangle that the angle information had
been printed on. Then we enabled the player to edit the power in increments of two that were
printed onto the rectangle. After the power and angle were programmed, we programmed the
catapult to through an image of one of the counselors heads.
Once the main functions of the catapult were programmed, we then had to set them so
that the player could access each of them. We made it so that the player was immediately able to
move once their turn started. Then we set the enter key to cycle through each of the functions.
So once the player is finished moving, they press enter disabling movement and causing the
angle selection to appear. When they press enter again, the power selection appears. If they
press enter again, the catapult fires whatever head they have selected. Once we accomplished
this, we had a second catapult of a different color drawn onto the screen. Then we programmed
the turn system. Instead of rewriting all of the code for the second catapult that we had for the
first we just set it to equal the first player. This made the first player equal to another variable
enabling the turn system. This works because each time the computer runs the program the first
player goes through their turn and then the second player becomes the first player and runs
through the program. The two different players continue to switch positions throughout the
game.
After we had the two catapults working, we began programming more specific
instructions and limitations for the projectiles. We came across the problem that the projectiles
when they were shot off screen would crash our program. To fix this we made it so they
disappeared from the program if they went off the screen. Then we had to make it so that the
projectiles would stop when they hit the ground instead of going straight through it. To do this
we used a collision detector and set the detection to recognize when the projectile hit the ground.
Once this worked, we had to set the explosions. In order to do this we found images of an
explosion online that we edited in paint. Each of the images showed a different scene of the
explosion. We programmed each of these images to be shown on the screen consecutively once
the head collided with the ground.
Once we had the explosions and limitations for the projectiles, we began programming
the hit points system and the destructible ground. To do the hit points we created a code similar
to the one we used for the angle and power. Instead of having the hit points displayed in a box
we programmed them to be displayed above the catapults. We gave each catapult a hundred hit
points. Then we edited the explosions so that they would subtract hit points depending on where
the catapult was located compared to the explosion. If a catapult is hit directly by a projectile,
fifty hit points are subtracted. The amount of damage is then reduced the further away from the
121

center of the explosion the catapult is. Next we had to develop the destructible ground. To do
this we had to go into pain and create an image of the ground on only a portion of our screen.
We set its color and then filled in the rest of the screen with purple. We deleted the previous
ground from our code and replaced it with this image.










sky=i mage. l oad( 'sky.bmp')
gr ound=i mage. l oad( 'ground.bmp')
gr ound. set _al pha( )
gr ound. set _col or key( ( 255, 0, 255) )
gr oundhi t box=Rect ( 0, 500, 1000, 200)
scr een. bl i t ( sky, ( 0, 0) )
scr een. bl i t ( gr ound, ( 0, 0) )
f or z i n r ange( 26) :
scr een. bl i t ( expl osi on[ z] , ( head. x- 150, head. y-
150) )
sl eep( . 04)
i f z==18:
x=i nt ( head. x)
y=i nt ( head. y)
dr aw. ci r cl e( gr ound, ( 255, 0, 255) , ( x+15, y+15) , 75)
scr een. bl i t ( heal t ht ext 2, ( ot her pl ayer . x+20, ot her pl ayer . y-
10) )
scr een. bl i t ( ot her pi c, ( ot her pl ayer . x, ot her pl ayer . y) )
di spl ay. updat e( )
Next we set the purple used in the image to be transparent. Then we programmed each explosion
to draw a circle of seventy-five pixel radius in this color. Since this color was set as transparent,
the circles do not appear giving the impression that the ground has been destroyed. Once we
finished programming the destructible ground, we had to get the catapults to sense when there
was ground underneath them and when there wasnt. If there wasnt any ground underneath
them, we programmed them to fall until there was. Then we enabled them to move slightly up a
curve and to move down a slope. Next we programmed the destruction of the catapults when
they hit the bottom of the screen with no ground underneath them.
122

After finishing the destructible ground and the hit points, we programmed another
rectangle to appear on the screen to function as our weapon selection box. We divided this
rectangle into ten different ones each with a width and height of fifty pixels. Next we placed the
different pictures of each of the counselors into the boxes. Then we had to program each of the
different boxes to allow the players to click on them during their turn. Once we accomplished
this, we programmed it so that each different square caused a different counselor to thrown by
the catapult. In order to do this, we had the mouse clicks return the name of the counselor that
was clicked. Then we set each returned name equal to the picture of that counselor. The image
of that counselor is then plugged into the fire function. This enables the user to select the
counselor that will be thrown. After finishing this, we had finished programming our game and
it was ready for hours of play.
Over the course of our work on Operation Pocket Catapults we learned many things
about the Python computing language. We learned that Python is a highly versatile language that
is able to do simple actions like drawing simple shapes in window with ease, able to handle
complex programs like our game with no loss of efficiency, and able to work with multiple
combinations of simple and complex tasks at once. On top of that, it has an unparalleled ease of
use that no other programming language can match. Coding in Python has proven to be a useful
skill to learn.



PARA RUNNER


Final Report


Submitted to
The Faculty of Operation Catapult LXXXVIII
Rose-Hulman Institute of Technology







Introduc

like langu
as effortl
Languag
at the end
lists, mea
popular l
data type
indenting
two piece

Peter

Dharm

John V

ction
The P
uages that ha
less as possib
es like C and
d of all state
ans of sortin
languages. A
es; the interp
g code is a co
es of code, w
Jacobs

min Shah

Vall

Python progr
ad more com
ble without s
d Java requir
ments and p
g through th
Additionally,
preter automa
onvention in
written in Jav
Terre H
G
Jul
amming lang
mplicated syn
sacrificing k
re braces aro
parenthesis ar
hem, and sho
Python doe
atically hand
n these langu
va and Pytho
Haute, India


By
Group 12
Hom
Fort
Evan
Evan
Carm
Carm
ly 27, 2010
guage was d
ntax. Its goa
key features o
ound section
round all exp
ortcuts with o
es not require
dles it for the
uages, it is no
on, respectiv
ana
me School,
t Wayne, Ind
nsville Day
nsville, Indi
mel High Sc
mel, Indiana
developed as
al was to mak
of other prog
ns of code (c
xpressions. P
operators tha
e the program
e programme
ot required.
vely:
diana
School,
ana
chool,
a
s an alternati
ke code writ
gramming la
alled block
Python provid
at are not fea
mmer to exp
er. Although
For example
ive to many
ting and read
anguages.
ks), semicol
des many bu
atured with o
plicitly decla
h spacing an
e, consider th
123
C-
ding
lons
uilt in
other
are
d
hese
124

The Python version is more concise. This is particularly useful when designing complex
algorithms that can feature looping structures.

Object Oriented Programming
Object-oriented programming utilizes blueprints called classes that have declarations for
data fields that represent real-life quantities. Each instance of a class is called an object. Objects
make programs more efficient. Without objects, programmers would have to create many
variables with different names. Classes can also be extended by building upon previously coded
ones, the process is known as inheritance, to allow maximum customization. Classes can hold
methods that perform operations on that data. For example, a class can be created to represent a
person, having fields for age, height, or gender. Different objects of that same class represent
actual people, with varying ages and heights. A method called birthday can be used to
increment the age by one. If a tax accountant needs additional fields for a social security number
and personal income, a programmer can extend the person class to specialize it for the
accountant.

Parallax
Parallax is the difference in the apparent position of an object viewed along two different
lines of sight. Parallax is measured by the angle of inclination between those two points. Motion
parallax is the parallax caused by movement of the eye from one nearby point to another, and can
be used to create an illusion of depth. We have used motion parallax to create a pseudo-3D effect
on a legacy 2D display. Astronomers use the principle of parallax to measure the distances to
celestial bodies beyond the solar system. Parallax also affects optical instruments such as
binoculars, microscopes, and twin-lens reflex cameras that view objects from slightly different
angles. Many animals, including humans, have two eyes with overlapping visual fields to use
parallax to gain depth perception; this process is known as stereopsis.
A simple everyday example of parallax can be seen in the dashboard of motor vehicles
that use a "needle" type speedometer gauge (when the needle is mounted in front of its dial scale

in a way
speed ma
needle ca
from the
view.
Figure1:Ce
that leaves a
ay show 60,
an appear ag
left or from

enterViewofCu
a noticeable
but when vi
gainst a sligh
the right), b


ubeF
spacing betw
ewed from t
htly lower or
because of th

Figure2:RightV
ween them).
the passenge
higher mark
he combined

ViewofCube
. When view
er seat (i.e. fr
k (depending
d effect of the


Figur
wed from dire
from an obliq
g on whether
e spacing an

re3:LeftViewo
ectly in fron
que angle) th
r it is viewed
nd the angle

ofCube
125
nt, the
he
d
of
126


Para Runner
Para Runner is a game we have written using Python programming language where the
user has to dodge obstacles in order to get the highest score. Using the concept of motion
parallax we make the display of the game move according to the users head motion, thus,
simulating a 3D effect on a 2D display. The user can play the game by steering with his head or
using the keyboard. We have used the openCV library, developed by Willow Garage, for face
detection and tracking, and pygame for drawing the cubes and other game objects. Object-
oriented programming was an essential part of the Para Runner game. There were no default
classes for rendering 3D objects, so we needed to define a class that would hold several points in
a polygon, and larger classes that would collect several such polygons into one 3D shape, such as
a cube. We also needed mathematical formulas for determining the parallax distance. The
points themselves were classes containing fields for X, Y, and Z coordinates. We then made
several instances of the Cube class, randomizing the point values and placing them into a list.
A loop cycled through the list and drew the cubes individually.
If the user chooses the option of following the users head, the game initiates the
webcam, detects the users face, registers their face movement to calculate the apparent position
of each point using the concept of motion parallax, and adjusts the display accordingly. If the
user chooses the mouse, the game will record the co-ordinates of the cursor to calculate the
apparent position using the concept of motion parallax, and will adjust the display accordingly.

Implementing Motion Parallax in Para Runner
The equations for determining distance to objects (such as stars) based on the observed
parallax are fairly well known and readily available. On the other hand, doing the inverse,
calculating what the observed parallax should be, based on a known distance is slightly less
common. The equation can be derived with the aid of a simple diagram.
For the movement in one axis we can treat both the screen and the users motion as being
two parallel lines in the plane. The object is a point at a known distance in between the lines.
The object has a known location along the screens line (in this case its x coordinate) and a
known distance away from the screen (its depth, or z coordinate). If the user stands
immediately in front of the object, it should appear to be directly in front of the user, in the

center of

If
the objec
Apparen
inclinatio
from the
W
objects d
out, this c
0b]cct
needs to
negative
UserMot
UserMot
T
def upda












f the screen.
f the user mo
ct should app
nt Position i
on to the obj
object to the
We can then s
depth, Appo
can be simpl
cptb (
0sc
be inverted,
values, and
tion will be p
tion will be n
The actual Py
ateParalla
f aceDel t a
f aceDel t a

di st ToFac

i f ( f aceDe
self.
r et ur
i f ( f aceDe
self.
r et ur

This is repr
oves a know
pear to move
in the figure
ect, we can t
e user, givin
solve for the
orcntPositi
lified to the
uscMoto
stuncc-0b
due to the f
rightwards m
positive, and
negative, and
ython code fo
ax( self, f a
aX = f aceX
aY = f aceY
ce = f aceDi
el t aX == 0)
. px = 0
r n
el t aY == 0)
. py = 0
r n
resented by t
n distance to
e a certain di
. It is the app
take the arc
ng us = ai
e apparent po
on = 0b]cc
equation act
on
]cctcpth
) .
fact that com
motion as be
d ApparentPo
d the Appare
for calculatin
aceX, f ace
- self. x
- self. y
i st - self. z
) :
) :
the perpendic
o the right, d
istance in the
parent positi
tangent of th
ictan[
UscrDI
osition by m
ctcptb ta
tually used in
In the actua
mputer graphi
eing positive
osition will b
entPosition w
ng the differe
eY, f aceDi s
z
cular line in

denoted by U
e opposite d
ion we wish
he users mo
UscrMotIon
Istancc-Objcc
multiplying th
an (). Sinc
n our progra
al Python cod
ics treat leftw
e. Therefore,
be negative,
will be posit
ence in rende
st ) :
n the center o
User Motion
direction, den
to find. To f
otion divided
ctDcpth
.
he tangent of
ce tan (arctan
am, Apporcn
de, the Appa
wards motio
, if the user m
and if the u
tive.
ered position
of the figure.
n in the figu
noted by
find the angl
d by the dista
f by the
n()) cance
ntPostion =
arentPosition
on as being
moves right,
user move lef
n looks like
127
.
ure,
le of
ance
els
=
n
,
ft,
this:
128

i f di st ToFace == 0:
di st ToFace = 1

dxDt oFace = ( f l oat ( f aceDel t aX) / f l oat ( di st ToFace) )
dyDt oFace = ( f l oat ( f aceDel t aY) / f l oat ( di st ToFace) )

self. px = - dxDt oFace * self. z
self. py = dyDt oFace * self. z
Where px and py are the difference in apparent position of the object, and are added (or
subtracted) from the actual x and y coordinates to get the onscreen location of the point.

Coding
Once we had the parallax equation, we could begin our implementation. Since Python
lends itself well to object-oriented programming, we decided to represent objects on the screen
as being collections of shapes or polygons, which were themselves made up of points. Each
Point object had an x, y, and z coordinate, and a function to compute its apparent position on
the screen based on the location of the users face. Since detecting a face requires advanced
mathematics and programming, we started off by using the cursor location instead of a face.
Each point object uses PyGame (a popular Python library for game making and simple
graphics) to draw two-dimensional polygons in the screen. A Shape object composed of several
Points could have all their component points recalculate their apparent locations, and then draw
a polygon to the screen. For example, each wireframe cube in our game is made up of four
Shapes, front, back, top and bottom (the sides do not need to be drawn separately for the
wireframe models) and eight points. This architecture allowed us to create a large number of
Cube objects, ask them to figure out where all their vertices should appear on the screen, and
then draw all their component shapes. This made managing all the 3D obstacles very easy, since
they could largely take care of themselves.
The next step was to obtain the location of the users face, for use in the parallax
calculations. To do this, we decided to use the Open Computer Vision library from Willow
Garage, a prominent robotics group. OpenCV has bindings for Python 2.6, which meant that we
could simply pass OpenCV the images captured from the webcam, and allow the library to find
the faces in the image. It was slow for gaming purposes, at around 100 to 150 milliseconds for

each fram

Results a
W
programm
get the de
T
position u
achieved
not achie
of the scr
O
visually n
resulted i
breaking
accuratel
they start
players v
me. The over
nd Conclusio
We have used
ming to desi
esired result
The game det
using the de
d our goal of
eve our goal
reen to the u
One of the dr
noisy or clut
in the displa
immersion
ly steer the g
ted playing t
velocity acc
rall working
on:
d the Python
ign our game
s.
tects the user
rived equati
simulating m
of simulatio
user.
rawbacks of
ttered enviro
y jumping a
and slowing
game using t
the game, se
ordingly.
Detects
Calcu
appare
usinge
p
of the game
n programmi
e. In our gam
rs face, regi
on for motio
motion paral
on 3D cubes
our program
onments, jum
around and la
g down the g
the users mo
eing how far
Gameusin
detect
suser'sface
ulatesthe
entposition
equationfor
arallax
e can be expl
ng language
me we have u
isters the use
on parallax, a
llax to get a
where the cu
m is that the f
mping around
agging behin
ame as a wh
tion, by mak
r left or righ
Gam
ngface
tion
MovesBackgro
accordingly
Registersuse
motionsincel
update
Adjustsdispla
accordingly
lained using
e and the con
used method
ers head mo
and adjusts t
3D effect on
ubes looked
face detectio
d or losing th
nd from the u
hole. We we
king a note o
ht the user ha
meMenu
ound
y
er's
last
Gam
Regi
Ca
appa
using
ay
y
g the followin
ncept of obje
ds, classes, lo
otion, calcul
the display a
n a 2D displa
d as if they w
on is erratic,
he face. The
users actual
ere, however
of where the
as moved, an
meusingthe
mouse
istersposition
ofcursor
alculatesthe
arentposition
gequationfor
parallax
ng diagram:
ect-oriented
oops, and lis
lates the app
accordingly.
ay, but we c
were coming
especially in
ese issues
l motions,
r, able to
user was wh
nd adjusting
129
sts to
arent
We
ould
out
n
hen
the

130

A few possible enhancements that could be made to our game would be to add music to
our game, make a menu that allows the user to select the faces of their favorite counselors as
runners, increase lives as the user gains points, and creating special objects that give the user
points or lives if the user runs into it.
Thus, we have used the Python programming language, the idea of object-oriented
programming, and motion parallax to create a simple, fun game that simulates running through a
field full of wireframe cubes.



Namalito
Final Report
Submitted to
The Faculty of Operation Catapult LXXXVIII
Rose-Hulman Institute of Technology
Terre Haute, Indiana


by
Group 14
Celena Lipscomb Trinity High School
Euless, Texas
131

Kris Welch Eastside Preparatory High School
Woodinville, Washington
Ricky Haines Elkins High School
Missouri City, Texas
July 27, 2010

Introduction
Programming languages are a way of communicating just like normal languages such as
English, Chinese, and Spanish. The only difference is that normal languages are used to
communicate between people, while programming languages are used to communicate
instructions to a computer. For each language, there are classes of objects, and one can import
and call other modules within a module. Python, the programming language which we learned,
does this quite effectively through a method called object oriented programming. Using this
concept, one is able to create versatile modules which contain functions to manipulate objects in
ones own program or to use those created by others. Using what we learned about Python, we
were able to create a game, which we called Namalito. Through this document, a recreation of
our process by which we created our game will be recounted.
Method
The beginning of a Python program generally starts by importing functions from various
modules, since Python keeps itself resource efficient by keeping only a small library of built in
functions to work with. In Namalito, we started by creating our first gameplay mode: arcade
mode. This meant initializing a window, which we did by simply initializing the window with
the code here (which uses an outside graphics module called pygame to render the defined
objects in the window being created here):

pygame. i ni t ( )
scr een = pygame. di spl ay. set _mode( [ 1000, 700] , 0, 32)
pygame. di spl ay. set _capt i on( 'Namalito')
backgr ound = pygame. i mage. l oad( 'NamlitoMainScreen.bmp')

The first line calls the module pygame. The word init is telling the module to initialize.
The next line introduces a window object called screen and sets the width and height. The next
line of code sets the caption at the top of the window to read Namalito. The next line of code
loads an image that was created in Blender, a 3d modeling program, as the background of the
window.
This is the piece of code that checks for keystrokes:
f or event i n event s:
i f event . t ype == QUI T:
132

r et ur n
i f event . t ype==KEYUP:
i f event . key == K_w or event . key ==K_UP:
hel dw=Fal se
el i f event . key == K_s or event . key==K_DOWN:
hel ds=Fal se
el i f event . key == K_a or event . key==K_LEFT:
hel da=Fal se
el i f event . key == K_d or event . key==K_RI GHT:
hel dd=Fal se
i f hel dw==Fal se and hel ds==Fal se and hel da==Fal se and
hel dd==Fal se:
hel d=Fal se
el i f event . t ype == KEYDOWN:
hel d=Tr ue
i f event . key == K_w or event . key ==K_UP:
p. moveUp( )
hel dw=Tr ue
el i f event . key == K_s or event . key==K_DOWN:
p. moveDown( )
hel ds=Tr ue
el i f event . key == K_a or event . key==K_LEFT:
p. moveLef t ( )
hel da=Tr ue
el i f event . key == K_d or event . key==K_RI GHT:
p. moveRi ght ( )
hel dd=Tr ue
el i f event . key==K_SPACE:
myShot s. append( p. f i r e( ) )

This code is called a for loop. In the first line, the words event in events is called the
conditional statement because it determines whether the for loop repeats or not. This for loop is
filled with if statements. As the name suggests, the code only runs if its conditional statement
(following the if) is met. Sometimes an if statement has an else statement that runs if the
conditional statement is not met. A combination of these words is called an elif. This is like
putting an if statement inside of an else statement. In this code, each if statement checks with the
conditional statement if a certain key is being pressed. If it is, the ship moves in that direction or
shoots, and if not, the movement code is skipped. This code runs until event surpasses
events; that is, until the last event in the list events is done.

After initializing a window, the players ship was drawn in that window by first creating
a ship class, which allows functions to be created and called which modify a ship object, which
is basically a small segment of code that knows some basic things about itself. This means that
ship can be used multiple times to modify multiple ships, which not only saves code from having
to be written twice, but makes it able to be used in other projects/files. The ship class has
various functions under it which define movement in the up, down, left, and right directions.
The ship class is then imported into a separate file called player. In here, things such as lives,
health, and collisions are defined so that the ship can interact with other objects in the window.
133

This is imported into the main function where the window is initialized, and then this ship with
all of its newly defined properties can be drawn using a pygame function called screen.blit.
While arcade mode was still in its infantile stages, we began to code shots into the game.
A test mode where shots rained down from the top of the screen randomly to test collisions lead
to the creation of a mode called survival since it was too interesting. All that was left to
implement there was a counter to say how many shots the player had dodged. In order to
implement this, the shots are simply removed after they leave the screen; raising the counter for
how many shots the player has dodged.
After finishing survival mode, we went back to the original concept of the game, now
dubbed arcade mode. This is where there are actually enemies that intelligently dodge the
players shots and also aim at the players ship. The patterns of movement and attack are
different for different enemies; the red enemies fire a spread shot intermittently and follow
around the player unless there is a shot coming at it, the blue enemies pick a corner and fire three
rapid succession shots at the player, the green enemies follow the player and shoot a bunch of
circular shots at a steady interval, and the boss just moves from side to side shooting at the
player. The speed of each enemys shots and movement depends on the difficulty chosen before
the game starts.
The later stages of development were relegated to minor graphical tweaks to beautify the
game. The boss was programmed to make the screen shake, turn white, and explode when he is
defeated. The player then flies off the screen and a screen comes up to tell you that have won.
Finally, throughout the project the graphics were made using 3d models in blender. This was
done by modeling the ships in 3d and then rendering them as .bmp files on black backgrounds.
This would allow the rendered images to be set as the image for the ships in 2d in our game. The
rest of the development process required play testing to find bugs which were then found in the
code and fixed.

Results
The program has two predefined modes, arcade and survival. In arcade mode, the user
controls a space ship that fights several enemies. Each of them has their own way of moving and
fighting that synergize with one another to a certain degree. The enemies are classified based on
color. Red enemies will stay close to the player and fire shots in a spread pattern. Blue enemies
hide in the corner and fire 3 fast shots in a burst. Green enemies stay away from other ships and
fire slow moving shots quickly that make dodging difficult. The boss combines elements from all
of the enemies to create a real challenge. There are six different difficulty levels, each of which
changes various things in the program, such as how fast the enemies fire and how long you stay
invincible after you respawn. Once the user has progressed past all the waves and beaten the
boss, the user wins the game. If the user dies 3 times, using all of their lives, a game over screen
appears and the user can retry or quit.
In survival mode, randomly generated lasers fall from the top of the screen and the user
must survive until all 3 of their lives are gone. The shots will begin to get faster as the game
continues, and then more and more shots will fall until the game becomes nearly impossible to
134

survive in. The goal is to dodge as many shots as you can. There is no high score feature, so the
user only plays against him- or her- self.
In all of the modes, the player controls the ship using the arrow keys or the WASD keys,
and the space key to fire. The user clicks on buttons in the various menus to navigate to the
various modes and instructions. Overall all of these features mentioned have been implemented
with solid stability so far.
Analysis
The goal of our project was initially to create a game somewhere in between Galaga and
Raiden X. Furthermore, we wanted to make it with multiple levels and power ups. When
making our game we would talk about a feature that would be implemented and each take a
specific file necessary to work to implement the feature. A good chunk of the time two of us
would work together on the same computer to write the code for a section when we werent able
to work on three separate files. The reason for working on separate files at the same time is that
the synchronization software we used would have problems if two people modified the same file.
Not only this, for files such as the ship class, it was easier to do it as a separate file so it could be
easily imported into all of the different specific ship files for use.

Discussion
Throughout our development process we were able to create and implement various
features in our game which fulfilled the majority of our goals for the game. We did more than
make a playable game though, implementing a second gameplay mode, polished menus, and
instructions. Unfortunately we were unable to implement power ups, high scores, or multiple
levels.




Kounselor Kombat

135

Final Report

Submitted to
The Faculty of Operation Catapult LXXXVIII
Rose-Hulman Institute of Technology
Terre Haute, Indiana



by
Group 15
Scott Harris Homestead High School
Fort Wayne, Indiana
Richard Ludwick IU High School
Indianapolis, Indiana
David Liu Huazhong University of Science and
Technology
Wuhan, Hubei, China
July 27, 2010


Introduction
One of the worlds largest problems is that of fun deprivation. The world seems to have
run out of fun. Whether people are watching television, going to clubs, or playing sports, they
can never seem to become satisfied. Fortunately, this horrible disease can be cured. Python is a
general-purpose high-level programming language that can be used in combination with a cross-
platform set of Python modules called Pygame to create video games that induce an ecstasy-like
fun.
136

Three catapult students used this ingenious programming language to create the infallible
cure to fun deprivation. In Python, these programmers were tiny gods, omnipotent in their
coding. From their trials and toil spawned a game that has been said to be more fun than
Disneyland. This incredible god-spawn is Kounselor Kombat. These tiny programming gods
have captured the essence of each counselor of Operation Catapult and brutally tossed them
inside of a virtual abyss. In this abyss the counselors must fight their way through each other to
achieve glory, honor and bragging rights.
Now, this game may seem awesome, maybe even unbelievable, but if you continue to
read for the next few pages, you too can know the secret of this nearly impossible task.
The Preparation
Before entering the Computer Science lab Richard Ludwick and Scott Harris had next to
no programming experience. Luckily the sage-like Dr. Anderson and his sidekick Nathan were
able to provide the both of us with enough background knowledge to program this game. During
the first week of their experience they learned the basics of the Python language. They used
zellegraphics to create basic Python codes and images. As the week progressed, all students
clearly progressed in their abilities to program. They first learned how to make a window appear,
then make words on the window. Eventually they started to create shapes from their code. After
creating these complex shapes that draw themselves with each click, they worked on turning
these shapes into buttons that make text appear. They learned about events, lists, classes,
functions, objects, and other common Python applications.
David however had experience in other programming languages. He has had an
intermediate amount of experience with programming languages such as C and Java. This
experience helped David with learning python as the languages are similar in most aspects. He
created shapes and buttons just as Scott and Richard had, but used these exercises to learn the
new syntax of this programming language and apply old knowledge from C and Java to expand
his knowledge of this new language.
The Conception
While listening to the opening ceremonies of Operation Catapult at Rose-Hulman, Scott
Harris was hit with inspiration. One of the example games for Python projects was a game where
students could launch water balloons at their counselors. This inspired Scott to create something
more. He thought that if his group could take pictures of every counselor in multiple fighting
positions, they could create a game where the counselors would fight. Pictures of the actual
Rose-Hulman campus could also have been taken to provide an environment for the fighters.
The Advantages of Teamwork
After the conception of the idea and initial training, David, Richard and Scott got together
to create Kounselor Kombat. They decided to split the project into three parts, the initial pages,
the photos of the counselor, and the actual fighting part of the game. Richard and Scott got to
work on creating the title page that would contain a start button and the instructions to the game.
They found that they could easily place the title and make the start button appear, but
programming the button to work was quite a task. Luckily they relied on each others skills and
on inquiring with the professor to find a quick solution. They could not understand how to track
137

the mouse to find where the user clicked but by using a line of code that recognizes when the
mouse is in a rectangle, the solution was quite easy.
def pushbutton( but t on) :
whi l e Tr ue:
f or event i n pygame. event . get ( ) :
i f event . t ype == MOUSEBUTTONDOWN:
x, y = event . pos
i f but t on. col l i depoi nt ( x, y) :
st ar t Scr een. f i l l ( pygame. Col or ( "black") )
r et ur n
sl eep ( 0. 2)
By this time, David had completed coding for making characters appear on screen and making
them move to different fighting positions.
The Character Select Screen
After the title screen was working properly, they programmed it to go to the character
select screen. They wanted the character select screen to have all eleven counselors displayed in
their own rectangles. When a counselor is clicked, he or she would be selected as either player
one or player two. This screen would control which images would display in the actual game.
On the Catapult website, Scott found a picture of all the counselors together for seventies
day. He quickly saved this picture and used the paint program to separate each counselor. He In
order to insert the characters into the character select screen Scott and Richard then realized that
Darcie was not in this picture of most counselors. Scott found a picture of Darcie on the website
and used that one instead.
Scott and Richard named each counselor using K and then a number 0 through 10.
Because of the naming, a loop could easily be created.
def loadpics( ) :
kpi cs = [ ]
f or i i n r ange( 1, 12) :
kpi cs. append( pygame. i mage. l oad( 'K'+st r ( i ) +'.JPG') )
st ar t Scr een. bl i t ( t ext 4, ( 10, 10) )
r et ur n kpi cs

def drawpics( kpi cs) :
f or i i n r ange( 11) :
st ar t Scr een. bl i t ( kpi cs[ i ] , ( i *90, 100) )
Loadpics() is a function that loads every K image into the program and drawpics() blits each
of the pictures onto the screen in their appropriately spaced position.
Scott, Richard, and David then used the spacing to make a function that would choose the
character based on where on the screen the user clicks.
def chooseChara( char aLef t , char aRi ght ) :
char aRi ght = - 1
char aLef t = - 1
138

whi l e Tr ue:
f or event i n pygame. event . get ( ) :
i f char aLef t ! = - 1 and char aRi ght ! = - 1:
r et ur n [ char aLef t , char aRi ght ]
i f event . t ype == MOUSEBUTTONDOWN:
x, y=event . pos
#pr i nt ( x/ / 90, y)
i ndexByUser = x / / 90
i f char aLef t == - 1:
st ar t Scr een. bl i t ( t ext Kounsel or s[ i ndexByUser ] , ( 23, 530) )
pygame. di spl ay. updat e( )
char aLef t = i ndexByUser
el se:
st ar t Scr een. bl i t ( t ext Kounsel or s[ i ndexByUser ] , ( 750, 530) )
pygame. di spl ay. updat e( )
char aRi ght = i ndexByUser
Player one is represented by charaLeft and player two is represented by charaRight. Each is
set to -1 and when a character is clicked, the program finds the x value of the click across the
screen and divides it by the distance that each characters rectangle takes up. This gives the
program a number 0-10 that is the same number that the image is set to (Kx). Then, based on the
number, the name is placed in the bottom left part of the page. Player ones turn is then used up
and player two gets to choose. When the player chooses, the characters name is displayed in the
bottom right. They then used the pushbutton function to create another start button on the
button that, when pressed would start the game.
The Pictures
In order to make the counselors into the characters, photos of every counselor had to be
taken. Scott used some project time to take pictures of Chris and Darcie in different positions.
Pictures were taken of the counselor in ready position, punching, kicking, jumping, crouching, in
winning position, losing position, and performing a special move. Scott had to find every
counselor and organize a time to take these pictures. During an intramural for softball, Scott took
pictures of all other counselors except Alisa, for she was running the intramural. These pictures
could not, however, be used in their primal state. Richard, Scott, and David had to delete the
background out of every image in order to create useable images. David used Microsoft
PowerPoints background remover to easily remove his characters backgrounds while Richard
and Scott cropped the characters using Paint.net. They completed the cropping for the five basic
poses rather quickly and could then implement them into the program. David defined each stance
using a single line of code.
st and_l ef t =
pygame. i mage. l oad( 'chara_img\\lchara\\chara_'+st r ( l ef t Char a) +'_1.png')
Each pose had its own name. Scott then took pictures of Alisa and the character pictures were all
taken.
Fighting
The fighting was accomplished by David. He gave each of the characters a status that
starts out as stand and can change to different statuses such as kick by pressing buttons.
139

i f event . key == K_c:
i f count Begi n1 == Fal se:
char aSt at us1 = 'kick'
count Begi n1 = Tr ue
i f det ect At t ack( char aSt at us1, char aSt at us2,
di st ance) :
heal t hPoi nt 2 - = 10
When the button c is pressed, the status of kick is assumed, which blits the image of kicking
into the game and then switches back to stand. If the character is close enough to the other
character, the other character will lose one unit of his or her heath. The health system is actually
quite simple. Each player starts out with 10 health, represented by a rectangle at the top of each
characters side of the screen.
heal t hBar 1 = pygame. Rect ( 50, 50, 250/ 100*heal t hPoi nt 1, 30)
heal t hFr ame1 = pygame. Rect ( 50, 50, 250, 30)
pygame. dr aw. r ect ( gameScr een, pygame. Col or ( 'yellow') , heal t hBar 1)
pygame. dr aw. r ect ( gameScr een, pygame. Col or ( 'yellow') , heal t hFr ame1, 5)
The health bar starts as being 200 pixels long, then is divided by the amount of health that the
character has to decrease the bar in size.
Winning the Game
All of this coding and gaming is spectacular, but is quite pointless if a user cannot be the
win. David developed a simple code based on the numbers 1-4 to tell the winner of a game.
def judgeWinner( hp1, hp2, t i meLef t ) :
i f t i meLef t <= 0:
i f hp1 > hp2:
r et ur n 1
el i f hp1 < hp2:
r et ur n 2
el se:
r et ur n 0
el se:
i f hp1 <= 0:
r et ur n 2
el i f hp2 <= 0:
r et ur n 1
el se:
r et ur n - 1
The first part of the code relies on the timer. A timer was developed that counts down from a
minute to zero. This code detects if the timeLeft or time until finish has hit zero. Once it does,
the character that has more heath wins if character one has more heath, it returns 1 which is
useful later in the code. If character 2 has more health, it returns 2. If they have the same, it
returns 0. If a character has zero health, the opposite characters number is returned.
David then used the numbers generated by the judgeWinner function to show the
winner.
bi gFont = pygame. f ont . SysFont ( "Times New Roman", 80)
decl ear Text = ''
140

j udgeResul t = j udgeWi nner ( heal t hPoi nt 1, heal t hPoi nt 2, GAME_TI ME-
( cur Ti me- st ar t Ti me) )
i f j udgeResul t == 1:
# pl ayer one wi ns
decl ear Text = "player 1 wins!"
gameScr een. bl i t ( wi n_l ef t , [ 100, 300] )
gameScr een. bl i t ( l ose_r i ght , [ 500, 300] )
This code detects if the number returned in judgeWinner was 0, 1, or 2. If 1 is detected, player
1 wins! is displayed on the screen. It also displays the winners winning image and the losers
losing image. The game then waits for three seconds and returns to the start screen for the game
to be replayed.
Improvements
The team wanted several other things for our program that the team did not have enough
time for. The team wanted each character to have a special move, but that wouldve been a large
hassle to program and take pictures for each character. The team also wanted more fluid motions
and not just quick position changes. The team wanted for the characters to turn around if the
other character is passed. One thing that seemed impossible was the development of computer
characters. The team thought that if the team let two characters control the game, it would feel
more user-friendly and include more people. The team also couldve programmed an image for
every time a character is hit. This way, each character does not seem to be made out of steel in
the way that they do not react to being hit. The team forgot, however, to take pictures of this pose
and therefore could not go back in time to take pictures of the counselors in this pose while
wearing the same clothing as on that day.
Conclusion
Programming with python has been quite an interesting experience for the team. For
Scott and Richard, working with a Chinese student has taught us much about work ethic and
diligence. It has also taught us much about international relations. For David, working with
Americans motivates his innovation. It made David feel younger and relieved his stress to be
working in a less tense environment. The Python experience has shown Richard that computer
programming wasnt exactly the most entertaining activity and has shown David and Scott that
computer programming could be a major option in his future and has shown.

O257
brackin@rosehulman.edu

141

WALKONWATER

FinalReport

Submittedto

ThefacultyofOperationCatapultLXXXVIII

RoseHulmanInstituteofTechnology

TerreHaute,Indiana

By

142

Group17

AndrewCooke LakeBraddockSecondary
Burke,Virginia
BrianNelson NaplesHigh
Naples,Florida

July27,2010

143

Ourgroupcametogetherforonereasonweallwantedtohaveafuntimemakinga
devicethatcouldfloatandmoveonthewaterwell.Thegroupaonepointwascomprised
offourpeopleandnowithaswhittleddowntojustonepersonfordifferentreasons.Weall
cameupwithgooddesignsforthatprojectandthendecidedonthepaddleboatdesignfor
asimplereasontobeatthefastesttimeofsession1.Wewantedthemaximumspeedwe
couldgetsothepaddleboatseemedreasonable.

Thedesignconsistedofthreewheels:oneforthemovementandtwoforthe
propulsionsystem.Wealsowantedtokeepthewalkingpartoftheprojectbutintheendit
wasnotasmuchofawalkingmotionaswehopedfor.Itendedasmoreofaslowpushwith
1footorevenyourhands.Forthemovementpartoftheprojectorthedesignwejustused
bikechainsandgearsbutwithourdesignittookalotofbikechainbecauseourprojectis
aboutninetotenfeetlong.Soourprojectwasahasslemovingaroundbecauseitbarelyfit
throughthedoorandittookfivepeopletomoveoutofthebuildingandtoSpeedLake.The
propulsionsystemontheprojectisveryeffectivebutsometimesitspinsalittletofatson
oneofthewheelsandthechainfallsoffwhenitisnotinwateratleast.Wealsodonthave
abreakonthedevicesogoingalittlefastcanbeaproblemalsothebikechaincanonlyget
sotightonasideforadevicethisbigandcanveryeasilyfalloff.Thehardestpartofthe
projectwastomakeitfloatevenlyoneachsidesoweputintwo55gallonplasticdrums
andeachonesupportsupto450poundsonwaterplussomestyrofoamonthefrontand
backtohelpstabilizeitfromleaningforwardsandbackwards.

Theprocessconsistedofgatheringasmuchwoodaswepossiblycouldfromallthe
dumpstersaroundcampus.Bythethirddayherewehadcomeupwiththatpaddleboat
designsowestartedbuildingthewheelsforourdesign.Thewheelswerenotperfectly
evenbutwedidntcareitcouldstillrollsmoothly.Afterthetwobiggerwheelswere
completedwethenstartedonthesmallerwheelforourmovement.Onceallthreeofthe
wheelswerecompletedwedecidedhowfarapartwewantedthembecauseweknewthat
weweregoingtoneedtogetchainenoughtowrapallthewayaroundthemiddlewheelto
thebackwheels.Alsowebuiltaframethatwecouldattachedthewheelstoandmake
anotherthatweputotopoftheoriginalframesothatwecouldputthatbarrel/drumson
forourfloatation.Finallynearingtheendofthebuildingtimethatwehadwegotourgears
andchainswhichwasthelastthingweattached.
144


Thedesignoftheprojectwasinfactverysimpleanddidnottaketomucheffort
intoputtingittogetherbutitdidtakealotofwoodandtimebecauseofhowbigthe
projectis.Thefirstdayofthegroupprojectplanningourgroupwentstraightoutbackand
tothedumpsterandgrabbedasmuchwoodaswe
couldbecausewedidntwanttohavetospendany
moneyontheframingoftheproject.Oneofour
biggestfindswasthesupplycrateoutbehindthat
building;ittookus2hourstodismantlefordecent
pieceofwood.Intheendmostofourmoneywentto
buyingone55gallonfromandthebikechainssonota
singlepennywasspentonthewoodwhichiswhatwe
aimedfor.Ourgroupplannedonputtingonhandrailingforthedevicetoobutthatnever
happenedbecauseintheendwefiguredwejustdidntneedthem.Itwasthesamething
withthecasterstokeepthegearsatadecentdistancefromthewoodsoitwouldntrub
andmakethechainfalloffbutweneverhadaproblemwithitsowejustleftthemoutand
wewererunningoutoftimebeforetestingitsowedidntwanttoputthemin.therewere
pointsintheprojectwerewestruggledtofindsomethingtodoevenifitwasthesimplest
tinglikemakingacutonapieceofwood.

Group17putbeatingthesession1timeanoverallgoal.Weheardthatthesession1
timewasprettyfastsothatswhywewantedtobeatit.Wewouldhavealsolikeso
competitionbutwehadnoneunlikesession1wheretheyhad3groupsmakingtheproject.
Itwouldhavemakethe2weeksevenmorefuniftherewassomeontoraceagainstinthe
endlikethehovercraftgroups.Wehadalotoffunintheprocessofmakingtheprojectand
wewerelookingforwardtogoinginSpeedLaketheentiretimeconsideringthepoolwas
closetheentiretimewewereoncampus.Weneverdidcalculatethebuoyancyofthe
projectwejustfigureditwillfloatwhenweputitinthewaterbecauseitdoesntweigh900
poundsandthatwhat2drumsholdup.Withtheamountofpowerwegetfromeachofthe
wheelsthegroupwasconfidentthattheprojectwouldmoveonthewaterfast.Alsowe
didnthaveascalelargeenoughtoactuallyweighttheentireprojectandwedidntwantto
takeisapartintopartstoweightitbecauseIwashardenoughtoputtogethersoimagine
puttingittogetheragain.

145

Themostdifficultpartoftheprojectwaswaitingforthemostimportantofallour
supplieswhichwerethebikegearandthe
bikechainsbecauseweneedsomuch
bikechainforourproject.Ifwenevergot
thechainwewouldbetryingtofigureout
howtomakeourprojectmovebutwegot
itjustintimetogetitontheprojectand
totestittomakesureitwouldwork.Also
theamountofchainweneededwas
outrageousbecausetosizeoftheproject
wassomassive.Wehadalotofhelpin
buyingthesuppliesweneeded.Thanksto
Dr.Robinsonwemanagedtogetallofoursuppliesandareentireprojectworkingbefore
thedaywehadtotestit.Thegroupwantedbuyabunchofspraypaintandmakethe
projectlookreallycoolwhenitwouldmovethroughthewaterbutweranoutofcashand
timesowenevergottorunouttothestoreforpaintpluswewouldhadtoletitdryfor
awhileandwejustdidnthavethetimeforthat.

Ourgroupdidverylittletonoresearchwejustthoughtofideaanddrewadesign
foritthenturneditintoourproject.Wewerealwaysworriedthatwerewouldonlybe
stuckwithonly55drumfortheprojectandthenwewouldhavetoredesignourproject
sothenwewouldonlybefloatingwiththebarrelinsteadoftwo.Thatwouldhave
complicatedourprojectalotthenwewouldbeworryinghowtokeepitfloatingevenly.
Wearestillveryworriedabouthowhigh/lowtheprojectisgoingtofloatinthewalk
becauseweneverdidgettotesttheprojectbeforethedaywehavetodothe
demonstration.Whentheprojectissuspendedinairwhilesittingonchairsinthe
classroomthenitworksverywellitcansupportareweightandthewheelspinatagood
rate.Forthemostpartbothoftheouterwheelsspinataboutoneandahalfrevolutions
perrevolutionofthemiddlewheelwhichshouldgiveusenoughtorquetomove
throughthewateratadecentpaceoncewegetmoving.

Therealquestionisdiditwork?Wellyesitdidbutitdidbreakalsobecausewe
attachedthebarrelsonthetopoftheframeinsteadofthebottomoftheframe.Inthe
enditwasstillalotoffuntestingtheproject.
146

ConstructedWetlandsforStormwaterRunoffTreatment

FinalReport

Submittedto
TheFacultyofOperationCatapultLXXXVIII
RoseHulmanInstituteofTechnology
TerreHaute,Indiana

by

Group18

BrettWalles HenryClayHighSchool
Lexington,Kentucky
GrantBishop EastsidePreparatorySchool
Redmond,Washington

July27,2010

Background
147

Aconstructedwetlandisanartificialwetlandmadeforthepurposeoftreatingwaste
water.ConstructedwetlandshavebeenusedintheUnitedStatesinthepast40yearstotreat
severalclassesofwastewater
1
:domestic(sanitary)sewage,stormwaterrunoff,and
agriculturalrunoff.Inparticularweinvestigatedtheuseofaconstructedwetlandfor
treatmentofstormwaterrunoffasanalternativetothestandardmethodsofnotreatmentor
combiningwithdomesticsewage.
Stormwaterrunoffmaycontainavarietyofcontaminates,primarilyfromrunofffrom
impervioussurfacewhichposesaprobleminthatwaterfromarelativelylargeareamaybe
funneledintoamuchsmallersystem.Thiscanbemoreproblematicwhencombinedwiththe
firstflush
2
effectinwhichthefirstfewmillimetersofrainduringastormeventmaywash
awayamajorityofthepollutants.Thishastheeffectthatmostpollutedwatermayarriveata
systemwhenitisleastabletotreatitduetooverflowconditions.
Formaximumcleaningeffect,watermustflowslowlythroughtheconstructedwetland
tomaximizeretentiontime,thetimewaterspendsinthesystem,andthusthetimeitspends
beingtreatedthroughphysical,chemical,andbiologicalprocesses.Thiswassomewhatofan
issueforusasflowratesdidnotscalewellwithoursmallsize.Withatotalwetlandwater
volumeofapproximately100liters,andanoutflowandinflowratebetween.05and.2L/min,
retentiontimerangedfromeighttoover20hours.Evenatthemaximumretentionratewitha
minimalflowratethesmallscaleofourwetland,bothinphysicalsizeandoperatingtime,
preventeditfromarchivingmorethanthelowerendoftheretentiontimesofrealconstructed
wetlands,whichrangefromhourstoafewweeks
3

Pollutants

Pollutantsinwastewater,includingstormwaterrunoff,includenutrientssuchasnitrogenand
phosphorouscompounds,varioussuspendedsolids,metalandoils.Nitrogenandphosphorous
existinseveralcommonformsinwastewater,andwillnaturallybreakdown.Removalof
nitrogenandphosphoroustakesplacethroughchemicalinthesoilandwater,andmicrobial
process,anduptakebyplants.
4
Nitrate,whichwemeasured(N0
3
-
-N),followsthegeneral
pathbelow:
0iganic Nitiogen NB
4
+

NB
4
+
+0
2
N0
3
-

N0
3
-
N
2

Ourmeasuresofnitrateshowedthedifferencebetweenthetreatedanduntreated
water.ThegoalofoursysteminrespecttonitrogenistobreakNB
4
+
andN0
3
-
downintoN
2
.
Thegoalofaconstructedwetlandisconvertthesecompoundssothatwhentheexitthesystem
theywillnotnegativelyimpactwaterquality.Highlevelsofnutrientsleadtoahighbiochemical

1
(EPA,1999)
2
(Lee&Bang,2000)
3
(Shutes,Revitt,Lagerberg,&Barraud,1999),(Vymazal,Greenway,Tonderski,Brix,&Mander,2006)
4
(EPA,1999),(MetropolitanCouncil,2001)
148

oxygendemand(BOD).Theavailabilityofnutrientsleadstoanincreaseinaerobicbacteria
whichconsumedissolvedoxygeninthewater.Fishandmanyotheraquaticorganismsrequire
dissolvedoxygentosurvive.

Constructionofourlabscalewetland

We designed our constructed wetland after researching various sources such as the EPA.
Constructed wetlands have three main components: an inlet that allows the water to settle and
solids to sink to the bottom, the main area that contains all of the plants and organisms, and the
outlet that discharges the water from the wetlands. Two gravel berms separate the three sections
and prevent large particles from escaping the system. Layers of pea gravel, sand and soil make
up the composition of the treatment area which is planted with cattails (Typha Sp.), algae and
duckweed (Lemnoideae). The diagram at the end shows the layout of our wetland.
We collected all the aquatic life from Hawthorn Park, which is located just outside the
Rose-Hulman campus. Our lab-scale wetland took the shape of a 50-gallon storage bin. We
drilled a hole for the outlet pipe and began layering the soil. Then came the hard part: In the
scorching Indiana heat, we carried buckets and buckets of soil, cattails and water back and forth
from the Hawthorn wetland to our wetland. Once we planted our wetland, we allowed it to settle
and grow for a few days. We used water from Lost Creek to simulate runoff water because that
is where much of the rainwater drains to on the Rose-Hulman campus. We rigged up a
siphoning system for the inlet with some buckets and a plastic tube. After a few days of letting
water flow through the system, we began testing the inlet, main part and the outlet with various
water quality tests.

Testingourscalewetland&Results

Toassesstheefficacyofourwetlandwetookseveralmeasurementsofwaterquality:pHand
alkalinity,dissolvedoxygen,nitrates,andBOD.Withinourlimitedscale,bothinphysicalsize
andtimeframe,theconstructedwetlandcouldnotbeexpectedtoperformideally.However,
weobservedsomeimprovementsinnitratesandBOD.
ThepHanddissolvedoxygenmetersweresimpleprobetestsandshowedthatwater
qualitywasimprovingasthewaterpassedthroughthesystem.Thealkalinitytestwasa
titrationwithsulfuricacidandshowedmixedresults.Becauseofthelimitedamountoftime,
wedidaBOD
3
(threeday)testinsteadofthestandardBOD
5
.AnitrateviaaUVspectrometer
testalsopointedtotheconclusionthatthewaterqualityhadindeedimprovedafterpassing
throughourwetland.
Thedatawecollected,influentfromLostCreek,andeffluenthavingslowlyflowed
throughourscalewetland,aresummarizedinthefollowingtables:
149

Data: pH Data: Nitrate


pH via pH meter Nitrate as mg/L NO
3
-
-N
Date: 22-Jul Nitrate via UV spectrometer
Time: 10:00 Date: 22-Jul
Reading IN MID OUT Time: 1:00
1 7.284 6.85 6.82 Reading IN MID OUT
Date: 22-Jul 0.3 N/A 0.0
Time: 16:30 Date: 23-Jul
Reading IN MID OUT Time: 1:00
1 7.229 7.084 6.937 Reading IN MID OUT
2 7.359 7.030 7.016 0.3 N/A 0.1
3 7.498 7.387 7.041
4 7.443 7.258 Data: BOD(3)
5 7.531 7.192 10, 20, and 50 mL sample/300 mL, water collected 7/23
Date: 23-Jul IN
Start
dissolved
O
2

End
dissolved
O
2
difference BOD
Time: 9:20 10 8.88 7.95 -0.93 27.90
Reading IN MID OUT 20 8.91 8.20 -0.71 10.65
1 7.392 N/A 6.963 50 8.82 7.82 -1 6.00
2 7.493 6.97 0
3 7.523 6.974 OUT
Start
dissolved
O
2

End
dissolved
O
2
difference
4 7.388 6.981 10 8.90 8.35 -0.55 16.50
20 8.52 8.00 -0.52 7.80
Data: Alkalinity 50 8.32 7.22 -1.10 6.60
Alkalinity via titration (acid & indicator)
Measured as mg CaCo
3
/ L
Date: 22-Jul
Time: 10:30
Reading IN MID OUT
309.4 N/A 253.8
313.0 314.0
Date: 22-Jul
Time: 10:30

Reading

IN:inflow
MID:wit
OUT:out

T
andareo
However
ourcase,
Creek.
p
effluentf
pHconsis
eitherwa
D
dropped
T
organism
duckwee
observed
havebee
O
reducing
this,asb
lowlevel

Conclusio

C
construct
showedi
time,orw
observed

IN
317
w
hinthesyste
tflow
otalsuspend
oftenanindi
r,something
,thewaterl
Handalkali
fromoursys
stentlydecr
ay.Alkalinit
Dissolvedoxy
throughou
hemostsign
msinthesyst
edreproduce
dmanyinver
enseen,and
OurBODtest
theBOD
3
fr
othnitratet
.
on
onstructedw
tioncostand
ittobeeffec
workedona
d.
MID O
N/A
em
dedsolids(T
icatorofwat
gassimplea
eavingours
nitywherem
stem,rather
easedthrou
ymostlyrem
ygenlevelsf
rsystem,ac
nificantindic
tem.Theca
edrapidlyan
rtebrateswi
theissuesw
tshowedtha
rom27.9to
testsshowed
wetlandsha
damuchlow
ctiveinremo
alargerscale
OUT
334
TSS)referto
terquality.
stheappea
systemwasn
measuredpr
rthanlookin
ghthesyste
mainedcons
romLostCre
causeforcon
catorthough
attails,duckw
ndquicklyco
thinoursyst
withdissolve
atoursystem
16.5inthe1
dareductio
vebeenuse
wermainten
ovingnitrate
e,morebene
theamount
Duetotime
ranceofthe
noticeablyc
rimarilyton
ngforaparti
em,butnoti
stantordrop
eekcamein
ncern.
hmayactua
weed,andot
overedthee
tem.Hadw
edoxygenm
mwassome
10mLdilutio
ntovirtually
edtosuccess
nancecost.
e,BOD,and
efitstowate
tofparticula
econstraints
ewatercanp
learerthant
otedifferen
icularformo
inawaytos
ppedslightly
athealthyl
llyhavebee
theraquatic
entiresurfac
wehadmore
mayhavebee
ewhateffect
onbottle.Th
ynone,alth
sfullytreatr
Ourtestofo
visiblesolid
erqualitywo
atessuspend
swedidnot
provideinsig
thatenterin
ncesbetween
ofpollution
showsignific
y.
evels,butco
enthevisible
cplantsallsu
ceofthewat
time,more
enresolved.
iveatremov
henitrateda
oughstartin
runoff.They
outlabscale
s.Hadweh
ouldlikelyha
dedinthew
measureth
ghtintothis
ngitfromLos
ninfluentan
inLostCree
cantconcern
onsistently
ehealthofth
urvived.The
ter.Wealso
growthmig

vingBOD,
atacomplem
ngatanalrea
yhavealow
ewetland
hadalonger
avebeen
150
water,
em.
:in
st
nd
k.
n
he
e
o
ght
ments
ady
er
151

Bibliography

EPA.(1995).AHandbookofConstructedWetlands.U.S.EnvironmentalProtectionAgency.
EPA.(1999).FreeWaterSurfaceWetlandsforWastewaterTreatment:ATechnologyAssessment.U.S.
EnvironmentalProtectionAgency.
EPAOfficeofWater.(2004).ConstructedTreatmentWetlands.U.S.EnvironmentalProtectionAgency.
Lee,J.,&Bang,K.(2000).CharacterizationOfUrbanStormwaterRunoff.WaterResources,17731780.
MetropolitanCouncil.(2001).ConstructedWetlands:StormwaterWetlands.InStormwaterBest
ManagementPracticesforColdClimates.Minneapolis&St.Paul:BarrEngineeringCompany.
Shutes,R.B.,Revitt,D.M.,Lagerberg,I.M.,&Barraud,V.C.(1999).Thedesignofvegetative
constructedwetlandsforthetreatmentofhighwayrunoff.TheScienceoftheTotal
Environment,189197.
Vymazal,J.,Greenway,M.,Tonderski,K.,Brix,H.,&Mander,.(2006).ConstructedWetlandsfor
WastewaterTreatment.InWetlandsandNaturalResourceManagement(pp.6996).Springer
BerlinHeidelberg.

152

SOLARCOOKER

FinalReport

Submittedto

TheFacultyofOperationCatapultLXXXVIII

RoseHulmanInstituteofTechnology

TerreHaute,Indiana

By

Group19
153

SydneyGard CentralHighSchool
Omaha,Nebraska
NicholasPannellFarragutHighSchool
Knoxville,Tennessee

July27,2010
154

192

Introduction

Approximatelytwobillionpeoplearoundtheworldarecurrentlywithoutelectricity.Yet,
millionsofpeoplecouldnoteventhinkoflivingeverydaywithoutelectricity;howwouldtheycook
withoutameanstopowertheirelectricovensandstoves?Therearecurrentlymanyalternativesto
electricstovesandovens,including:woodburningstoves,naturalgas,andsolarpower.Solarpowerhas
manydifferentapplicationsinlifetoday;itcanbeusedtocreateheatbytrappingthesunsraysorasa
meansofcreatingelectricityfromtheuseofasolarcell.Solarcookingisaverypracticaluseofsolar
energyandcanbeusedasareplacementforelectricstovesinthirdworldcountries.
Therearethreecommontypesofsolarcookers;heattrapboxes,parabolic(alsocalledcurved
concentrators),andpanelcookers.Parabolicsolarcookersworkbyreflectinglightoffofaconvexdiskto
afocalpoint,whichisusuallythebottomofthecookingcontainer.DuetotheEarthsrotationaround
thesun,closeattentionhastobepaidwhencookingbecausethefocalpointwillmoveasthesuns
positionintheskychanges.Parabolicsolarcookerscanreachheatssimilartothoseofaconventional
oven;however,frequentadjustmentsandcloseattentionarerequiredforsafe,effectivecooking.
Anotherdownfallofparaboliccookersistheycanbecomeveryhotandcauseburnsanddamageto
eyes,ifappropriateprecautionsarenottaken.
Wedecidedtobuildaparabolicsolarcooker,ouroriginalgoalwastoboilonequartofwaterin
thirtyminutesorless.However,asconstructiontookplaceitbecameevidentthataonequartpot
wouldnotbeavailable.Withthatinmindthegoalchangedtoboilingtwocups(halfaquart)ofwaterin
fifteenminutesorless.Lateronduringtheconstructionprocessitwasalsodecidedthatadditional
cookingtestswouldalsobeperformedincluding:makingsmores,cookinghotdogs,andevenbaking
cookies,usingthesolarcooker.

Construction

Ourfirstthoughtsonhowtobuildaparabolicsolarcookerinvolvedcreatingeverythingfrom
scratch,includingtheconcavedisk.Afterresearchandbrainstorming,thedecisionwasmadethat
creatingeverythingfromscratchwouldrequiretoomuchtimeandexceedthesetfortydollarbudget.It
wasthendecidedtousean8footdiametersatellitedish,coatedinMylar,ashinyreflectivesubstance,
astheconcavedisk.WefoundthedishinsideRotzLab,whilebrainstormingonwhattouseasour
155

concavedisk.Awoodenstandwascreatedthatwouldholdthedishatafixed142angle.Apostwitha
retractablearmwasthenconnectedtothefrontofthewoodenstandtoaccountforthemovingfocal
point.
Earlycalculationsshowedthatthefocalpointofthedishwouldbe39.6centimetersabovethe
centerofthedish.Asteststookplaceitwasdiscoveredthatthiscalculationwasonlysometimes
correct.Whilethefocalpointremainedat39.6centimetersfromthecenter,itwasonlyabovethe
centerofthedishwhenthesunwasdirectlyovertopofthesolarcooker.Asthesunspositionmovedin
theskythefocalpointwouldmoveitselfaroundthedish,attimesbeing39.6centimetersdiagonally
fromthecenter,insteadofabovethecenter.
Aretractablearmwasusedtoholdthepotabovethefocalpointandmoveasthefocalpoint
moved.Duringtestnumberthreeofthesolarcooker,thetemperatureatthefocalpoint
193

becometoohot,andmeltedtheendofthePVCpipe,whichtookusbacktothedrawingboardfor
redesign.AmetalrodwasthenattachedtotheendofthePVCpipeandholesweredrilledthroughthe
rodsothatthepotcouldbeboltedtotherod.

Results

Theveryfirsttestdoneinvolvingthesolarcookerfailed.Thistestwasmerelytestinghowsturdy
thestandwasandifitwouldfallapartornot.Aftersettingthedishontopofthewoodenstand,it
collapsed.Thusitwasdiscoveredthatthestandwasinadequateandneededredesigning.Bottom
supportbeamswereaddedtomakethestandmorestablewhensittingonflatgroundandallnailswere
replacedwithwoodscrewsasawaytoholdthestandtogether.
Afterredesigningwascomplete,asecondtestwasdone.Thistestresultedintheconfirmation
ofasturdysupportsystemforthedishandalsogaveahighestrecordedtemperatureofapproximately
119C.Duringthistestboilingofwaterwasnotdone,sonotimewasrecordedforboilingtime.
Thethirdtestfollowedapatternsimilartothefirsttest,whereitwasdiscoveredthatsomepart
oftheoriginaldesignwouldnotworkforthepurposeofasolarcooker.ThePVCpipethatheldthepot
meltedbeforethewaterhadtimetoreachaboilingpointandthepotwentcrashingtotheground,so
onceagainnoboilingtimewasrecorded.However,anewhighesttemperaturewasrecordedat148C.
Thefourthtestwastheonlytestwhereallaspectsweresuccessful.Anewhighesttemperature
wasrecordedat178.8C;however,thistemperaturecouldnotbesustainedduringtheentireboiling
time.Ittookeighteenminutesandfivesecondstobringtwoandahalfcupsofwatertoaboil.Once
156

boiling,thepotoverflowedsonoboilingtemperaturewastaken;howeveritisaknownfactthatwater
boilsat100C,soitwasestimatedthatthewaterwasat100Cwhenthepotwasremovedfromthe
focalpoint,eventhoughitcouldhaveactuallybeenhotter.Afterremovingthepot,temperature
immediatelydroppedto97Candcontinuedtodrop.Althoughittookmorethatfifteenminutestobring
thewatertoaboilingpoint,thistestwasstillconsideredsuccessfulduetothefactthatthewater
boiled.
Aftergettingonesuccessfultestoutoffour,itwasdecidedthatafuntestwasneeded.Thefun
testwasmakingsmores,usingthesolarcooker.Insteadofthemarshmallowsbrowningastheywouldif
overafire;theymelted,whichseemslikealogicalresult.Amentalnotewasthenmadenottohold
themoverthecookerforsolongandtheresultofthetestwasdelicioussmores,thusmakingit
successful.

Analysis

Nosolarcookerisevenclosetoonehundredpercentefficient;veryfewsolarcellsareeven
closetobeingonehundredpercentefficient.Measuringtheefficiencyofasolarcellorsolarcookerisa
difficultprocessandoftentimestakesmorethanonecalculation.Therearetimeswheredifferent
calculationswillbecombinedtogethertogetatotalefficiencyvalue.Aftercalculatingandrecalculating
numeroustimes,theefficiencyoftheparabolicsolarcookerbuiltwasonlyaboutthreepercent.Atfirst
glancethisnumberdoesnotlookveryefficient;however,

194

iftakenintoaccounttheefficiencyofmanyadvancedsolarcells,whichonlyhaveanefficiencyof
approximately25%,itdoesnotlooksobad.
OneeasywaytoincreasetheefficiencywouldbetorecoatthedishwithnewMylar.CurrentlytheMylar
coatingisafewyearsoldinsomeplacesandnoneofitiscompletelyflat.Eliminatingairbubblesinthe
Mylarwouldgiveforacleanreflectivesurfaceandthusdecreasetheamountoflightthatisreflectingin
otherdirections,insteadofreflectingtothefocalpoint.
Manyoftheproblemsthatoccurredalongthewayhadsomerelationtodesignflaws.Byfixing
someoftheminordesignflaws,efficiencycouldalsobeincreased.Whileboilingwater,itwasfoundout
thattheretractablepoledidnotworkthewayitshouldhaveandwasnotabletomovetoallpartsof
thedish.Tofixthisandcontinuewithtesting,thepolewasremovedfromitsstandandheldbygroup
members.Holdingitbyhanditwasnotalwaysinthesamepositionandnotalwaysexactlyinthefocal
157

point,whichinturnmadetheboilingtimelongerthanifithadbeenheldbyastationarystand.By
decreasingtheboilingtimeandincreasingtheamountoflightreflectingtothefocalpoint,theefficiency
ofthesolarcookershouldincrease.
Asolarcookerwithsimilardesignandsizetotheonecreatedcanbebothpracticaland
impracticalatthesametime.IntheUnitedStateswhereelectricityisreadilyavailableandcloseto
everyonehasaccesstoastoveforcooking,thisprojectwouldnotbethemostpractical.However,in
thirdworldcountrieswherethemajorityofthepopulationlivesinpovertyandelectricityisnotalways
available,solarcookersareaverypracticalinnovation.Asolarcookerthesizeoftheonecreatedcould
evenbemorepractical,becauseitcanbesharedbetweenfamilies.Mostofthesuppliesusedtocreate
thesolarcookerarematerialsthatwouldnotbeverydifficulttoobtaininapovertystrickennationand
othermaterialsthatwouldbedifficulttoobtaincouldbesubstitutedforsimilar,cheapermaterials.The
onlymajordownfallofusingasolarcookerforcookingpurposesisthatoncloudyorrainydays,cooking
wouldbeverydifficult.

Application

Solarcookershavemanydifferentapplicationsapartfromcooking.Theycanbeusedtosanitize
medicalinstruments,bykillingbacteriathroughthesunsheat;toheatwaterforcleaningpurposes;
eventopurifydrinkingwaterbykillingbacteriaandpathogensduringboiling.Solarcookingisalsoaway
tobeproactiveinpreservingtheearthandtheenvironmentweliveineveryday.Solarcookersdonot
putanyharmfulgasesintotheatmosphereandusethesunforpower,soenergywillneverrunout.

Conclusion

Parabolicsolarcookersreflectsuntoafocalpointandcreateintenseheatatthefocalpoint.
Eventhoughefficiencyisverylowtheyhavetheabilitytoboilwater,cookfoodproducts,andprove
themselvesusefulinmanyothersituations.Solarcookingisanenvironmentallyfriendlywayofcooking
andcanbefunatthesametime.Theparabolicsolarcookercreatedwasabletoreachtemperatures
similartothoseofaconventionalstoveanddidnotrequireanythingotherthansunlighttopowerit.In
thirdworldnationssolarcookingisasustainableinnovation,becauseelectricity,naturalgas,andfire
woodarenotalwaysavailable;however,thesunusually
195

158

is.Inconclusion,solarcookingisagreatwaytohavefun,cookdeliciousfoods,savemoney,sustainthe
environment,anddevelopstrugglingnations.



HYDROELECTRICITY


Final Report


Submitted to
The Faculty of Operation Catapult LXXXVIII
Rose-Hulman Institute of Technology
Terre Haute, Indiana




by
Group 20
Catherine Hidlebaugh Barron Collier High School
Naples, Florida
Kyle Gustafson Crescenta Valley High School
La Crescenta, California
Finn Leary Mount Horeb High School
Mount Horeb, Wisconsin
Jack Tift Benilde-Saint Margarets High School
Minneapolis, Minnesota
July 27, 2010
159



Introduction

Water is one of the most powerful resources on Earth, covering approximately seventy
percent of our planet's surface; however, its potential as a near-permanent supply of energy is
largely overlooked. Of all the electricity used in the United States, only nine percent comes from
hydroelectricity. The waterwheel was essentially untapped in the Western World until four
centuries ago, when systems that utilize the energy of flowing water began powering textile
mills. British colonists in North America during the seventeenth century constructed enormous
waterwheels half-submerged in the rivers that flowed through their settlements, attached a large
sequence of shafts and gears to them, and established a mechanism that would eventually lead to
the urban development of the First Industrial Revolution.
Centuries of mechanical development and innovation later, engineers began designing
underwater generators stationed on the ocean floor that look like massive boat propellers. In
another system, strands of material capable of generating electricity are attached to preexisting
underwater pillars. This project is the examination of two types of hydroelectric generators, one
traditional and the other modern, in order to create a product that could be marketed in river-
based civilizations throughout the world; an affordable system that has a minimal impact on
aquatic life while producing enough electricity to power basic household appliances. The
traditional aspect of the project includes a waterwheel design, while the modern portion is an
amalgamation of the two generators mentioned previously in the paragraph.


Double Helix Propeller Design

The double helix design is comprised of two helices that spiral around each other to
resemble a twisted rope ladder. This pattern is most commonly associated with deoxyribonucleic
acid, more commonly known as DNA. This design initially seemed more appropriate because it
would channel the water efficiently and, theoretically, generate a decent amount of energy. To
create a testable model, several propellers were glued together and twisted around a dowel to
form one continuous propeller. Ideally, the dowel containing the double helix propeller would
connect to a series of bevel gears that would turn a motor shaft (alternator) and produce power;
however, this design proved too difficult for the permitted budget and available supplies.


Waterwheel Design, Materials, and Process

At times, tradition can overpower innovation. After discovering that the double helix
propeller system would not be the most successful method, research was conducted on more
traditional methods of using water as a source of energy. The paddle wheel, which has been used
for centuries and is also referred to as the waterwheel, was deemed the most appropriate design.
Experimentation with the waterwheel design began with fixing the paddles onto an axle
with glue. It was quickly realized that this could not withstand the fast current required to
generate power, necessitating a redesign. The second model was fastened onto a block that was
nailed and glued to the axle. Plexiglas paddles were separated and attached to a light wooden
160

body, allowing them to function correctly and making them nearly indestructible. Once
assembled and tested, it proved to be a sturdy and reliable design.

Stand Design

In order to create a complete model, a stand was built to hold the system in place. The
stand is completely made out of wood and has four metal legs designed to puncture the surface
soil on the ground. These metal legs hold the stand in place and disallow the model to shift
horizontally. Acrylic was used to create a shield over the motor that would protect it from water
damage. Since acrylic is strong, cheap and light weight, using it for the paddles seemed more
than reasonable.
The stand that holds the waterwheel consists of two levels. The bottom level rests on the
ground and does not block any portion of the water flow. The top level is designed to keep all
measurement instrumentation dry. The location of the axle and paddles was designed for water to
flow only on their lower half. The model allows for another placement option. By turning the
stand around and putting it underneath a small ledge of flowing water, the current enters a
slanted PVC pipe that channels water directly above the paddles.
In order to secure the motor to the framework, a hole the diameter of the motor was
drilled into one of the wooden legs and the motor was glued in place. To keep it dry, sheets of
Plexiglas and sheet metal were installed on both sides of the motor. These prevented harmful
contact between the water and the generated power.
The axle used was a 3/8 inch wooden dowel with a 1 inch by 1 inch by 5 inch block used
for attaching the paddles. A hole was drilled in the center of the block using a drill press and the
dowel was glued inside. Holes were drilled through the base of the 1-1/4 inch by 4 inch
Plexiglas paddles in order to nail them to the block. Using hot glue, nails, and an alternating
pattern, the paddles were secured to the axle.
A ball-bearing was counter-sunk into the opposite side of the framework and glued in
place. The axle was inserted into the ball bearings inner hole. This design decreased the
amount of friction when the axle rotated and kept the axle secured in place.
Harnessing the energy of the spinning axle required an efficient motor; a difficult task
considering the budget and available supplies. The efficiency of three different motors was
tested and, after analyzing the data, the most efficient motor was used. Once attached to the end
of the axle, quickly flowing water was needed to produce enough electricity to power a small
LED. Instead of using an LED to demonstrate how much electricity was generated, a voltmeter
was attached to the motor to measure its electric potential.

P
system in
the axle w
ball beari


Data and

A
river. Us
This volt
initial tes
energy co


Concern

M
this set o
were to b
stream cu
Earth and
E
to mitiga
edges, ra
wildlife.
debris, fu
found tha
conventio
it does no


roducing the
n which a wo
will be able
ings, a light
d Results
After comple
ing the least
tage was mu
sting. All go
ould be mark
ning the Env
Minimizing th
f design asp
be marketed,
urrents rema
d must coexi
Examining th
ate its effect
ather than the
Also, grate
urther decrea
at the standa
onal wheel i
ot contain a
e least mech
ooden dowel
to turn faste
axle and pad
ting the proj
t resistant mo
ch higher th
oals originall
keted so the
vironment
he environm
ects was not
, it would be
ains unharme
ist with othe
he double hel
on water life
e sharp ones
s and mesh c
asing its imp
ard water wh
is not fully su
tube, which
anical resist
l spins at hig
r and easier
ddles.
ject, it was te
odel and two
an originally
ly set were r
common pe
mental impac
t considered
e crucial to en
ed. After all
er animals.
lix system, s
e. The prope
of the proto
could be inst
pact on the ec
heel was mor
ubmerged in
could trap f
ance possibl
gh speed. By
from the cur
ested with a
o hoses, the h
y recorded fo
reached. An
erson can hel
ct of each dev
in the produ
nsure that th
l, humans are
several mate
ellers used in
otype to prev
talled to bloc
cosystem an
re feasible th
n water, it wo
fish and othe
le was neces
y creating a m
rrent of a riv
water hose t
highest volta
for each moto
n easily acces
lp the world
vice was a s
uction of the
he aquatic lif
e one of man
erial and desi
n a large sca
vent injuring
ck out larger
nd preventing
han the doub
ould be easi
er animals.

ssary in cons
machine wit
ver. This is d
that resembl
age recorded
or and system
ssed source
out on their
ignificant co
e systems. If
fe of flowing
ny species in
ign changes
ale system w
g fish and oth
r objects like
g damage to
ble helix. See
er for anima
structing a
th low resista
done by usin
les a current
d was 0.783
m during the
of alternativ
r own.
oncern; how
f these produ
g river and
nhabiting the
could be ma
would have d
her
e fish or floa
the product
eing as the
als to avoid.
161
ance,
ng
t in a
V.
e
ve
ever,
ucts
e
ade
dull
ating
t. We
Also

Concern

T
manufact
bacteria r
exterior s
amount o
mechanic
tight loca
smaller s
a signific


Conclusi

Im
illuminat
enlighten
only imp
into alter
ning the Cos
To keep the c
turing a devi
resistant pain
surfaces. Re
of bacteria gr
cal processe
ation within
scale machin
cant part of i
ion
magine sittin
ting lights se
n your audien
pressed your
rnative energ
st of Materi
cost of the su
ice with dura
nt, similar to
eplacing any
rowing on th
s of the devi
the body of
ne, anyone co
its appeal.
ng on your b
et the mood f
nce on the si
peers, but pr
gy sources, d
Biome
The F
R
als
upplies to a m
able parts is
o the paint us
y plastic or w
he surface of
ice. The gea
the product
ould reuse sc
ack porch at
for a nice din
implicity of
roven an ess
despite the m
echanics o
Fi
Su
Faculty of Ope
Rose-Hulman
minimum an
imperative.
sed on the hu
wooden parts
f the design.
ar system and
for mechani
crap materia
t night overl
nner. As peo
using water
sential point
magnitude of
of Human


inal Project


ubmitted to
eration Catap
Institute of T
nd reduce wa
In order to
ulls of ships
s with coppe
Algae and
d generator m
ical and elec
als to build it
looking a cre
ople complim
as a source
: everyone s
f the scale.
n Movem
pult LXXXVI
Technology
aste machine
make the ge
s, would be a
r would also
bacteria inte
must be secu
ctrical purpo
t on his or he

eek in your b
ment the lit c
of electricity
hould have t
ment
III
ery,
enerators las
applied to th
o decrease th
erfere with th
ured in a wa
ses. On a
er own, whic
backyard. Sm
creek, you
y. You have
the ability to
162
st,
he
he
he
ater-
ch is
mall,
e not
o tap
163







By

Group 22

Nathan Zwissler Columbus East H.S.
Columbus, IN
Jack Dickinson The Hotchkiss School
Northfield, IL
Chris Molten Henry Clay High School
Lexington, KY
Edward Momanyi Terre Haute South Vigo H.S.
Terre Haute, IN

July 26, 2010
164

Introduction

Human motion is a seemingly simple, yet complicated process. The average person does not think
much about moving. Walking, running, or just about any motion just happens in an almost automated
way, but in reality, a lot of things are happening while these actions are performed. While moving, the
body propels you forward, absorbs the shock of each step, and re-energizes your muscles with each
action. So, while a nice walk may seem to be a very simple and easy thing, the process of walking is
actually quite complex.
The purpose of this study was to determine the varying amounts of force on the joints of the
lower extremity when performing such actions as standing, walking, and walking up stairs; all while
using different types of footwear. The goal was to determine what types of footwear and actions result in
the least amount of stress experienced by the joints of the leg.
In order to figure the magnitude and position of the forces on the body, a motion tracking system
is necessary. There are many types of motion tracking systems, ranging from only capturing the motion
of inferred markers to using high-definition video to capture the movement of the muscles themselves as
well as the motion of the body as a whole. This study will use the inferred marker system.
The inferred marker system is very simple and effective at tracking movement of the body in
general. It works by following the motion of many markers placed on the body with a few cameras. It
tracks only the markers and filters out everything else. This creates much less data and uses up much less
memory and still accomplishes what is necessary.


Procedure

To get a motion tracking system to work, the image must be in three dimensions, and to create a
3D image, there must be data from different angles. The first step was to create a setup that would be able
to generate a 3D image. A good system comprises of two or more cameras, but it depends on the
situation. Four cameras were used in this study.
The positions of the cameras are also very important. As said, there must be at least 2 images at
all times to create a 3D image. This can become a problem when the subject being tracked is in motion
because the markers can be taken out of view quite easily by objects in the environment, going out of
range, or even the subject himself (swinging arms, etc). The cameras must be positioned according to
the situation in order for the system to work. For this study, the cameras were positioned in an arc around
a central point.
In the study, it was necessary to measure the forces on the subject as well as the positions,
velocities, and accelerations. The cameras in this study were positioned around the force plate. This force
165

plate measures all of the force exerted on it very accurately. Every action had to be centered around the
force plate in order to get accurate results.
Calibration is also a very important thing to worry about. The cameras and the force plate both
need to be calibrated before use. When calibrated, they can be very accurate, but if they arent calibrated,
you may not even be able to get any data whatsoever. Calibrating the cameras is a pretty simple process.
A L-shaped rod with four reflective markers must be placed in a spot that is visible to all the cameras, and
then a rod with 2 markers on it must be spun around the same spot. The distance between the markers on
the rod is known, so it is used to figure out the distance from the bracket by the cameras. It also
determines the X, Y, and Z axes by the positioning of the L rod. The force plate is a little more
complicated to calibrate. Weights must be placed on the plate in intervals, and then programming these
weights into the plate so it can create a calibration curve. The force plate will only be as accurate as the
weights are, so it can have varying accuracy.
All of this equipment ultimately has to be connected to an interface. A computer that is connected
to this interface is a necessity, as well as other equipment, such as an amplifier for the force plate signal.
All the data will be recorded on the computer. In this study Qualisys Track Manager was used to take in
readings from the cameras and the force plate. Qualisys Track Manager can also analyze some of the data
taken.
To do multiple experiments, it is necessary to have multiple set-ups. In this study, stairs were
built, as long as platform for running. The force plate is not even with the ground, so to get accurate
results, the subject needed to be moving on the same level as the force plate. The set-ups do not have to
be made of any specific material, but be careful about using metal or anything reflective. If its too
reflective, analysis will be much harder.
After it is all connected and ready to go, there is still more to do before recording anything. The
subject now has to put the reflective markers on. The markers have to be played in very specific parts of
the body, such as the joints and the center of masses of the sections of the leg. They have to be as close as
you can possibly get them, so it requires a good amount of measuring and time. They also have to be
repositioned if the subject changes shoes or clothes.
Recording is the next step. Everything is now all set up. The subject now stands in the view of the
cameras or stands out of it depending on the situation. The subject may have to run onto the force plate so
standing out of the view may be necessary. If force is to be measured, it is necessary to be on it at some
point during the recording. The recording should not be too long though. In this study, we used 2-3
seconds for our recordings every time. The recording process is most likely going to be the shortest one.
The reason for short recordings is analysis. Analysis is easier the shorter it is, so make sure the
recording is the perfect length. In analysis, you have to figure out which markers are which body part and
label them. Then, finally, it is possible to get all of the data from the experiment and put it in an organized
manner. In this study, the format of data was very compatible with Microsoft Excel, which was an
excellent way to organize the data.
The only thing left now is to calculate all of the values on the subjects joints. In this study, the
use of inverse dynamics and physics were necessary, due to the use of only a force plate on the ground.

The value
represents
exerted on












Data
Figure O
e of the mome
s how much m
n the joints.
ne:
ents on the joi
muscle is used
ints, as well a
d when at a jo
as other force
oint, and the f
s, should be c
forces represe
calculated. Th
ent how much
he moment
h force is bein

166
ng


F
tracks the
barefoot.
a result of
walking a
Another tr
rising at a
because th
shifted to

Figure Tw

F
representa
each type
knee whil
expected,
while wea
forces aro


igure 1 shows
force while w
Each line ha
f the subjects
and climbing s
rend seen in t
a constant rate
he first contac
the balls of h
wo:
igure 2 shows
ation of how m
of footwear,
le walking up
the forces we
aring sneakers
ound the knee
s the force in
wearing sneak
s a similar M
s weight shift
stairs include
this graph is t
e, the force de
ct the subject
his feet, and a
s the magnitu
much force is
the most forc
stairs barefo
ere highest w
s. This figure

the Z directio
kers, the red o
M shape. Th
ting from one
forward mot
the hitch. On
eclined for a s
makes with t
hitch occurs
ude of the reac
s exerted on th
ce was exerted
ot was almos
hile the subje
e supports the
on (up and do
one while wea
his shape was
foot to anoth
tion and have
each line, aro
short period th
the force plac
in the graph w
ction moment
he joint. This
d on the knee
t eight times
ect was barefo
e conclusion t
own) while as
aring flip flop
also visible w
her. There is
weight shifti
ound .2 secon
then went bac
ce is with his h
when his wei
t around the k
s figure clearl
e while climbi
as much the f
oot, than whil
that sneakers
scending stair
ps, and the gr
while walking
an M shape b
ing from one
nds, there is a
ck up. This sm
heel. Immed
ight is shifting
knee. The rea
ly shows that
ing stairs. Th
force while st
le in flip-flop
act as a cushi
rs. The blue l
reen while
g. The M sha
because both
leg to the oth
a hitch. Instea
mall hitch occ
diately his wei
g

action momen
t in the case o
he force aroun
tanding. As
s, and the lea
ion, reducing
167
line
ape is
her.
ad of
curs
ight is
nt is a
of
nd the
ast
g
168

Data Analysis:
The M
a
, M
k
, and M
h
values are all moments. The units used for them are Newton*meters. A
moment represents the muscle force around a specific joint. A general trend in the values is that the
moment was usually greatest on the hip, and smallest on the ankle. The greatest moment recorded was
97.8 N-m, and it was the moment around the hip while climbing stairs. A negative moment only means
the direction is different, not that the overall moment is smaller. There are some outliers. These outliers
could be caused by the fact that the subjects walk was not always exactly the same. For example he
could have walked quicker than the previous test, or he could walk in a slightly different line. Although
seemingly minute, these actions can cause significant changes in values. In an attempt to reduce the
variance in the subjects walk, a line was put down on the runway and across the force plate so that the
subject would walk on the same line each time. Although we attempted to control his speed, it was
difficult, thus creating some error in values.
The forces in the Z direction (A
z,
K
z
, and H
z
) are a measure of the vertical force. The numbers are
all relatively similar because the subjects body weight is constant. When he steps on the force plate all
of his weight is being applied to the plate, and as a result the numbers are similar. The forces in the X
direction (A
x
, K
x
, and H
x
) vary more than the vertical forces. The X direction is the forward and backward
direction. The values are minute while standing, because there is very little forward or backward motion.
While walking and climbing stairs, however, there is a significant amount of force. The forces are
relatively close in number, although the signs are different. While walking the values for forces in the X
direction are negative, and while climbing stairs they are positive. While walking forward the motion is
straight forward. While climbing stairs, the subject pushes off the force plate with the balls of his feet to
climb to the next step. Because he pushes to move up and forward, the reaction force goes the other way,
thus a negative ground reaction force value. The negative ground reaction force will result in positive A
x
and K
x
values. The ground reaction forces while walking and standing are positive, thus negative A
x
and
K
x
values.


Experimental Errors and Improvements
In this experiment multiple errors had to be taken into account; the first of which was error in the process
of calibrating the motion tracking cameras. In using the calibration wand to have the cameras track the
motion sensors there is a given deviation of distance of points. This deviation ranged from 0.49 to 0.8
millimeters over the course of the experiment. In order to reduce the immense complexity that a third
dimension would have made, the y-axis was ignored in our calculations. The y-axis was ignored also for
the reason that the movement recorded in that direction was insignificant. In order to reduce this margin
of error a line of tape marked the x axis along which all motion of the subject took place.
Human errors in this experiment included variation in the subjects weight which ranged from 624
Newtons to 650 Newtons (or 140-146 pounds). Some other minor faults could have been the physical
motion of stepping by the subject and also the speed at which he moved. Even during the standing tests
the subject shifted his weight creating minute differences in force.
169

The tracking rate, or percent of time each individual motion sensor was in view, was consistently held at a
minimum of 90% for all markers during all experiments though they were at 100% the majority of the
time.


Conclusion
For future experiments, it is suggested to use more cameras so that the markers can be in view
100% of the time. This will result in more accurate readings. Another suggestion is to obtain a body suit
that one can attach markers onto so that the markers are in the exact same place in every trial, instead of
having to attach reattach markers on a subjects body every time a new trial is started.
The data shows that while standing, flip flops result in the greatest forces and moments on the
joints. While walking, being barefoot resulted in the greatest moments about the knee and the hip. The
largest moment experienced while walking was 66.5 Nm, which was on the hip while barefoot. The
sneakers were able to act as a cushion during walking with moments of 30.7Nm and 30.8Nm on the ankle
and knee respectively; as compared to being barefoot (38.1 Nm, 54.3 Nm) and wearing flip flops (40.5
Nm and 45.6 Nm). Although the sneakers reduced the moment, or muscle force, in the ankle and knee,
they caused about the same moment as the flip flops on the hip. The sneakers caused a moment of 46.7
Nm and the flip flops caused a moment of 46.1 Nm. While going up stairs, being barefoot caused the
greatest moments about the knee (78.8 Nm) and hip (97.8 Nm), however it also resulted in the least
moment about the ankle (46.5 Nm). In conclusion, the sneakers generally reduced the muscle forces on
the joints while standing, walking normally and while ascending stairs. The sneakers were able to act as a
cushion and reduce the stress experienced by the joints of the lower extremity.











170



























171








Appendix:

Standing
ANKLE Barefoot Flip Flop Sneaker
M
a
(N*m) -39.39 -45.77 -33.93
A
x
(N) -3.83 -8.35 -16.28
A
z
(N) -615 -625.27 -625.54
KNEE
M
k
9.68 20.38 19.7
K
x
-3.83 -8.35 -16.28
K
z
-586 -596.25 -596.52
HIP
M
h
23.02 30.9 13.97
H
x
3.83 8.35 16.28
H
z
-523.59 -533.84 -534.11

Walking
ANKLE Barefoot Flip Flop Sneaker
M
a
(N*m) -38.12 -40.5 -30.66
172

A
x
(N) -57.03 -61.77 -50.41
A
z
(N) -633.6 -628.76 -641.44
KNEE
M
k
54.3 45.6 30.8
K
x
-65.91 -62.7 -40.82
K
z
-605.18 -598 -616.86
HIP
M
h
66.5 46.65 46.1
H
x
56.36 68.6 22.12
H
z
-543.27 -541.38 -506.3

Stairs
ANKLE Barefoot Flip Flop Sneaker
M
a
(N*m) -46.1 -75.5 -71.8
A
x
(N) 45.1 75.6 50.2
A
z
(N) -778.5 -741.7 -770.6
KNEE
M
k
-78.8 -67.5 -42.7
K
x
50.7 82.8 55.8
K
z
-763.1 -728.1 -754.9
HIP
M
h
97.8 12.03 51.46
H
x
-48.16 -40.26 -38.7
H
z
-729.96 -691.5 -720.8


173










Design of a Bioshirt



Final Report



Submitted to
The Faculty of Operation Catapult LXXXVIII
Rose-Hulman Institute of Technology
Terre Haute, Indiana






By

Group 23

Lauren Dobias Hamilton Southeastern High School
Aaron Ackerman Ames High School
Trevor Bischoff East Central High School

July 27, 2010
174

Introduction

An electrocardiogram (ECG/EKG) measures the electrical activity of the heart. In order to
display the heart rate on the screen, circuitry is required to amplify the signal and filter any extra
noise. This creates the familiar image of the two sharp peaks, one up and one down, created with
each heart beat. The electrical signal created by the heart beat produces a small voltage. The
electrical signal originates in the SA node, the bodys natural pacemaker, which is located in the
top chamber. Cells in the SA node rapidly switch from negative to positive charge, creating an
electrical impulse. This impulse spreads into the ventricles and the rest of the heart, causing it to
contract and depolarize. The contraction of the heart pumps blood throughout the entire body.
Immediately after the depolarization, the cells repolarize and let blood back into the heart so the
cycle can start again. The groups goal was to detect the voltage created by the depolarization
and repolarization and then power a LED with that signal so that it flashes once each time the
heart beats.
A great amount of circuit work was required to accomplish the goal. It was necessary to
comprehend the basics of circuits before designing a solution. Circuits may consist of integrated
circuit chips, resistors, diodes, and capacitors. All of these can be wired together on a
breadboard. There were two different types of chips used in the design. The first was an AD 620,
which is an operational amplifier chip used specifically for amplifying. The second type was an
AD 741, which was a chip that had more general uses, such as filtering and rectifying. Filtering
eliminates unwanted frequencies received, while rectifying eliminates the entire negative side of
the signal. Active high-pass filters allow only frequencies above the cut-off frequency through,
while active low-pass filters allow only frequencies below the cut-off frequency through.
Resistors drop voltage through the circuit. Capacitors store electrical energy, and then even out
the output of the current by blocking direct current flow and letting alternating current pass.
Diodes block the negative signal in the circuit. With this knowledge, the group was able to
initiate a solution to the objective.


Process

The signal from the heart was detected by attaching three electrodes to the test subject. One
electrode would attach to the ankle as a ground, while the other two would attach to each arm on
the biceps muscle. By attaching the main input electrodes on each arm, the electrodes were able
to detect the hearts signal because the signal passed through the heart.
Although the heart produces a voltage, it is not high enough to power an LED. The LEDs
require at least three volts to light, however the heart produces significantly less than one volt. In
order to produce more voltage from the signal, it had to be sent through a circuit including a
series of integrated circuit chips. The circuit chips were designed to amplify the voltage picked
up from the heartbeat and filter the unwanted signals picked up from muscles. An AD 620 was
the first chip the signal was sent through. This amplified the signal to a magnitude that was able
to power an LED. However, the heartbeat was not clear in the signal because of all of the extra
signals the electrodes picked up in the range of 1-5mV. The unwanted signals acquired were
called noise. In order to make the LED flash clearly with the heartbeat, all of the excess noise
had to be eliminated.

Fig
filter, Re

T
one AD 6
operation
to elimin
designed
between
and capa
high-pass
through t
designed
10 Hz wa
is 1.17 H
amplified
active low
amplified
E
be reache
at this po
through t
contracts
is when t
preparing
heartbeat
with the n
In
included
addition,
from the
A
supply th
used to p
the chips
out of the
g. 1 Schemat
ctifier
The design w
620 chip and
nal amplifyin
nate the noise
d to be filters
an active hig
citors used d
s filter with
the chip (Fig
d to let freque
as ideal for f
Hz. In additio
d the signal.
w-pass filter
d by a factor
Even after the
ed. The goal
oint it was fla
the process o
s, pumping b
the heart rele
g for the nex
t the LED fla
negative cha
n order to ma
onto the end
the charge f
depolarizati
After wiring a
hat would be
power the ch
s, allowing th
e lab, the gro
ic of the EK
was first assem
d three 741 c
ng chip, the
e, the amplif
s. The differe
gh-pass and
determined t
a cut-off fre
g. 1). Follow
encies below
filtering the d
on to filtering
The active h
r magnified b
r of 12,000 (F
e signal was
l of the group
ashing twice
of depolariza
blood through
eases and all
xt heartbeat.
ashed twice,
arge from rep
ake the LED
d of the circu
from the rep
ion. With thi
all the filters
e easy to carr
ips. These m
hem to funct
oup chose to
KG circuit. Fr
mbled on a b
chips (Fig. 2
signal was m
fied signal w
ent arrangem
an active low
the value of t
quency of 1
wing the activ
w the cut-off
desired sign
g out unwan
high-pass fil
by a factor o
Fig. 1).
sent through
p was to mak
e with each h
ation and rep
hout the bod
lows blood t
This produc
, once with th
polarization
D flash only o
uit. Rectifier
polarization o
is, the LED w
s and amplif
ry around. Pr
machines app
tion. Since it
o power the c
rom left to ri
breadboard t
). After the v
magnified by
was sent throu
ment of capac
w-pass filter
the cut-off fr
Hz, thus all
ve high-pass
f frequency o
al because th
nted signals,
ter magnifie
of 6, so comb
h all of the p
ke the LED
heartbeat. Th
polarization.
dy. This prod
o flow back
ces a negativ
he positive c
.
once with ea
rs eliminate
of the heart w
was successf
fiers together
rimarily, two
plied a positi
t wouldnt b
chips with tw
ight: Op amp
that connecte
voltage was
y a factor of
ugh two AD
citors and re
r, while the d
frequency. T
lowing frequ
filter was th
of 10 Hz pas
he frequency
the second a
ed the signal
bined the sig
processes, th
flash once w
his was beca
Depolarizat
duced a posi
into the hea
ve charge. Co
charge from
ach heartbea
negative cha
was removed
ful in flashin
r, the group
o stationary
ive and nega
e practical to
wo nine volt
p, High-pass
ed inputs fro
sent through
one thousan
D 741 operati
esistors distin
different val
he first filter
uencies abov
he active low
ss through. T
y of an avera
and third chi
by a factor
gnal ended u
he desired ou
with each hea
ause each hea
tion is when
itive charge.
art, restarting
onsequently,
depolarizati
at, a rectifier
arge. Theref
d, leaving on
ng once with
needed to us
DC power s
ative voltage
o move thes
batteries. W
s filter, Low
om the heart
h the AD 62
nd. Then, in
ional chips
nguished
lue of resisto
r was an acti
ve 1 Hz pass
w-pass filter,
The range fro
age human h
ips also
of 2 and the
up being
utcome had y
art beat, how
artbeat goes
n the heart
Repolarizat
g the cycle a
, with each
ion, and onc
needed to b
fore, after the
nly the charg
h each heartb
se a power
supplies wer
e which pow
e power sup
With the batte
175
w-pass
t to
0
order
ors
ive
,
om 1-
heart

yet to
wever
tion
and
ce
be
e
ge
beat.
re
ered
pplies
eries

S-ar putea să vă placă și