MIT App Inventor V 2.0: app creation that transforms

Preview:

Citation preview

TableofContentsIntroduction

WhatisMITAppInventor?Arduino(FromArduinoWebsite)

TurnOnandOFFanLED(HelloWorld)CreatingAndroidApp

ConnectingBluetoothandprogrammingArduinoControlLEDbySpeechrecognition

TaskControlaServoMotor

ArduinocodeforservocontrolControlMultipleServoMotors

ArduinoCodeMultipleservoRGBColorSlider

Activitystarter

CompleteprogramfortheRGBSliderArduinoProgramforRGBSlider

CommonanodeArduinoprogramCommonCathodeArduinoprogramRGBColorPicker

ArduinoProgram

TemperaturedataintoAndroidArduinoProgramforTemperature

AndroidRemotecontrolRobotArduinoProgramforAndroidremote

ControlthesamerobotbyspeechrecognitionHowtoimportaiafilestoMITappinventorContactandappinventorfiles.

Introduction

WhatisMITAppInventor?MITAppInventorisaninnovativebeginner’sintroductiontoprogrammingandapp creation that transforms the complex language of text-based coding intovisual, drag-and-drop building blocks. The simple graphical interface grantsevenan inexperiencednovice theability tocreateabasic, fully functionalappwithinanhourorless.

Arduino(FromArduinoWebsite)Arduinoisanopen-sourceprototypingplatformbasedoneasy-to-usehardwareandsoftware.Arduinoboardsareabletoreadinputs-lightonasensor,afingeronabutton,oraTwittermessage-andturnitintoanoutput-activatingamotor,turningonanLED,publishingsomethingonline.Youcantellyourboardwhattodobysendingasetofinstructionstothemicrocontrollerontheboard.Todoso you use the Arduino programming language (based onWiring), and theArduinoSoftware(IDE),basedonProcessing.Over the years Arduino has been the brain of thousands of projects, fromeverydayobjectstocomplexscientificinstruments.Aworldwidecommunityofmakers - students, hobbyists, artists, programmers, and professionals - hasgatheredaroundthisopen-sourceplatform,theircontributionshaveaddeduptoan incredible amount of accessible knowledge that can be of great help tonovicesandexpertsalike.ArduinowasbornattheIvreaInteractionDesignInstituteasaneasytoolforfastprototyping, aimed at students without a background in electronics andprogramming. As soon as it reached a wider community, the Arduino boardstartedchanging toadapt tonewneedsandchallenges,differentiating itsofferfrom simple 8-bit boards to products for IoT applications, wearable, 3Dprinting,andembeddedenvironments.AllArduinoboardsarecompletelyopen-source, empowering users to build them independently and eventually adaptthem to their particular needs. The software, too, is open-source, and it isgrowingthroughthecontributionsofusersworldwide.

TurnOnandOFFanLED(HelloWorld)Beforestartingtogoinsidethischapter,firstlyyouneedtoinstallArduinoIde

fromthewebsitearduio.ccDownload the latestArduinosoftwareand install itonyour laptoporPC,withoutArduinoIDEyoucannotprogramyourArduinoboard.Things you need for this tutorial are 1) Arduino board 2) LED and AndroidphonetocontroltheLEDconnectedtoArduino.Firstwe create android app to control the LED, to do this you should have aGmail account or you can create a new account it’s really easy and most ofpeoplewillhaveanexistingGmailaccount.The following step-by-step picture tutorial will guide you to create your firstandroidappthatconnectstoyourArduino.

1)Gotothewebsitehttp://ai2.appinventor.mit.edu,whenyouenterforthe first time you will be required to login with your Gmail id andpassword.

2)MITappinventorwillasktouseyourGmailaccountclickallowandcheckrememberthisapprovalforthenext30days.

3)WhenyouloggedintoMITappinventordevelopmentenvironmentforthe first time, therewon’t be any projects, youwill be greetedwith anemptywindow.Clickonthestartnewprojecttocreateyourfirstandroidapp.

4)NameyournewprojectasLED_CTRLorwhatevernameyouwouldlikeforyourfirstappandclickoktoenterintothemainscreen.

5)When you click ok after naming your app, you will be moved to a mainscreen tomakeyour app, the screen that appearsonyourwindow is called asDesigner, where you need to design user interface like buttons, widget, textpane, label this window act as a controller and there is also another windowwhereyouneedtoprogramthegraphicalcodestomakeyourfunctiontowork.

Ontheleftsideyoucanseepalette,thepalettewhichcontainsinterface,layout,Media, Drawing and Animation, Sensors, Social, Connectivity etc., To createyour user interface on the main screen you need to pick buttons and yourrequiredstuffsfromthepalette.ClickLayouton the left sidebelowpalette,PickTableArrangement anddropintotheViewer.

Ontheleftsideofthetableproperties,changecolumnsandrowsto3andalsochangethewidthtofillparentfromautomatic.

PickListpickerfromUserInterfaceanddropintofirstrowintheViewerscreen.ThisusedtoconnecttoyourBluetoothdevice.WhenyouclickthisbuttonitwilldisplayavailableBluetoothdevices.

SelectListPickerfromtheComponentsList

GotolistpickerpropertiesandchangethetexttoBluetoothandyoucanalsouploadanimagefiletothelistpicker.

ClickontheNonetabbelowImageanduploadyourBluetoothpicturetosetittoListpicker.

Click theupload fileandbrowse to the imageyouwant tousefortheListPicker,iftheViewerScreendisplaystheImagefortheListPickerinlargersizeyouneedtoaltertheheightandwidthoftheListPickerbygoingtothepropertiesfortheListpicker.

Next pick a button and drop into second row of the Viewer screen and addanotherbuttontothesamerow.

ClickonthefirstbuttonandgothebuttonpropertiesandchangethenameofthebuttontoONdothesame

forthesecondbuttonbychangingthenameofthebuttontoOFF.

Changebuttoncolorbychangingthebackgroundcolorfrompropertiesoftheappropriatebutton.

PickandplaceLabelfromuserinterfaceandplaceintothe3rdrowofViewer

Screen.GotopropertiesandremovetheTextlabelandleavethisasempty,thislabelwilllateronusedforindicatingwhetherourapphasconnectedtoanBluetoothornot.

We have almost completed User Interface for our first Android app, we alsoneedsomeNon-visiblecomponents tomake thisapp, thefirstone is theclockwhich can pick and placed from the sensor palette

Itprovidestheinstantintimeusingtheinternalclockonthephone.Itcanfireatimeratregularlysetintervalsandperformtimecalculations,manipulations,andconversions.Weareusingclocktocauseactivitiestooccuratapresetinterval.

LaststepinthistutorialpickBluetoothclientformtheconnectivitypaletteandplaceitinsidetheViewerscreen.TheBluetoothclientcomponentwhichallowsus to connect tootherdeviceandmakeus to sendand receivedata’sbetweenBluetoothdevices.Wehavecompleted theuser interfacedesign for the firstapp,nowthisdesignrequiresprogramtorunbehindthisanddocertainfunctions,Inappinventorweconnectdifferentblockstomakeaprogramandit’seasyforanynewuserwho’shavinglotofenthusiasmforlearning,let’smovetoprogramming.

Clickontheblockstogetintoprogrammingmode.

ClickListPicker1andselectwhen.listpicker1.BeforePickingblockandplaceintoprogrammingwindow.

Afterplacingthefirstblockandscrolldowninthelistpickerblocksandselect

set.Listpicker1.elementtoNow you may familiarize with blocks and how to pick and place intoprogrammingwindow,completetheblocksprogrammingbygoingintodifferentblocks associated with different functions and place it on the programmingwindow.GotoBluetoothclientandpickBluetoothclientaddressandnamesandcompletethefirstblock.

Thefirstblockwhichexplains,whenyouclick the listpickerbutton, itshoulddisplaytheavailableBluetoothdevicesthatarealreadyconnectedtoyourdevicepreviously.Nowcompletethesecondblockbygoingtothedifferentcomponentsandpickandplacetherequiredblockintoprogrammingwindow.

Ifthenblockcanbepickfromthebuiltinfunctions.

Second block which explains, when you pick a Bluetooth device from theavailable list the current device that you picked should be used as a currentdeviceandBluetoothaddresswillbestoredandtheappwillcommunicatewiththeselecteddevice.

Thethirdblockwhichisplacedinsideatimer,thisblockwillassignConnectedtexttoTextLabelonthethirdrowiftheBluetoothdeviceisconnectedifthedeviceisnot

connectedTextlabelwilldisplaymessageasNotConnected.Completetheblockbyusingtheabovescreenshot.TextstringblockcanbeaddedfromTextinbuiltfunction

We have already seen how to add If then block from controls, in the aboveprogramforscreenshotwehaveaddedIfthenelseblock,whichisnotavailableinthecontrols,weneedtoplaceusualifthenblockandclickontheblueiconontheifthenblockandplacetheelsefunctiontotheblock.

Andwearejustfewstepsawayfromcompletingourapp.YouneedtocreateacontroltaskforthetwobuttonwecreatedintheViewerscreen.Completethecodeforbutton

usingthescreenshotbelow.

Whenyoupress the first button itwill send “on” and for the secondbutton it is “off”.Weconnect to a

BluetoothdeviceattachedtoArduino,whenArduinoreceivethesetwostringwehavetoprogrambasedon

thesestringandmakeadecisiontoturnOnandOffanLED.

Here’sthecompleteblockfortheFirstprogramtocontrolanLEDconnectedtoanArduino.Checkyourblockwiththisblockandmakesureyouhavenotmadeanymistakewhenconnectingtheblocks.

CreatingAndroidAppConvertyourblockintoandroidapp.Clickbuildandselectapp(save.apktomycomputer).

Attach the app to your email and send the Email addresswhich your androiddeviceregisteredtoanddownloadtheapptoyourmobileandinstallit.Makesureyouhaveenabledinstallationofappsfromunknownsources,thiscanbedonefromyoursettings.

YouneedtoaddHC-05orHC-06orwhatevermodelyouareusingtoyourandroiddevice,connectyourBluetooth device VCC to 5v and Gnd to Ground of Arduino, go to your Bluetooth and turn on yourBluetoothandsearchfordevices,connecttoyourBluetoothdeviceusingdefaultpassword,mostBluetoothdeviceswillbe‘1234’or‘0000’.

ConnectingBluetoothandprogrammingArduinoNowconnectyourBluetoothdevicetoArduinoboard,connectionasfollows

ConnectyourLEDto13thpinofArduino,ifyoudon’twanttoconnectanLEDstillyoucando thisproject,bydefaultanLEDisconnected to the13thpinofArduino.ConnectTXofBluetoothto10thpinandRXofBluetoothto11thpin.Youcanalsoconnectit totheavailableTXandRXpinsthatis0and1,whenyouconnect to thesetwopinsyoucannotconnectyourArduinotoyourPCorLaptop.//codebeginhere#include<SoftwareSerial.h>SoftwareSerialBT(10,11);//TX,RXrespectivelyStringstate;//stringtostoreincomingmessagefrombluetoothvoidsetup(){BT.begin(9600);//bluetoothserialcommunicationwilltakeplaceonpin10and11Serial.begin(9600);//serialcommunicationtocheckthedataonserialmonitorpinMode(13,OUTPUT);//LEDconnectedto13thpin

}

//–––––––––––––––––––––––—//

voidloop(){while(BT.available()){//Checkifthereisanavailablebytetoread

delay(10);//Delayaddedtomakethingstable

charc=BT.read();//Conductaserialreadstate+=c;//buildthestring-either“On”or“off”

}

if(state.length()>0){

Serial.println(state);

if(state==“on”)//ifthereceivedstringison,turnonledconnectedtothepin13

{

digitalWrite(13,HIGH);

}

elseif(state==“off”)//ifthereceivedstringisoff,turnoffledconnectedtothepin13

{

digitalWrite(13,LOW);

}

state=””;}}//Resetthevariable

//codeendshereUploadtheaboveprogramtoArduinoandconnectyourappandturnonandoffthe led connected to your Arduino, you can also check the Arduino serialmonitorforincomingdata.

ControlLEDbySpeechrecognitionIn the previous chapterwe have seen how to control anLED connected to

Arduinobycreatinganandroidapp, in thischapterwewillseehowtocontrolthe same LED and the same setup and program that we used in the previouschapter by speech recognition, this app is very simple, all the android phonecomes with Google inbuilt speech recognition engine, it need to connect tointernet toworkproperly,whenyou speak something toyourmobile phone itrecognizeyourspeechandconvert it to text,wesimply transfer the text to theBluetoothdeviceandmatchthetextwithpredefinedtextinArduino,ifthetextsend from our android mobile matches then Arduino executes certain taskassociatedwiththetext.StepstocreateandroidappinMITappinventor

1) Gotohttp://ai2.appinventor.mit.edu/andcreatenewprojectandnametheprojecttoyourwish.

2)PicklabelfromuserinterfaceandplaceintoViewerscreen,Thiswillbe used for displaying Bluetooth connectivity, if the Bluetooth isconnected , connected text will be displayed if the Bluetooth is notconnected,notconnectedtextwilldisplayinthelabel.

Gotopropertiesofthelabelandchangethewidthtofillparentanddeletethetext

3)Pickandplacehorizontalarrangementfromlayoutandchangethepropertiesofwidthtofillparent.

4)Picklistpickerfromuserinterfaceandplaceintothehorizontalarrangementbox,andchangethelistpickerpropertieswidthto“fillparent”andchangethetexttoBluetooth,youcanalsoaddanimagetothelistpicker.

5)Pickanotherhorizontalarrangementtableandfromlayout,thistablewilladdaspacebetweentheBluetoothpickerandbuttonwhichwilllookgoodinsteadofthebuttonimmediatelyfollowstheBluetoothpicker.

6) Pick one more horizontal arrangement and place it below the previousarrangement and change the properties of the present horizontal arrangementwidth to “fill parent”, pick a button from user interface and place into thehorizontal arrangement. Change the button properties width to fill parent andchange the text to “ press to talk”, add an image to the button, you canuse agoogletalkicontomakeitmorepresentableandattractive.

7)Addalabelbelowpresstotalkbutton,thislabelwillbeusedtodisplaytheresultfromspeechrecognitioneditthepropertiesoflabelandremovethedefaulttextassociatedwiththislabelandchangethewidthtofillparentandmakethetextaligntocentre.

8)ForthefinalfinishingstageweneedtopickandplacenonvisiblecomponentstotheViewer,weneedtoplaceclock,Bluetoothclient,andspeechrecognizer,pickclockfromthesensorpalette,BluetoothclientfromconnectivitypaletteandspeechrecognizerfromMediapalette.

AftercompletingeverythingintheDesignersectionit’stimetoprogramusingblocks,clickontheblockson the top right hand side and move to programming section, we have already discussed aboutprogrammingsectioninlastchapter,let’sdirectlydiveintocodingandseewhatevertheblocksneedtobepickandplacetomakethisapptowork.

First place the block functions for before picking the listpicker what shouldhappenintheprogram.

When you place this function, when you press the list picker button it willdisplayavailableBluetoothdevice thathas alreadyconnected toyourAndroidmobile.Now, place the block for the second function, what should the app do afterconnecting to a Bluetooth device

ThisfunctionwillsettheaddressoftheBluetoothdevicethatweselectedmostlyweselecttheHC-05orHC-06BluetoothdeviceconnectedtoArduino.All the block that is associatedwith speech recognizer can be find the speechrecognizerblock.Clickon the speech recognizer toget theblocks andchoosetheblocksbyfollowingthescreenshotfortheprogram.

Now,weplace the thirdblockwhichwill set the text label1 toconnect if theBluetoothdevicehassuccessfullyconnectedelseitwillsettonotconnected.

Nowwewillmoveonthemainprogram,weaddedabuttonintheviewer,whensomeone press that button it should open Google speech recognizer and startlisteningtoyouandconvertyourspeechtotext.

Addtheaboveblockstostartthespeechrecognizerandgetthetext.Nowwegotthetext,itshouldbestoredintolabel2andbeforestoringtolabel2,previous text that occupied in the label 2 should clear. Make the block byfollowingbelowscreenshottodothat.

Thisblockwillhelpustoemptythetextthatpreviouslyoccupiedinlabel2.NowwewilladdblocksforsendingtheconvertedspeechtotextcharacterasaBluetoothmessageandalsodisplaythetextinlabel2.

AboveblockwillsendtheresultasstringtotheBluetoothdeviceconnectedtoArduino,wehavealreadyprogrammedArduino,soifthetextmatchestoitthenArduinowillexecuteappropriatefunctionthatisassociatedwiththetext.

Completeprogramforthespeechrecognitionhasgivenintheabovescreenshot,thatcanbeusedtoverifywhetheryouhaveprogrammedwithoutanyerrorsornot.UploadthesameArduinoprogramtoyourArduinoboardandstarttalkingtoyourapp,whenyousayONtheledontheArduinowillgoesonandwhenyousayOFFledontheArduinosidewillgoesoff,checkthisappwithyourAndroiddevice.ReferConnectingBluetoothandprogrammingArduino

TaskCombineboththeappspeechrecognitionandbuttoncontrolintooneappandplaywithyourandroidArduino.

ControlaServoMotorInthischapteryouwillcreateanappforcontrollingtheservomotorandalso

programArduinotoreceivecommandsfromandroidmobileandangletheservomotortothepositionthatisassignedbytheandroidapp.YouneedaservomotorandArduinoboardwithBluetoothmodule,useanyoftheservomotorthatisavailableinthemarket,somemotorsdrawsmorepowerandArduinocannotsupplyenoughpowertoruntheservomotor,insuchcasesyoushouldconnectanexternalpowersupplytoyourArduinothiswillmaketheArduinoboard towork smoother during theoperation, if you are not suppliedwithexternalpowerArduinomayfrequentlyresetwhenrunninginlaptoporPCUSBpower.

1)Clickonstartnewprojectandnameyournewprojectasservocontroloranyotheryouwouldlikeforyourandroidapp.

2)PicklabelfromuserinterfaceandplaceitinViewerscreen,changethepropertiesoflabelwidthtofillparent,andtextaligntocentre.

3) Pickhorizontal arrangement from layout andplace itbelowTextlabel-1andchange thepropertiesofhorizontalarrangementwidth to fillparent 4) Pick another horizontal arrangement and place it belowpreviousone.Thiswillbeusedforspacing.

5) Pick label fromuser interface and place it belowprevioushorizontalarrangementweaddedforspacing.

6) Addanother horizontal arrangement belowText label 2 andchangeitspropertieswidthtofillparent.

7) Pickandplaceabuttonfromuserinterfaceandplaceit insidethehorizontal arrangement that created newly, add another 4 buttons to thesamehorizontalarrangement.

8) Changethebuttonpropertiesfrom text for button to 0 for thefirst button, 45 for the secondbutton,90forthethirdbutton,135for the fourth button and 180 forthelastbutton.

9)PicksliderfromuserinterfaceandplaceitinViewerscreenbelowthebuttonsthathavecreatedinthe

previousstep.ChangethesliderpropertiesMax

valueto180andMinvalueto0.

10)Pickandplaceinvisiblecomponents,BluetoothclientandclockintoViewerscreen.

Designerpartisoverandtheprogrammingpartisleftover,clickontheblocksontheupperrightsideoftheAppinventorwindow.Completethefirst3blockswhichhasrepeatedinthefirst2chapters,ifyouhaveskippedthesechaptersanddirectlylaunchedintothischapter,pleasegothroughfirstorsecondchaptertomakesurehowthiscodeworksandwhatyoushoulddotocompletethebelowcodegiveninthescreenshot.

AbovecodewillconnecttotheBluetoothdevicethatisalreadypairedwithyourandroid phone and if the device is connected then label 1 text changes toconnectedelselabel1willdisplayasnotconnected.Functionrelatedtosliderblockcanbefindinthesliderchecktheimagebelowtoknowhowtoaccessblocksrelatedtoslider.

DraganddropthebelowscreenshotfortheblocksintheblockswindowofMitapp inventor, this block will send the number when you change the sliderposition inyourandroidapp,and thecurrentsliderpositionwillbedisplayonyourlabel2.

Roundfunctionwillbenewtoyouandthisfunctionisintroduceinthischapter,theround

functionhelpustoroundanumberallthenumberwillbepresentedasawholenumber.Thisblockisavailableinthebuiltinmathblock.

Completethebelowblockforsendingnumberswheneachbuttonispressed,wehavecreatedfivebuttonsintheViewerscreenandeachbuttonhasassignedanumber,whenwepressabuttonthenumberassignedtothenumbershouldsendtotheconnectedBluetoothdevice.Blocktogivenumberinputcanbefindinthemathbuiltinfunction.

ArduinocodeforservocontrolIn thissectionwewillknowhowtoconnect theservomotorandBluetooth toyourArduino.

ConnectyourBluetoothTXpintothe10thpinofArduinoandRXpintothe11thpinofArduino,mostoftheservomotorcomeswith3wiresandcheckforyourservo motor wire specification with the manufacturer sometime servo motorcomeswithdifferentwirecolors,connecttheservosignalwiretothe9thpinofArduino.IfyourArduinoboardresetfrequentlywhenyouconnectingyourapp,thismightbe due to low power from the Arduino side, to eliminate this error you cansupplyexternalpowersupplytoyourArduinowhichcanmakethingsstable.WritethebelowcodeandalltheexplanationforthiscodeisgivenasacommentnexttoeachlineofArduinoprogram,trytotypethecodeandknowwhateachcoderepresentsandthiscodecanbecorelatewiththeandroidprogram.Don’tcopy and paste without understanding what is actually happening inside thecode.

Arduinoprogramforservomotor:

//codebegins

#include<SoftwareSerial.h>//TXRXsoftwarelibraryforbluetooth#include<Servo.h>//servolibraryServomyservo;//servoname

intbluetoothTx=10;//bluetoothtxto10pinint

bluetoothRx=11;//bluetoothrxto11pin

SoftwareSerialbluetooth(bluetoothTx,bluetoothRx);voidsetup()

{

myservo.attach(9);//attachservosignalwiretopin9//SetupusbserialconnectiontocomputerSerial.begin(9600);//SetupBluetoothserialconnectiontoandroidbluetooth.begin(9600);

}

voidloop()

{

//Readfrombluetoothandwritetousbserialif(bluetooth.available()>0)

//receivenumberfrombluetooth{

intservopos=bluetooth.read();//savethereceivednumbertoservoposSerial.println(servopos);//serial

printservoposcurrentnumberreceivedfrombluetoothmyservo.write(servopos);//roatetheservothe

anglereceivedfromtheandroidapp}

}

//codeendshere.

ControlMultipleServoMotors

Inthischapterwewillknowhowtocontrolmanyservomotors,thischapterwillresembleeverythingwhat we did in the previous chapter for controlling a single servo motor, in this chapter we willconcentratingoncreatingsixslidertocontrolsixservomotorconnectedontheArduinoside.Allthecodesaresameforandroidapp,ontheArduinosidetherewillbeplentyofchangeintheprogramming.It’sveryeasytocontrolasingleservomotorthereasonisArduinocaneasilyaccept8bitnumber,whenwecreatedasingleservosliderweassignedthedatavaluefrom0to180anditfallsbelow255(8bit)soitbecomeseasyforus,whenwewanttocontrolmoreservoweneedtoassignnumbermorethan255soitmorethan8bit,and still we don’t have problem on android app side it just sending numbers from android app on theArduinosidewehavetoreceivethesenumberanddosomecalculationandmakethenumbertodocertainaction.Let’sbeginwithcreatingViewerscreenforthisapp.

1) Start a newproject onyourMITapp inventor andnameyourproject asMutliple_servo_control2) Startwithplacinga text label fordisplayingBluetoothconnectivitystatus3)Placehorizontalarrangementandchangeitspropertieswidthtofillparent4)Placelistpickerfromuserinterfaceandplaceitinsidehorizontalarrangement5)Placeasliderfromuserinterfacebelowthehorizontalarrangement6) Placefiveslideroneafteranother.

Selectslider1andchangeitspropertieswidthtofillparentandchangemaximumvalueto1180andminimumvalueto1000andalsothumbpositionto1000

Selectsecondsliderandchangeitspropertieswidthtofillparentandchangemaximumvalueto2180andminimumvalueto2000andalsothumbpositionto2000.Selectthirdsliderandchangeitspropertieswidthtofillparentandchangemaximumvalueto3180andminimumvalueto3000andalsothumbpositionto3000.Selectfourthsliderandchangeitspropertieswidthtofillparentandchangemaximum

valueto4180andminimumvalueto4000andalsothumbpositionto4000.Select fifth slider and change its properties width to fill parent and changemaximumvalueto5180andminimumvalueto5000andalsothumbpositionto5000.Select last slider and change its properties width to fill parent and changemaximumvalueto6180andminimumvalueto6000andalsothumbpositionto6000Pickandplaceinvisiblecomponents,BluetoothclientandclockintoViewerscreen.Completethefirst3blockswhichhasrepeatedinthefirst2chapters,ifyouhaveskippedthesechaptersanddirectlylaunchedintothischapter,pleasegothroughfirstorsecondchaptertomakesurehowthiscodeworksandwhatyoushoulddotocompletethebelowcodegiveninthescreenshot.

AbovecodewillconnecttotheBluetoothdevicethatisalreadypairedwithyourandroid phone and if the device is connected then label 1 text changes toconnectedelselabel1willdisplayasnotconnected.Complete the block for first slider, whenever slider position changes, thesepositionwillsendasa2bytenumbertotheconnectedBluetoothdevice.

RoundblockcanbepickfromMathbuiltinfunction.Continuethesameblockwhichshownintheabovescreenshotforothersliders

Programmingfortheapphascompletednowbuildthecodeandtransfertheappto your androidmobile and install the app,make sure you have enabled yoursettingforinstallingappfromunknownsource.

ArduinoCodeMultipleservoWhen come’s to Arduino code this is quite complicated than our previous

programs, this code will receive number from android app, the number fromandroidappisa2bytenumber,sotheArduinowillreceivethesenumberas2bytes and later on add the first and second byte andmake it as a single digitnumber.

WhenyouusingservomotorwithArduinoboardyoushoulduseexternalpowersupply to ensure proper working of this board, Arduino board cannot supplyenoughpowertotheseservomotorsifithasconnectedtoPCorLaptop.

ConnectTxofBluetoothto7thpinofArduinoandRxofBluetoothto8thpinofArduino.

Connectfirstservosignalwireto9thpinofArduinoSecondservosignalwireto10thpinofArduinoThirdservosignalwireto11thpinofArduinoFourthservosignalwireto3rdpinofArduinoFifthservosignalwireto5thpinofArduinoSixthservosignalwireto6thpinofArduino//codestartshere#include<SoftwareSerial.h>#include<Servo.h>Servomyservo1,myservo2,myservo3,myservo4,myservo5,myservo6;intbluetoothTx=7;

intbluetoothRx=8;

SoftwareSerialbluetooth(bluetoothTx,bluetoothRx);voidsetup()

{

myservo1.attach(9);//attachservo1to9thpinmyservo2.attach(10);//attachservo2to10thpinmyservo3.attach(11);//attachservo3to11thpinmyservo4.attach(3);//attachservo4to3rdpinmyservo5.attach(5);//attachservo5to5thpinmyservo6.attach(6);//attachservo6to6thpin//SetupusbserialconnectiontocomputerSerial.begin(9600);//SetupBluetoothserialconnectiontoandroidbluetooth.begin(9600);

}

voidloop()

{

//Readfrombluetoothandwritetousbserial

if(bluetooth.available()>=2)//receivetwobytenumbers{

unsignedintservopos=bluetooth.read();//receivefirstbyteunsignedint

servopos1=bluetooth.read();//receivesecondbyteunsignedint

realservo=(servopos1*256)+servopos;//addfirstand

secondbytetomakesingledigitnumber

Serial.println(realservo);//ifnumberfallsbetween1000to1180itisfirstservo

if(realservo>=1000&&realservo<1180){//checkforthenumberintservo1=realservo;servo1=map(servo1,1000,1180,0,180);myservo1.write(servo1);

Serial.println(“servo1ON”);delay(10);

}

//ifnumberfallsbetween2000to2180itissecondservoif(realservo>=2000&&realservo<2180){intservo2=realservo;

servo2=map(servo2,2000,2180,0,180);myservo2.write(servo2);Serial.println(“servo2On”);delay(10);

}

//ifnumberfallsbetween3000to3180itisthirdservoif(realservo>=3000&&realservo<3180){intservo3=realservo;servo3=map(servo3,3000,3180,0,180);myservo3.write(servo3);Serial.println(“servo3On”);delay(10);

}

//ifnumberfallsbetween4000to4180itisfourthservoif(realservo>=4000&&realservo<4180){

intservo4=realservo;servo4=map(servo4,4000,4180,0,180);myservo4.write(servo4);Serial.println(“servo4On”);delay(10);

}

//ifnumberfallsbetween5000to5180itisfifthservoif(realservo>=5000&&realservo<5180){

intservo5=realservo;servo5=map(servo5,5000,5180,0,180);

myservo5.write(servo5);

Serial.println(“servo5On”);

delay(10);

}

//ifnumberfallsbetween6000to6180itissixthservo

if(realservo>=6000&&realservo<6180){

intservo6=realservo;

servo6=map(servo6,6000,6180,0,180);

myservo6.write(servo6);

Serial.println(“servo6On”);

delay(10);

}

}

}

//codeendshere

UploadtheaboveprogramtoyourArduinoboardandconnecttoyourandroidapp,youcanchecktheserialmonitorforthedatareceivingfromtheandroidapp.

RGBColorSliderIn this chapter we will use three slider and mix color using RED slider,

GREENsliderandBLUEslider.WhenwemixRGBwegetanewcolor, thiscolor will be displayed on our app as well as the color data will send to aBluetooth device connected to Arduino, the same color will be applied to anRGBLEDconnectedtoArduinoontheotherside.

ActivitystarterThis activity starter will be useful when the app initialize if we want to

execute certain function in android phone we can make use of this activitystarter,wewilllookinthischapterhowtousethisactivitystartertoremindustoturn on our Bluetooth if it is disabled during the opening of the app in theandroiddevice.

1) PickaLabelandplaceitontheviewerscreen,changeitspropertieswidthtofillparentandchangethetextalignmenttocentre.

2) PickahorizontalarrangementfromlayoutandplaceitbelowTextlabelandchangeitspropertieswidthtofillparent.

3) Place a list picker fromuser interface and change its name fromproperties toBluetoothandalsoplaceabuttonnext to it andname it todisconnect in this chapterweuseabutton todisconnect fromBluetoothdevicewhenwepressthebutton.

4)Pickcanvasfromdrawingandanimationandplaceitbelowhorizontalarrangementandchangethepropertiesofwidthtofillparentandheightto100pixels.

5) Pick3sliderandplace

itoneafteranother.

Changethepropertiesofsliderasfollows

PlacenonvisiblecomponentsBluetoothClient,ClockandActivitystarter,activitystartercanbeplacedfromtheconnectivitypalette.

Designerpartforthisapphascompletedmoveontotheblocksforprogrammingthisapp,clickontheblockstomovetotheprogrammingwindow.

ProgramtheRGBsliderchooserblocksforconnectingtoaBluetoothdevice,abovecodewillshowthelist

ofavailableBluetoothdevicesthatyoupairedalreadyandonceyouconnecttoadevicethiswillsavethe

addressoftheBluetoothdeviceandconnecttoit.

Complete the above blocks to display whether the Bluetooth devices hassuccessfullyconnectedornot.Colortotheblockcanbeaddedfromthebuiltincolorsfunction.

Complete the below code to disconnect from the Bluetooth device that hascurrently connect to, when you click the app it will disconnect thecommunication.

Whenthescreeninitialize,aswediscussedalreadyiftheBluetoothisnotcurrentlyturned

ontheactivitystartershouldremindustoturnontheBluetoothdevice,andalsothecanvasshouldbesetto

whitecolor.Completetheblocksgivenbelowdoallthisfunctions.

ScreeninitializefunctioncanbepickedfromtheblockspresentinsidetheScreen1.Click on activity starter and pick activity starter action and place it in screeninitialize block and pick block from text and type“android.bluetooth.adapter.action.REQUEST_ENABLE” remove the quotesbetweenthecommands.Slidercolorleftblockcanbefindinsidetherespectivesliderontheleftsidefunctions.

Makecolorblockispresentinsidethecolorsbuiltinfunction.Adding two number block is presented in themath built in block, add roundblockbeforeslider1positionandalsopickanemptynumberplacefromMathbuiltinblockaddtwonumberstogether.

Completeaboveblockstostore thefirstvaluein thecanvasandalsowhenwechange the first slider position if the androiddevice is connected toBluetooththentheslidervaluewillbeaddedwith3000andsendtoconnectedBluetoothdevice,wehavealreadyseenwhywearesendingtwobytenumberinMultipleservoprogramming.Pleasereferifyouhavenotcompletedthattutorial.Get thumbpositionblockcanbe find in thevariables,pickget function in thevariablesandplaceitinthecolormakelistandchoosethumbposition.

Afterplacinggetblockinthemake color click on theinverted triangle symbol toselect thumb position. Thisvariablewillhold thecurrentvalueofslider.

Completethesameblockforthesecondslider,rightclickonthefirstsliderandduplicate the blocks and select to slider2wherever slider1 is presented,makesuretoeditthevalueintheBluetoothclient1.Complete the third slider block to complete the program, this slider does thesamefunctionliketheothertwosliders.

CompleteprogramfortheRGBSlider

ArduinoProgramforRGBSliderThere are two types of RGB LED available in the market one is common

cathodeandanotheroneiscommonanode.MakesurewhattypeofRGBLEDyouareusingforyourpractice.CommonAnodeType

If you have a common anode typeRGBLED then you have to connect youranodeto3.3vofArduino.Connecttheredpinto3rdpinofArduinogreenpinto5thpinofArduinoandbluepinto6thpinofArduino.ConnectBluetoothTxto7thpinandRxto8thpinofArduino.CommonCathodeType

Ifyouhaveacommoncathode typeRGBLED thenyouhave toconnectyourcathode togroundpinof

Arduino.Connecttheredpinto3rdpinofArduinogreenpinto5thpinofArduinoandbluepinto6thpin

ofArduino.ConnectBluetoothTxto7thpinandRxto8th

pinofArduino.Youalsoneedtoconnect220ohmresistorbetweenthepinsofLEDandArduinotoprotectitfromburning.

CommonanodeArduinoprogram

#include<SoftwareSerial.h>intbluetoothTx=7;

intbluetoothRx=8;

SoftwareSerialbluetooth(bluetoothTx,bluetoothRx);voidsetup()

{

pinMode(3,OUTPUT);//redpinofRGBLEDpinMode(5,OUTPUT);//GreenpinofRGBLEDpinMode(6,OUTPUT);//bluepinofRGBLEDdigitalWrite(3,HIGH);digitalWrite(5,HIGH);digitalWrite(6,HIGH);

//SetupusbserialconnectiontocomputerSerial.begin(9600);

//SetupBluetoothserialconnectiontoandroidbluetooth.begin(9600);

}

voidloop()

{

//Readfrombluetoothandwritetousbserialif(bluetooth.available()>=2)

{

unsignedintcolor1=bluetooth.read();unsignedintcolor2=

bluetooth.read();unsignedintcolor=(color2*256)+color1;Serial.println(color);if(color>=1000&&color<1255){intblue=color;

blue=map(blue,1000,1255,0,255);

int blue1 = 255-blue;

analogWrite(6,blue1);

Serial.println(blue1);

delay(10);}

if(color>=2000&&color<2255){intgreen=color;

green=map(green,2000,2255,0,255);int

green1=255-green;analogWrite(5,green1);

Serial.println(green1);delay(10);

}

if(color>=3000&&color<3255){intred=color;

red=map(red,3000,3255,0,255);intred1=255-red;analogWrite(3,red1);Serial.println(red1);

delay(10);

}

}

}

ThisprogramissameastheMutliservoprogramthatwedidinthepreviouschapter.

CommonCathodeArduinoprogram

#include<SoftwareSerial.h>intbluetoothTx=7;

intbluetoothRx=8;

SoftwareSerialbluetooth(bluetoothTx,bluetoothRx);voidsetup()

{

pinMode(3,OUTPUT);//redpinofRGBLEDpinMode(5,OUTPUT);//GreenpinofRGBLEDpinMode(6,OUTPUT);//bluepinofRGBLEDdigitalWrite(3,LOW);digitalWrite(5,LOW);digitalWrite(6,LOW);

//SetupusbserialconnectiontocomputerSerial.begin(9600);

//SetupBluetoothserialconnectiontoandroidbluetooth.begin(9600);

}

voidloop()

{

//Readfrombluetoothandwritetousbserialif(bluetooth.available()>=2)

{

unsignedintcolor1=bluetooth.read();unsignedintcolor2=bluetooth.read();unsignedintcolor=(color2*256)+color1;Serial.println(color);

if(color>=1000&&color<1255){

intblue=color;

blue=map(blue,1000,1255,0,255);

analogWrite(6,blue);Serial.println(blue);

delay(10);

}

if(color>=2000&&color<2255){intgreen=color;

green=map(green,2000,2255,0,255);

analogWrite(5,green);Serial.println(green);

delay(10);

}

if(color>=3000&&color<3255){intred=color;

red=map(red,3000,3255,0,255);analogWrite(3,red);Serial.println(red);

delay(10);

}

}

}

ThisprogramissameastheMutliservoprogramthatwedidinthepreviouschapter.

RGBColorPickerInthepreviouschapterwehaveseenhowtosetacolorforanRGBledfrom

android app, this appwill bemuch similar to the previous one but instead onmixingsliderwearegoingtochoosethecolor’sbypickingexistingimagefromgallery.

1) Pickhorizontalarrangementandplace iton theviewerscreenandchangeitspropertieswidthtofillparent.

2) Pick list picker fromuser interface andplace it on the horizontalarrangementchangeitsimagebyuploadinganyBluetoothimage3)PlaceabuttonnexttolistpickerthisbuttonwillbeusedfordisconnectingfromtheBluetoothdevice,uploadanyimagetothebuttontomakeitlookmoreattractive.

4) Pick canvas fromDrawingand animation andplace it belowhorizontal arrangement. Change the height of canvas to 250 pixels andwidthtofillparentinthecanvaspropertiestab.

5) Pick horizontal arrangement and place it below canvas edit its

propertiesandchangewidthtofillparent.

6) Pick image picker from media and place it in horizontalarrangementandchange itswidth inproperties to fillparentandchangethetexttoPickanimage.

7) Pick canvas fromdrawing and animation, place next to imagepickerandchangeitspropertieswidthtofillparent.

PlaceLabel1belowtoimagepicker(thiswillstorethecanvasXdata)PlaceLabel2belowlabel1(thiswillstorethecanvasYdata)PlaceLabel3aboveLabel1(thiswillstoreRGandBpixels)changetextlabel3widthtofillparentandtextalignmenttocentre.

PlaceLabel4belowTextlabel2(thislabelwillstoreREDpixelvalue)PlaceLabel5belowTextlabel4(thislabelwillstoreGREENpixelvalue)PlaceLabel6belowTextlabel5(thislabelwillstoreBLUEpixelvalue)

WeusuallyaddalabeltodisplaytoknowconnectivitybetweenBluetoothdevices,alabelneedtoaddforthispurpose.Addlabel7atthetopofBluetooth

anddisconnect

PlaceImagefromuserInterface,anduploadanyRGBimagetoitanduncheck

thevisibleboxinthepropertiesofImage.

Finallyplacenonvisiblecomponentsforthisapp,BluetoothclientandActivitystarterfromconnectivityandclockfromsensors.Designer for Viewer screen has completed and it’s time to program for theviewerscreen,clickontheblockstoprogramit.Initialize twoglobalvariables, thiscanbeofanyvalueand Ichoose“49”and“a”youcanalsochooseanyvalues.

Initialize global blocks can be find the variables and change the names tocolorrpickedandpreviouscolor.

Complete the aboveblocks, thiswill initialize the screen and start the activitystarter will ask us to enable the Bluetooth function if it’s turned off, defaultimagewillbedisplayedinthecanvas.

AboveblockswillsplitRGBcolorandstoreitinlabel4,5,6,whenyoutouchcertainpartof the image theaboveblockhelp to identifyRGBvaluesand thevalueswillbedisplayedinthelabel3.

Whenyoudragaroundtheimage,theaboveblockswillcalculatetheRGBpixelvaluesandseparatethesecolorsandstoreitintherespectivelabels.

Aboveblockwill set an image to the canvas that is currently picked from thegallery,whenyouclickthebuttonitwilldisconnectfromtheBluetoothdevicethathascurrentlyconnectto.

This block will set the label 7 to connect or disconnect based upon the appconnected to Bluetooth devices. When this app connected to the Bluetoothdevices, thiswill send theRGB values from the Label 4, 5 and 6.Completecodeasfollows

ArduinoProgramThisRGBcolorpickerusessamecodeweusedintheRGBcolorslider,but

inthischapteryouhavetochangethe3rdpintoconnectRGBbluepinand6th

pinforREDand5thpinforGreen.CopyandpastethesameArduinocodethatweusedforRGBcolorslider.Circuitconnectionforcommonanode:

Circuitconnectionforcommoncathode:

TemperaturedataintoAndroidInthischapterwegoingtogettemperaturedatafromArduinoanddisplaythe

temperature in android app, and we also going set certain conditions if thetemperatureisbelowthesettemperaturetheninourandroidappitwilldisplayascold, if the temperatureexceeded the set temperature then itwilldisplayasHotandifitfallsintooursettemperaturethenitwilldisplaytextasmoderate,wealsogoingtochangethebackgroundpicturebaseduponthesetemperatures.

1)Picklabel-1andplaceitontopofviewerscreen.

2) Pick horizontal arrangement place it below label-1 and change itspropertiesaswenormallydo3) PlacelistpickerfromuserinterfaceintohorizontalarrangementchangeitsnametoBluetoothandwidthtofillparent4) Placehorizontalarrangementbelowlistpicker,weusethisforemptyspacebetweenlistpickerandalabeltofollow.

5) Pick label andplace it belowemptyhorizontal arrangement 6) Pickanotherlabelandplaceitbelowthepreviouslabel.

7) Pickimagefromuserinterfaceandplaceitonviewerscreenuploadan image for cold conditionanduncheck thevisible in theproperties tohide the image, pick and place another image and upload an image formoderatecondition,dothesameforHotcondition.

Place non visible components Bluetooth Client, Clock and Activity starter,activitystartercanbeplacedfromtheconnectivitypalette.MovetoblocksforprogrammingfortheDesignerwehavecompleted,clickontheblocksandstarttoprogramthebelowblocks.

TheaboveblockswillconnecttotheBluetoothdevice,andwhenappisopenedforthefirsttimeandiftheBluetoothisdisabledactivitystarterwillremindustoturnontheBluetooth.Completethebelowcodetofinishtheprogram.

BlocksusedintheIfcondition

Andblockscanbefindinthelogicofinbuiltfunction,lessthanandgreaterorequaltoblock,isnumber?Willbepresentedinsidetheinbuiltmathfunction.

Thisisexactlylikeplayingapuzzlewhereyouhavetoplaceablockinsideanothertomakeitwork.Theconditionsareusedtocheckwhetherthetemperatureexceedorbelowthe

setconditionanditalsosettheimagetothebackgroundbasedonthetemperature.

ArduinoProgramforTemperatureOn the Arduino side for this chapter we going to use LM35 temperature

sensor,or anyother temperature sensoryouwould like tousecanbeused forthis chapter, if you are changing temperature sensor make sure you alsochangingthecodebasedonthedatasheetforthesensor.

In the above circuit connection, Bluetooth, LM35 temperature sensor andcommonanodetypeRBGLEDareused.

ConnectBluetoothTxpinto10thpinofArduinoandRxto11thpinofArduino.ConnectoutputpinLM35toA0pinofArduino.

ConnectredpinofRGBLEDto6thpinofArduino.

ConnectgreenpinofRGBLEDto5thpinofArduino.

ConnectbluepinofRGBLEDto3rdpinofArduino.ArduinoProgram://codebeginshere:

#include<SoftwareSerial.h>

constintTempsensor=A0;//connectoutputpinoflm35toA0pinofarduinointbluetoothTx=10;//connecttxofbluetoothto10thpinintbluetoothRx=11;//connectrxofbluetoothto11thpin

SoftwareSerialbluetooth(bluetoothTx,bluetoothRx);voidsetup(){

pinMode(Tempsensor,INPUT);pinMode(3,OUTPUT);//bluepin

ofrgbledpinMode(4,OUTPUT);//greenpinofrgbled

pinMode(5,OUTPUT);//redpinofrgbledSerial.begin(9600);//

serialcommunicationbeginsbluetooth.begin(9600);//bluetooth

communicationbegins}voidloop(){floattemp=analogRead(Tempsensor);//readtemperaturesensorvoltage

temp=temp*0.48828125;//(5*1000)/1024=0.48828125fromsensordatasheetSerial.println(”“);//

Serial.println(temp);//watchthecurrenttemperatureinserialmonitorbluetooth.print(”“);

bluetooth.println(temp);//sendtemperaturetobluetoothdevicedelay(200);

if(temp<=30){//iftemperatureisbelow30turnonbluelightdigitalWrite(3,LOW);

digitalWrite(4,HIGH);digitalWrite(5,HIGH);

}

elseif(temp>30&&temp<=34){//iftempisabove30andbelow34turnon

greenlight

digitalWrite(3,HIGH);digitalWrite(4,LOW);

digitalWrite(5,HIGH);

}

elseif(temp>36){//iftemperatureisabove36turnonredlight

digitalWrite(3,HIGH);

digitalWrite(4,HIGH);

digitalWrite(5,LOW);

}

}

//codeendshereType the above program inArduino ide and upload toArduino board, sensordata from LM35 are calculated and send from Arduino to android device,androiddevice receive thesedata throughappwecreated in theprevious step,temperature data will be checked with the set conditions Condition 1: if thetemperature is less than30,uploadbackground image tophoto related to coldcondition and change the label 3 to cold Condition 2: if the temperature isgreater than30and less than34,uploadbackground image tophoto related tomoderate condition and change the label 3 to moderate Condition 3: if thetemperatureexceeds34thensettheimagetohotconditionandalsochangethe

labeltoHOT.

AndroidRemotecontrolRobotThis app is very similar to the first chapterwecreated to turnon andoff a

singleLED that has connected toArduino, in this chapterwegoing to send5different commands from android app and execute certain functions on theArduinoside.

1) Picka labelandplace iton the topofViewerScreenandedit thepropertiesofthelabel2)Pickhorizontalarrangementandplaceitbelowlabel.

3) Pick list picker and place it inside horizontal arrangement andchangethebackgroundimageoflistpickertosomeBluetoothimage.

4) Pick table arrangement from layout edit the properties of tablearrangementandentercolumnas3androwas3andwidthtofillparent.

5)Pickbuttonfromuserinterfaceandplaceitaroundthetable,arrangefivebuttonandchangetheimagesofthebuttontoreflectlikethebelowscreenshot.

AftercompletingtheaboveViewerscreenmoveontoblocksbyclickingontheblocksontheupperrightsideintheMITappinventorwindow.

CompletetheaboveblockforBluetoothcommunicationandalsonotificationinthe text label if theandroiddeviceconnected toBluetoothdeviceconnected toArduino.

Completetheaboveblockstofinishtheprogram,whenyoupresstheuparrowthatbutton is associated tobutton1 it should send forwardas command,whenyoupressdownarrowthatbuttonisassociatedtobutton4itshouldsendreverse,likewisethecommandwillsendfromtheappbasedontheselectionofbutton.

Thinkaboutthebuttonconnectivitywhenprogrammingthathasnotdetailedinthischapteraswecrossedmanytutorialsthisisreallysimplethinkyourselfandaccomplishthetask.

ArduinoProgramforAndroidremoteFormakingthisprojectyouneedmanycomponents,inthepreviouschapters

wehaveusedsimplecomponentsandweneverusedmorethan2componentsinallthechapters,whencomingtorobot,itinvolveslotofcomponentstomakeitworkFollowsthelistofcomponents:ArduinoUnoBluetoothModule(HC-05orHC-06)

L293DMotordriver

2xGearMotors

1xcastorwheel

2xWheelsforGearmotor

9vbatteryRobotchassis1xbreadboardandconnectingwires.

Connectthecomponentsasshowninthecircuit,itisbitcomplicatedifyouarestartingwith electronics and robotics, insteadofL293d ICyouuse anyMotordrivermodulewhicheliminatefuzzyconnectiontotheIC.

This robotworksbasedon thesignalpassedfromArduino to themotordriverIC,allthemotordriverhavesomelogicbehindit.Aboveimagesshowsthemotordriverpinconfigurationandlogicbehindthe

motordriver,whenyousupplyHighandLowsignaltotheinput1andinput2MotorconnectedtoOutput1andOutput2willrotateclockwise,whenthesignalischangedtoLowandHighmotorwillstarttorotateintheanticlockwise.Usingthesamelogic,whenwereceiveaforwardcommandfromandroidapp,wehavetosendaHightoinput1andlowtoinput2andHightoinput4andlowtoinput3thismaketwomotorstorotateforward.

Arduinocode://codebeginshere#include<SoftwareSerial.h>

SoftwareSerialBT(10,11);//TX,RXrespetivelyStringreaddata;

voidsetup(){

BT.begin(9600);

Serial.begin(9600);

pinMode(3,OUTPUT);//connecttoinput1ofl293dpinMode(4,OUTPUT);

//connecttoinput4ofl293dpinMode(5,OUTPUT);//connecttoinput3of

l293dpinMode(6,OUTPUT);//connecttoinput2ofl293d}

//–––––––––––––––––––––––—//voidloop(){

while(BT.available()){//Checkifthereisanavailablebytetoreaddelay(10);//Delayaddedtomakethingstablecharc=BT.read();//Conductaserialread

readdata+=c;//buildthestring-“forward”,“reverse”,“left”and“right”

}

if(readdata.length()>0){

Serial.println(readdata);//printdatatoserialmonitor//ifdatareceivedasforwardmoverobotforwardif(readdata==“forward”){

digitalWrite(3,HIGH);digitalWrite(4,HIGH);digitalWrite(5,LOW);

digitalWrite(6,LOW);delay(100);

}

//ifdatareceivedasreversemoverobotreverse

elseif(readdata==“reverse”)

{

digitalWrite(3, LOW);digitalWrite(4, LOW);digitalWrite(5, HIGH);digitalWrite(6,HIGH);delay(100);}

//ifdatareceivedasrightturnrobottorightdirection.elseif(readdata==“right”){

digitalWrite (3,HIGH);digitalWrite (4,LOW);digitalWrite (5,LOW);digitalWrite (6,LOW); delay(100);}

// if data received as left turn robot to left direction else if ( readdata==“left”){

digitalWrite (3, LOW);digitalWrite (4, HIGH);digitalWrite (5, LOW);digitalWrite (6, LOW); delay(100);}

//ifdatareceivedasstop,halttherobotelseif(readdata==“stop”)

{

digitalWrite (3, LOW); digitalWrite (4, LOW);digitalWrite(5,LOW);digitalWrite(6,LOW);delay(100);}

readdata=””;}}//Resetthevariable//codeendshere

ControlthesamerobotbyspeechrecognitionUsetheappcreatedinthebeginningchapterandspeaktoyourspeechrecognitionsendcommandslike“forward”“reverse”“left”“right”and“stop”andplaywiththerobot.

HowtoimportaiafilestoMITappinventor

Clickprojectsandselectimportproject(.aia)frommycomputer.ClickbrowseandpointtoaiafilelocationinyourPCorlaptop

Contactandappinventorfiles.Forsuggestionsandqueriesyoucanalwaysmailmeatjayakumarmagesh@gmail.comForallthecodeandnecessarydocumentsforthisbookpleaseclickhere

Recommended