mit app inventor v 2.0: app creation that transforms

167

Upload: others

Post on 11-Sep-2021

11 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: MIT App Inventor V 2.0: app creation that transforms
Page 2: MIT App Inventor V 2.0: app creation that transforms
Page 3: MIT App Inventor V 2.0: app creation that transforms

TableofContentsIntroduction

WhatisMITAppInventor?Arduino(FromArduinoWebsite)

TurnOnandOFFanLED(HelloWorld)CreatingAndroidApp

ConnectingBluetoothandprogrammingArduinoControlLEDbySpeechrecognition

TaskControlaServoMotor

ArduinocodeforservocontrolControlMultipleServoMotors

ArduinoCodeMultipleservoRGBColorSlider

Activitystarter

CompleteprogramfortheRGBSliderArduinoProgramforRGBSlider

CommonanodeArduinoprogramCommonCathodeArduinoprogramRGBColorPicker

ArduinoProgram

TemperaturedataintoAndroidArduinoProgramforTemperature

AndroidRemotecontrolRobotArduinoProgramforAndroidremote

ControlthesamerobotbyspeechrecognitionHowtoimportaiafilestoMITappinventorContactandappinventorfiles.

Page 4: MIT App Inventor V 2.0: app creation that transforms

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.

Page 5: MIT App Inventor V 2.0: app creation that transforms

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.

Page 6: MIT App Inventor V 2.0: app creation that transforms

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.

Page 7: MIT App Inventor V 2.0: app creation that transforms

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

Page 8: MIT App Inventor V 2.0: app creation that transforms

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.

Page 9: MIT App Inventor V 2.0: app creation that transforms

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.

Page 10: MIT App Inventor V 2.0: app creation that transforms

Ontheleftsideofthetableproperties,changecolumnsandrowsto3andalsochangethewidthtofillparentfromautomatic.

Page 11: MIT App Inventor V 2.0: app creation that transforms

PickListpickerfromUserInterfaceanddropintofirstrowintheViewerscreen.ThisusedtoconnecttoyourBluetoothdevice.WhenyouclickthisbuttonitwilldisplayavailableBluetoothdevices.

Page 12: MIT App Inventor V 2.0: app creation that transforms

SelectListPickerfromtheComponentsList

GotolistpickerpropertiesandchangethetexttoBluetoothandyoucanalsouploadanimagefiletothelistpicker.

Page 13: MIT App Inventor V 2.0: app creation that transforms
Page 14: MIT App Inventor V 2.0: app creation that transforms

ClickontheNonetabbelowImageanduploadyourBluetoothpicturetosetittoListpicker.

Page 15: MIT App Inventor V 2.0: app creation that transforms

Click theupload fileandbrowse to the imageyouwant tousefortheListPicker,iftheViewerScreendisplaystheImagefortheListPickerinlargersizeyouneedtoaltertheheightandwidthoftheListPickerbygoingtothepropertiesfortheListpicker.

Page 16: MIT App Inventor V 2.0: app creation that transforms

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

ClickonthefirstbuttonandgothebuttonpropertiesandchangethenameofthebuttontoONdothesame

forthesecondbuttonbychangingthenameofthebuttontoOFF.

Page 17: MIT App Inventor V 2.0: app creation that transforms
Page 18: MIT App Inventor V 2.0: app creation that transforms

Changebuttoncolorbychangingthebackgroundcolorfrompropertiesoftheappropriatebutton.

PickandplaceLabelfromuserinterfaceandplaceintothe3rdrowofViewer

Page 19: MIT App Inventor V 2.0: app creation that transforms

Screen.GotopropertiesandremovetheTextlabelandleavethisasempty,thislabelwilllateronusedforindicatingwhetherourapphasconnectedtoanBluetoothornot.

Page 20: MIT App Inventor V 2.0: app creation that transforms

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

Page 21: MIT App Inventor V 2.0: app creation that transforms

Itprovidestheinstantintimeusingtheinternalclockonthephone.Itcanfireatimeratregularlysetintervalsandperformtimecalculations,manipulations,andconversions.Weareusingclocktocauseactivitiestooccuratapresetinterval.

Page 22: MIT App Inventor V 2.0: app creation that transforms

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

Page 23: MIT App Inventor V 2.0: app creation that transforms

Clickontheblockstogetintoprogrammingmode.

Page 24: MIT App Inventor V 2.0: app creation that transforms

ClickListPicker1andselectwhen.listpicker1.BeforePickingblockandplaceintoprogrammingwindow.

Page 25: MIT App Inventor V 2.0: app creation that transforms
Page 26: MIT App Inventor V 2.0: app creation that transforms

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.

Page 27: MIT App Inventor V 2.0: app creation that transforms

Ifthenblockcanbepickfromthebuiltinfunctions.

Page 28: MIT App Inventor V 2.0: app creation that transforms

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.

Page 29: MIT App Inventor V 2.0: app creation that transforms

Thethirdblockwhichisplacedinsideatimer,thisblockwillassignConnectedtexttoTextLabelonthethirdrowiftheBluetoothdeviceisconnectedifthedeviceisnot

Page 30: MIT App Inventor V 2.0: app creation that transforms

connectedTextlabelwilldisplaymessageasNotConnected.Completetheblockbyusingtheabovescreenshot.TextstringblockcanbeaddedfromTextinbuiltfunction

Page 31: MIT App Inventor V 2.0: app creation that transforms

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

Page 32: MIT App Inventor V 2.0: app creation that transforms

Andwearejustfewstepsawayfromcompletingourapp.YouneedtocreateacontroltaskforthetwobuttonwecreatedintheViewerscreen.Completethecodeforbutton

Page 33: MIT App Inventor V 2.0: app creation that transforms

usingthescreenshotbelow.

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

BluetoothdeviceattachedtoArduino,whenArduinoreceivethesetwostringwehavetoprogrambasedon

thesestringandmakeadecisiontoturnOnandOffanLED.

Page 34: MIT App Inventor V 2.0: app creation that transforms

Here’sthecompleteblockfortheFirstprogramtocontrolanLEDconnectedtoanArduino.Checkyourblockwiththisblockandmakesureyouhavenotmadeanymistakewhenconnectingtheblocks.

Page 35: MIT App Inventor V 2.0: app creation that transforms
Page 36: MIT App Inventor V 2.0: app creation that transforms

CreatingAndroidAppConvertyourblockintoandroidapp.Clickbuildandselectapp(save.apktomycomputer).

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

Page 37: MIT App Inventor V 2.0: app creation that transforms

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’.

Page 38: MIT App Inventor V 2.0: app creation that transforms

ConnectingBluetoothandprogrammingArduinoNowconnectyourBluetoothdevicetoArduinoboard,connectionasfollows

Page 39: MIT App Inventor V 2.0: app creation that transforms

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

Page 40: MIT App Inventor V 2.0: app creation that transforms

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

Page 41: MIT App Inventor V 2.0: app creation that transforms

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

Page 42: MIT App Inventor V 2.0: app creation that transforms

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.

Page 43: MIT App Inventor V 2.0: app creation that transforms

Gotopropertiesofthelabelandchangethewidthtofillparentanddeletethetext

Page 44: MIT App Inventor V 2.0: app creation that transforms

3)Pickandplacehorizontalarrangementfromlayoutandchangethepropertiesofwidthtofillparent.

Page 45: MIT App Inventor V 2.0: app creation that transforms

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

5)Pickanotherhorizontalarrangementtableandfromlayout,thistablewilladdaspacebetweentheBluetoothpickerandbuttonwhichwilllookgoodinsteadofthebuttonimmediatelyfollowstheBluetoothpicker.

Page 46: MIT App Inventor V 2.0: app creation that transforms

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.

Page 47: MIT App Inventor V 2.0: app creation that transforms
Page 48: MIT App Inventor V 2.0: app creation that transforms

7)Addalabelbelowpresstotalkbutton,thislabelwillbeusedtodisplaytheresultfromspeechrecognitioneditthepropertiesoflabelandremovethedefaulttextassociatedwiththislabelandchangethewidthtofillparentandmakethetextaligntocentre.

Page 49: MIT App Inventor V 2.0: app creation that transforms

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

Page 50: MIT App Inventor V 2.0: app creation that transforms
Page 51: MIT App Inventor V 2.0: app creation that transforms

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

Page 52: MIT App Inventor V 2.0: app creation that transforms

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.

Page 53: MIT App Inventor V 2.0: app creation that transforms
Page 54: MIT App Inventor V 2.0: app creation that transforms

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.

Page 55: MIT App Inventor V 2.0: app creation that transforms

Thisblockwillhelpustoemptythetextthatpreviouslyoccupiedinlabel2.NowwewilladdblocksforsendingtheconvertedspeechtotextcharacterasaBluetoothmessageandalsodisplaythetextinlabel2.

AboveblockwillsendtheresultasstringtotheBluetoothdeviceconnectedtoArduino,wehavealreadyprogrammedArduino,soifthetextmatchestoitthenArduinowillexecuteappropriatefunctionthatisassociatedwiththetext.

Page 56: MIT App Inventor V 2.0: app creation that transforms
Page 57: MIT App Inventor V 2.0: app creation that transforms

Completeprogramforthespeechrecognitionhasgivenintheabovescreenshot,thatcanbeusedtoverifywhetheryouhaveprogrammedwithoutanyerrorsornot.UploadthesameArduinoprogramtoyourArduinoboardandstarttalkingtoyourapp,whenyousayONtheledontheArduinowillgoesonandwhenyousayOFFledontheArduinosidewillgoesoff,checkthisappwithyourAndroiddevice.ReferConnectingBluetoothandprogrammingArduino

Page 58: MIT App Inventor V 2.0: app creation that transforms

TaskCombineboththeappspeechrecognitionandbuttoncontrolintooneappandplaywithyourandroidArduino.

Page 59: MIT App Inventor V 2.0: app creation that transforms

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.

Page 60: MIT App Inventor V 2.0: app creation that transforms
Page 61: MIT App Inventor V 2.0: app creation that transforms

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

Page 62: MIT App Inventor V 2.0: app creation that transforms

valueto180andMinvalueto0.

10)Pickandplaceinvisiblecomponents,BluetoothclientandclockintoViewerscreen.

Designerpartisoverandtheprogrammingpartisleftover,clickontheblocksontheupperrightsideoftheAppinventorwindow.Completethefirst3blockswhichhasrepeatedinthefirst2chapters,ifyouhaveskippedthesechaptersanddirectlylaunchedintothischapter,pleasegothroughfirstorsecondchaptertomakesurehowthiscodeworksandwhatyoushoulddotocompletethebelowcodegiveninthescreenshot.

Page 63: MIT App Inventor V 2.0: app creation that transforms

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

Page 64: MIT App Inventor V 2.0: app creation that transforms

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

Page 65: MIT App Inventor V 2.0: app creation that transforms

Roundfunctionwillbenewtoyouandthisfunctionisintroduceinthischapter,theround

Page 66: MIT App Inventor V 2.0: app creation that transforms

functionhelpustoroundanumberallthenumberwillbepresentedasawholenumber.Thisblockisavailableinthebuiltinmathblock.

Completethebelowblockforsendingnumberswheneachbuttonispressed,wehavecreatedfivebuttonsintheViewerscreenandeachbuttonhasassignedanumber,whenwepressabuttonthenumberassignedtothenumbershouldsendtotheconnectedBluetoothdevice.Blocktogivenumberinputcanbefindinthemathbuiltinfunction.

Page 67: MIT App Inventor V 2.0: app creation that transforms

ArduinocodeforservocontrolIn thissectionwewillknowhowtoconnect theservomotorandBluetooth toyourArduino.

Page 68: MIT App Inventor V 2.0: app creation that transforms

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:

Page 69: MIT App Inventor V 2.0: app creation that transforms

//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

Page 70: MIT App Inventor V 2.0: app creation that transforms

printservoposcurrentnumberreceivedfrombluetoothmyservo.write(servopos);//roatetheservothe

anglereceivedfromtheandroidapp}

}

//codeendshere.

Page 71: MIT App Inventor V 2.0: app creation that transforms

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.

Page 72: MIT App Inventor V 2.0: app creation that transforms
Page 73: MIT App Inventor V 2.0: app creation that transforms

Selectslider1andchangeitspropertieswidthtofillparentandchangemaximumvalueto1180andminimumvalueto1000andalsothumbpositionto1000

Page 74: MIT App Inventor V 2.0: app creation that transforms

Selectsecondsliderandchangeitspropertieswidthtofillparentandchangemaximumvalueto2180andminimumvalueto2000andalsothumbpositionto2000.Selectthirdsliderandchangeitspropertieswidthtofillparentandchangemaximumvalueto3180andminimumvalueto3000andalsothumbpositionto3000.Selectfourthsliderandchangeitspropertieswidthtofillparentandchangemaximum

Page 75: MIT App Inventor V 2.0: app creation that transforms

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.

Page 76: MIT App Inventor V 2.0: app creation that transforms

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

Page 77: MIT App Inventor V 2.0: app creation that transforms

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

Page 78: MIT App Inventor V 2.0: app creation that transforms

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.

Page 79: MIT App Inventor V 2.0: app creation that transforms

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;

Page 80: MIT App Inventor V 2.0: app creation that transforms

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{

Page 81: MIT App Inventor V 2.0: app creation that transforms

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);

Page 82: MIT App Inventor V 2.0: app creation that transforms

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){

Page 83: MIT App Inventor V 2.0: app creation that transforms

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

}

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

Page 84: MIT App Inventor V 2.0: app creation that transforms

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

Page 85: MIT App Inventor V 2.0: app creation that transforms

UploadtheaboveprogramtoyourArduinoboardandconnecttoyourandroidapp,youcanchecktheserialmonitorforthedatareceivingfromtheandroidapp.

Page 86: MIT App Inventor V 2.0: app creation that transforms

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.

Page 87: MIT App Inventor V 2.0: app creation that transforms

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.

Page 88: MIT App Inventor V 2.0: app creation that transforms

5) Pick3sliderandplace

Page 89: MIT App Inventor V 2.0: app creation that transforms

itoneafteranother.

Page 90: MIT App Inventor V 2.0: app creation that transforms

Changethepropertiesofsliderasfollows

PlacenonvisiblecomponentsBluetoothClient,ClockandActivitystarter,activitystartercanbeplacedfromtheconnectivitypalette.

Page 91: MIT App Inventor V 2.0: app creation that transforms

Designerpartforthisapphascompletedmoveontotheblocksforprogrammingthisapp,clickontheblockstomovetotheprogrammingwindow.

ProgramtheRGBsliderchooserblocksforconnectingtoaBluetoothdevice,abovecodewillshowthelist

ofavailableBluetoothdevicesthatyoupairedalreadyandonceyouconnecttoadevicethiswillsavethe

addressoftheBluetoothdeviceandconnecttoit.

Page 92: MIT App Inventor V 2.0: app creation that transforms

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.

Page 93: MIT App Inventor V 2.0: app creation that transforms

Whenthescreeninitialize,aswediscussedalreadyiftheBluetoothisnotcurrentlyturned

Page 94: MIT App Inventor V 2.0: app creation that transforms

ontheactivitystartershouldremindustoturnontheBluetoothdevice,andalsothecanvasshouldbesetto

whitecolor.Completetheblocksgivenbelowdoallthisfunctions.

Page 95: MIT App Inventor V 2.0: app creation that transforms

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.

Page 96: MIT App Inventor V 2.0: app creation that transforms

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

Page 97: MIT App Inventor V 2.0: app creation that transforms
Page 98: MIT App Inventor V 2.0: app creation that transforms

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

Page 99: MIT App Inventor V 2.0: app creation that transforms

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

Page 100: MIT App Inventor V 2.0: app creation that transforms

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.

Page 101: MIT App Inventor V 2.0: app creation that transforms
Page 102: MIT App Inventor V 2.0: app creation that transforms

CompleteprogramfortheRGBSlider

Page 103: MIT App Inventor V 2.0: app creation that transforms

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

cathodeandanotheroneiscommonanode.MakesurewhattypeofRGBLEDyouareusingforyourpractice.CommonAnodeType

Page 104: MIT App Inventor V 2.0: app creation that transforms

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

Page 105: MIT App Inventor V 2.0: app creation that transforms

Ifyouhaveacommoncathode typeRGBLED thenyouhave toconnectyourcathode togroundpinof

Arduino.Connecttheredpinto3rdpinofArduinogreenpinto5thpinofArduinoandbluepinto6thpin

ofArduino.ConnectBluetoothTxto7thpinandRxto8th

Page 106: MIT App Inventor V 2.0: app creation that transforms

pinofArduino.Youalsoneedtoconnect220ohmresistorbetweenthepinsofLEDandArduinotoprotectitfromburning.

Page 107: MIT App Inventor V 2.0: app creation that transforms

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=

Page 108: MIT App Inventor V 2.0: app creation that transforms

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

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

Page 109: MIT App Inventor V 2.0: app creation that transforms

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);

}

}

Page 110: MIT App Inventor V 2.0: app creation that transforms

}

ThisprogramissameastheMutliservoprogramthatwedidinthepreviouschapter.

Page 111: MIT App Inventor V 2.0: app creation that transforms

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)

{

Page 112: MIT App Inventor V 2.0: app creation that transforms

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

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

Page 113: MIT App Inventor V 2.0: app creation that transforms

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);

Page 114: MIT App Inventor V 2.0: app creation that transforms

delay(10);

}

}

}

ThisprogramissameastheMutliservoprogramthatwedidinthepreviouschapter.

Page 115: MIT App Inventor V 2.0: app creation that transforms

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

Page 116: MIT App Inventor V 2.0: app creation that transforms

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.

Page 117: MIT App Inventor V 2.0: app creation that transforms

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

Page 118: MIT App Inventor V 2.0: app creation that transforms

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

WeusuallyaddalabeltodisplaytoknowconnectivitybetweenBluetoothdevices,alabelneedtoaddforthispurpose.Addlabel7atthetopofBluetooth

anddisconnect

PlaceImagefromuserInterface,anduploadanyRGBimagetoitanduncheck

Page 119: MIT App Inventor V 2.0: app creation that transforms

thevisibleboxinthepropertiesofImage.

Page 120: MIT App Inventor V 2.0: app creation that transforms

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.

Page 121: MIT App Inventor V 2.0: app creation that transforms

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.

Page 122: MIT App Inventor V 2.0: app creation that transforms

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

Page 123: MIT App Inventor V 2.0: app creation that transforms
Page 124: MIT App Inventor V 2.0: app creation that transforms

Whenyoudragaroundtheimage,theaboveblockswillcalculatetheRGBpixelvaluesandseparatethesecolorsandstoreitintherespectivelabels.

Page 125: MIT App Inventor V 2.0: app creation that transforms

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

Page 126: MIT App Inventor V 2.0: app creation that transforms

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

Page 127: MIT App Inventor V 2.0: app creation that transforms
Page 128: MIT App Inventor V 2.0: app creation that transforms
Page 129: MIT App Inventor V 2.0: app creation that transforms

ArduinoProgramThisRGBcolorpickerusessamecodeweusedintheRGBcolorslider,but

inthischapteryouhavetochangethe3rdpintoconnectRGBbluepinand6th

pinforREDand5thpinforGreen.CopyandpastethesameArduinocodethatweusedforRGBcolorslider.Circuitconnectionforcommonanode:

Page 130: MIT App Inventor V 2.0: app creation that transforms

Circuitconnectionforcommoncathode:

Page 131: MIT App Inventor V 2.0: app creation that transforms

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.

Page 132: MIT App Inventor V 2.0: app creation that transforms
Page 133: MIT App Inventor V 2.0: app creation that transforms

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

TheaboveblockswillconnecttotheBluetoothdevice,andwhenappisopenedforthefirsttimeandiftheBluetoothisdisabledactivitystarterwillremindustoturnontheBluetooth.Completethebelowcodetofinishtheprogram.

Page 134: MIT App Inventor V 2.0: app creation that transforms
Page 135: MIT App Inventor V 2.0: app creation that transforms

BlocksusedintheIfcondition

Page 136: MIT App Inventor V 2.0: app creation that transforms

Andblockscanbefindinthelogicofinbuiltfunction,lessthanandgreaterorequaltoblock,isnumber?Willbepresentedinsidetheinbuiltmathfunction.

Page 137: MIT App Inventor V 2.0: app creation that transforms

Thisisexactlylikeplayingapuzzlewhereyouhavetoplaceablockinsideanothertomakeitwork.Theconditionsareusedtocheckwhetherthetemperatureexceedorbelowthe

Page 138: MIT App Inventor V 2.0: app creation that transforms

setconditionanditalsosettheimagetothebackgroundbasedonthetemperature.

Page 139: MIT App Inventor V 2.0: app creation that transforms

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.

Page 140: MIT App Inventor V 2.0: app creation that transforms

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

ConnectBluetoothTxpinto10thpinofArduinoandRxto11thpinofArduino.ConnectoutputpinLM35toA0pinofArduino.

ConnectredpinofRGBLEDto6thpinofArduino.

ConnectgreenpinofRGBLEDto5thpinofArduino.

ConnectbluepinofRGBLEDto3rdpinofArduino.ArduinoProgram://codebeginshere:

Page 141: MIT App Inventor V 2.0: app creation that transforms

#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);

Page 142: MIT App Inventor V 2.0: app creation that transforms

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

}

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

greenlight

Page 143: MIT App Inventor V 2.0: app creation that transforms

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

Page 144: MIT App Inventor V 2.0: app creation that transforms

labeltoHOT.

Page 145: MIT App Inventor V 2.0: app creation that transforms

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.

Page 146: MIT App Inventor V 2.0: app creation that transforms

5)Pickbuttonfromuserinterfaceandplaceitaroundthetable,arrangefivebuttonandchangetheimagesofthebuttontoreflectlikethebelowscreenshot.

Page 147: MIT App Inventor V 2.0: app creation that transforms

AftercompletingtheaboveViewerscreenmoveontoblocksbyclickingontheblocksontheupperrightsideintheMITappinventorwindow.

Page 148: MIT App Inventor V 2.0: app creation that transforms

CompletetheaboveblockforBluetoothcommunicationandalsonotificationinthe text label if theandroiddeviceconnected toBluetoothdeviceconnected toArduino.

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

Page 149: MIT App Inventor V 2.0: app creation that transforms

Thinkaboutthebuttonconnectivitywhenprogrammingthathasnotdetailedinthischapteraswecrossedmanytutorialsthisisreallysimplethinkyourselfandaccomplishthetask.

Page 150: MIT App Inventor V 2.0: app creation that transforms

ArduinoProgramforAndroidremoteFormakingthisprojectyouneedmanycomponents,inthepreviouschapters

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

Page 151: MIT App Inventor V 2.0: app creation that transforms

L293DMotordriver

Page 152: MIT App Inventor V 2.0: app creation that transforms

2xGearMotors

Page 153: MIT App Inventor V 2.0: app creation that transforms

1xcastorwheel

Page 154: MIT App Inventor V 2.0: app creation that transforms

2xWheelsforGearmotor

Page 155: MIT App Inventor V 2.0: app creation that transforms

9vbatteryRobotchassis1xbreadboardandconnectingwires.

Page 156: MIT App Inventor V 2.0: app creation that transforms

Connectthecomponentsasshowninthecircuit,itisbitcomplicatedifyouarestartingwith electronics and robotics, insteadofL293d ICyouuse anyMotordrivermodulewhicheliminatefuzzyconnectiontotheIC.

Page 157: MIT App Inventor V 2.0: app creation that transforms

This robotworksbasedon thesignalpassedfromArduino to themotordriverIC,allthemotordriverhavesomelogicbehindit.Aboveimagesshowsthemotordriverpinconfigurationandlogicbehindthe

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

Page 158: MIT App Inventor V 2.0: app creation that transforms
Page 159: MIT App Inventor V 2.0: app creation that transforms

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

Page 160: MIT App Inventor V 2.0: app creation that transforms

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);

Page 161: MIT App Inventor V 2.0: app creation that transforms

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

}

//ifdatareceivedasreversemoverobotreverse

Page 162: MIT App Inventor V 2.0: app creation that transforms

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”)

Page 163: MIT App Inventor V 2.0: app creation that transforms

{

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

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

Page 164: MIT App Inventor V 2.0: app creation that transforms

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

Page 165: MIT App Inventor V 2.0: app creation that transforms

HowtoimportaiafilestoMITappinventor

Page 166: MIT App Inventor V 2.0: app creation that transforms

Clickprojectsandselectimportproject(.aia)frommycomputer.ClickbrowseandpointtoaiafilelocationinyourPCorlaptop

Page 167: MIT App Inventor V 2.0: app creation that transforms

Contactandappinventorfiles.Forsuggestionsandqueriesyoucanalwaysmailmeatjayakumarmagesh@gmail.comForallthecodeandnecessarydocumentsforthisbookpleaseclickhere