0% found this document useful (0 votes)
220 views43 pages

Connect Arduino Uno To Android Via Bluetooth

Connect Arduino Uno to Android via Bluetooth

Uploaded by

Restu Adtya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
220 views43 pages

Connect Arduino Uno To Android Via Bluetooth

Connect Arduino Uno to Android via Bluetooth

Uploaded by

Restu Adtya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 43

let's make Explore(/tag/typeid/) Publish(/about/create.

jsp) You (/you/)

Featured: share what you make


IntelIoT(/id/intel/) LifeHacks(/tag/typeid/categoryhome/channellifehacks/?sort=FEATURED)
(/)
Beauty(/tag/typeid/categoryhome/channelbeauty/?sort=FEATURED) Woodworking(/tag/typeid/categoryworkshop/channelwoodworking/)

AboutThisInstructable

Posted:
141,077views Apr27,2014
120favorites License:

pmosconi
(/member/pmosconi/)
Follow 7

(/member/pmosconi/)

Tags:
Arduino(/tag/typeid/categorytechnology/keyw ordarduino/)

Android(/tag/typeid/categorytechnology/keyw ordandroid/)

Bluetooth(/tag/typeid/categorytechnology/keyw ordbluetooth/)

MITAppInventor(/tag/typeid/categorytechnology/keyw ordmit+app+inventor/)

Addinstructableto:

Group
Related

Bluetoothcontrolled
homeelectronic
appliances
(/id/INTRODUCTION59/)
byachakravarthi
Howtocontrolservo
motorfromandroidapp
(/id/Howtocontrolservo
motorfromandroidapp/)
byMageshJayakumar
Drivingmotorwith
androidusingarduino
andbluetooth
(/id/Drivingmotorwith
androidusingarduino
Arduino+Androidburglar
alarmHomeautomation
(/id/Makenoise
ArduinoTweetandSMS
usingAndroidApp/)
RCSubmarineHack
Androidcontroller
(Arduino,Android,
Submarine,Bluetooth)
(/id/RCSubmarineHack
SeeMore(/tag/typeid/?q=)

(http://cdn.instructables.com/FEM/XC88/HTX5KJWO/FEMXC88HTX5KJWO.LARGE.jpg)
(http://cdn.instructables.com/FJ4/POS3/HUFW6Q8F/FJ4POS3HUFW6Q8F.LARGE.jpg)
InthisprojectaserialBluetoothmoduleisusedtocreateaconnectionbetween
ArduinoUnoandanAndroidappthatIcreatedwithMITAppInventor.
ArduinolistensforcommandstolightsomeLED'sorshowitsstatus.Inaddition,a
timerinterruptmakesitcheckfortemperatureviaaTMP36sensor:iftemperature
isgreaterthanathresholdaLEDisliteverynseconds(wherenisaparameter
setthroughtheapp)astatusreportissenttotheapp.Asimplecommandstructure
enablestheapptosendparametersandvaluestoArduinoandtheotherway
round.
TherearemanyBluetoothmodulesandevenArduinoshields:mychoicehasfallen
onJYMCUthatIboughtfromHobbyComponents(http://hobbycomponents.com/)
intheUK.
TheJYMCUisaclass2Bluetoothmodulethatactslikeaserialportwithnoneed
ofanysoftwareconfigurationontheArduino.Thismoduleisavailableinseveral
configurations,andthishasbeenthefirsthurdletoovercome.
TheoneweneedtomaketheconnectionbetweenArduinoandtheAndroidphone
isaSlaveModule(http://hobbycomponents.com/index.php/arduinojymcu
bluetoothwirelessserialportmodule.html).Tomakethingsverysimple,thereare
twotypesofdevices:MasterandSlaveaMastercancommunicatewithmorethan
oneSlavewhileaSlavecancommunicatewithasingleMasteratatime,Master
MasterandSlaveSlavecommunicationisnotallowed.SincetheBluetooth
moduleinallsmartphonesisofMastertype,theoneweneedforArduino
mustbeaSlave(thishasnothingtodowithclientservercommunicationaswe'll
seelaterintheappdescription).

Step1:TheCircuit

(http://cdn.instructables.com/FVJ/MJIE/HTX5KJJ5/FVJMJIEHTX5KJJ5.LARGE.jpg)
Components:
1xArduinoUno
3x220OhmResistrors
1xGreenLED
1xYellowLED
1xRedLED
1xTMP36TemperatureSensor
1xJYMCUBluetoothSlaveModule(seeintroduction)
1xBreadboard
wires
Connections:
Step1):ConnectGroundand5VfromArduinotobreadboard.
Step2):PlacetheLEDsonthebreadboardandconnecttheircatodestoground
connecttheiranodestoDigitalPinsthrougha220Ohmresistoreach:YellowtoPin
3,GreentoPin4andRedtoPin5.
Step3):PlacetheTMP36sensoronthebreadboardandconnectitspinsto5V,
GroundandA0ArduinoPin.
Step4):ConnecttheprovidedcabletotheJYMCUBluetoothmoduleononeside
andtothebreadboardtotheothersideconnectionsareasfollows:
VCC<>5V
GND<>GND
TXD<>Pin0(Rx)
RXD<>Pin1(Tx)
ThesketchwillalsomakeuseofArduinobuiltinLEDonDigitalPin13.
TheconnectionsoftheBluetoothmodulecanbealittleconfusingsinceTXDgoes
toRxandRXDgoestoTx:here'sanexplanation.TransmitandReceivereferto
eachdevice,thereforeatransmissioncomingoutofTXDpinoftheBluetooth
modulemustbereceivedbyArduinoontheRxPin0similarlyatransmissiongoing
outofArduinoTxPin1mustreachtheJYMCUBluetoothmoduleonitsRXDpin.
Warning:TheBluetoothmodulemayinterferewithPCtoArduinocommunication:
disconnectVCCwhenprogrammingtheboard.(inmyteststhishasnotbeenthe
case,butforsureitwon'tdoanyharm).
Step2:ArduinoCodeIntroduction

(http://cdn.instructables.com/FXC/70OB/HUFW6SXB/FXC70OBHUFW6SXB.LARGE.jpg)

ArduinolistensforcommandstolightsomeLED'sorshowitsstatus.Inaddition,a
timerinterruptmakesitcheckfortemperatureviaaTMP36sensor:iftemperature
isgreaterthanathresholdaLEDisliteverynseconds(wherenisaparameter
setthroughtheapp)astatusreportissenttotheapp.Asimplecommandstructure
enablestheapptosendparametersandvaluestoArduinoandtheotherway
round.
Thecommandstructuredefinedintheprogramis:
CMDRED|GREEN|YELLOW=ON|OFF
CMDTMAX|SECONDS=value
CMDSECONDS=value
CMDSTATUS
TheStatusmessagestructureis:
STATUSRED|GREEN|YELLOW|TMAX|SECONDS|TEMP|THIGH=value
ArduinowillanswertotheSTATUScommandwithfullstatuswhileoninterruptitwill
reportashorterversion.
Examples:
CMDRED=ONswitchestheredLEDon
CMDGREEN=OFFswitchesthegreenLEDoff
YoucantestthesketchbyissuingcommandsandviewingresponsesinArduino
IDE'sSerialMonitor:makesuretoselectCarriageReturninthedropdownoptions
atthebottom.
Youcandownloadthesketchcodefromtheattachedfile.Thefollowingstepwill
provideadetailedexplanationofit.

BtOnSerial_Interrupt.ino (/files/orig/FUS/JGRP/HUFW6SO4/FUSJGRPHUFW6SO4.ino)7KB

Step3:ArduinoCodeDetails
Commandandmessagestructureasdescribedinthepreviousstep
//SerialParameters:COM1196008N1
//\ror\ntoendcommandline
//BluetoothisonPin0&1@9600speed
//Commandstructure//CMDRED|GREEN|YELLOW=ON|OFF
//CMDTMAX|SECONDS=value
//CMDSECONDS=value
//CMDSTATUS
//Statusmessagestructure
//STATUSRED|GREEN|YELLOW|TMIN|TMAX|SECONDS|TEMP|THIGH=value
Initializationofvariablesneededfortemperaturecontrol
floatmaxTemp=30.0//switchonledwhentemp>maxTemp
intmaxTempSensor=(int)((maxTemp/100+.5)*204.8)
floattemperature=0.0
maxTempcanlaterbechanged,buttheprogramneedsadefaultvaluetostartwith.
maxTempSensoristheconversionofmaxTemptothe01023rangeprovidedby
ArduinoADCconvertertemperaturecomparisonwillbeperformedbyaninterrupt
routinethatwewantasfastaspossible:itismoreefficienttodirectlycomparethe
integerPinoutputvalueratherthanthefloattemperature.Westillwanttoreportthe
temperatureandtheprogramwillstoreitinthevariablewiththesamename.
Ifyouarenotfamiliarwiththetemperatureconversionformula,youcanhavea
lookhere(http://www.instructables.com/id/ArduinoExpermentationKitHowtoget
Startedwi/step12/TemperatureTMP36PrecisionTemperatureSensorCIR/).
maxSecondscanalsobechangedwithacommandbutagainweneedadefault
intmaxSeconds=10//sendstatusmessageeverymaxSeconds
DeclarationsofPinconstants
constintledPin=13//temperatureled
constinttempPin=A0//T36temperaturesensoranaloginputpin
constintled1Pin=3//Yellow
constintled2Pin=4//Green
constintled3Pin=5//Red
Variablesusedintheinterruptroutineandaccessedfromoutsideofit
volatileinttempVal
volatileintseconds=0
volatilebooleantempHigh=false
volatilebooleanstatusReport=false
Volatileisaspecialkeywordthatpreventsthecompilerfromperformingcertain
optimizations:allvariablesthataremodifiedwithinaninterruptroutineandarealso
accessedoutsideofitmustbedeclaredasvolatiletosignalthattheirvaluecan
changeatanytimeandtomakesurethelatest,correct,valueisreadfrommemory
whenneeded.
Commandstringvariables(theywillbeexplainedlater)
StringinputString=""
Stringcommand=""
Stringvalue=""
booleanstringComplete=false
Thesetup()function
voidsetup(){
//startserialconnection
Serial.begin(9600)
Serial.print("MaxT:")
Serial.print(maxTemp)
Serial.print("Sensor:")
Serial.println(maxTempSensor)
inputString.reserve(50)
command.reserve(50)
value.reserve(50)

pinMode(ledPin,OUTPUT)
digitalWrite(ledPin,LOW)

pinMode(led1Pin,OUTPUT)
pinMode(led2Pin,OUTPUT)
pinMode(led3Pin,OUTPUT)
digitalWrite(led1Pin,LOW)
digitalWrite(led2Pin,LOW)
digitalWrite(led3Pin,LOW)
Thereservemethodofastringallocatesthenumberofbytesprovidedas
argument.
Thefollowingcodeisneededtoinitializethetimerinterruptandsetittofireevery
second,theslowestthatArduinocandofordetailedinformationseehere
(http://www.instructables.com/id/ArduinoTimerInterrupts/step1/Prescalersand
theCompareMatchRegister/).
cli()//disableglobalinterrupts

//initializeTimer1forinterrupt@1000msec
TCCR1A=0//setentireTCCR1Aregisterto0
TCCR1B=0//sameforTCCR1B

//setcomparematchregistertodesiredtimercount:
OCR1A=15624//turnonCTCmode:
TCCR1B|=(1<<WGM12)
//SetCS10andCS12bitsfor1024prescaler:
TCCR1B|=(1<<CS10)
TCCR1B|=(1<<CS12)
//enabletimercompareinterrupt:
TIMSK1|=(1<<OCIE1A)

sei()//enableglobalinterrupts
}
Thetimerinterruptroutine:wecannotchangeitsname,butthecontentisentirely
customizable.
ISR(TIMER1_COMPA_vect)
{
tempVal=analogRead(tempPin)

if(tempVal>maxTempSensor){
digitalWrite(ledPin,HIGH)
tempHigh=true
}
else{
digitalWrite(ledPin,LOW)
tempHigh=false
}
Thetemperaturevalueor,asdiscussedaboveits01023integerrepresentation
isreadfromthesensorandiscomparedwiththethethresholdvalue:whenabove
thebuiltinLEDislitandtempHighissettotrue,otherwisetheLEDisswitchedoff
andtempHighissettofalse.
if(seconds++>=maxSeconds){
statusReport=true
seconds=0
}
}
Rememberthattheinterruptisfiredeverysecond,butwewanttoreportthesystem
statuslessfrequently:thesecondsvariableisincrementedateachiterationuntilit
reachesthevalueswhenthereportisduethiswillbedonelaterinthemainloop
bycheckingstatusReportflag.Asarule,neverneverperformsomethingsoslow
suchwritingdatatoserialfromwithinaninterruptroutine.
Theloop()functioninterpretsandexecutescommandswhenreceived,itthen
reportsstatusifflagisraisedbytimerinterrupt.Inordertoreadastringfromthe
serialbuffer,loop()reliesupontheserialEvent()functionthatwillbedefinedatthe
end:thisroutineisrunbetweeneachtimeloop()runs.Itisnotwidelydocumented
anditprobablydoesn'tapplytoallArduinomodelsinanycase,it'snotdifficultto
nestitscontentwithinthemainloop(seetheendofthistep).
voidloop(){
intintValue=0

if(stringComplete){
Serial.println(inputString)
booleanstringOK=false
if(inputString.startsWith("CMD")){
inputString=inputString.substring(4)
Firstwecheckifthereceivedstringstartswith"CMD":ifsowecandiscardthe
firstfourcharacters,otherwisewe'lllaterraiseanerror.

intpos=inputString.indexOf('=')
if(pos>1){
command=inputString.substring(0,pos)
value=inputString.substring(pos+1,inputString.length()1)//extract
commandupto\nexluded
Therearetwotypesofcommands:thosesettingavalue,wherewe'llfind"="
separatingthevariable+valuepair,andthosewherethecommandisasingle
directive(STATUS).If"="ispresentatpos,thestringissplitintocommand(left
part)andvalue(rightpart),droppingboththe"="inbetweenandtheendofline
characterattheend.

if(command.equals("RED")){//RED=ON|OFF
value.equals("ON")?digitalWrite(led3Pin,HIGH):digitalWrite(led3Pin,
LOW)
stringOK=true
}
elseif(command.equals("GREEN")){//GREEN=ON|OFF
value.equals("ON")?digitalWrite(led2Pin,HIGH):digitalWrite(led2Pin,
LOW)
stringOK=true
}
elseif(command.equals("YELLOW")){//YELLOW=ON|OFF
value.equals("ON")?digitalWrite(led1Pin,HIGH):digitalWrite(led1Pin,
LOW)
stringOK=true
}
WeexamineandexecutetheLEDcommandsnotethatthecodeonlychecksfor
valueON:ifyouwriteGREEN=ASDitwillbeinterpretedasGREEN=OFF.It'snot
perfect,butitkeepsthingsalotsimpler.stringOK=trueisseteverytimea
commandisrecognizedandexecutedsothatwrongcommandswillbeflagged
later.

elseif(command.equals("TMAX")){//TMAX=value
intValue=value.toInt()
if(intValue>0){
maxTemp=(float)intValue
maxTempSensor=(int)((maxTemp/100+.5)*204.8)
stringOK=true
}
}
elseif(command.equals("SECONDS")){//SECONDS=value
intValue=value.toInt()
if(intValue>0){
maxSeconds=intValue
stringOK=true
}
}
Whenvalueshouldbeanumber,weneedtoconvertitandtestitreallyisa
number.InthecaseofMaxTemp,wealsocomputethesensorvalueasexplainedin
thevariabledefinitionsection

}//pos>1
elseif(inputString.startsWith("STATUS")){
Serial.print("STATUSRED=")
Serial.println(digitalRead(led3Pin))
Serial.print("STATUSGREEN=")
Serial.println(digitalRead(led2Pin))
Serial.print("STATUSYELLOW=")
Serial.println(digitalRead(led1Pin))
Serial.print("STATUSTMAX=")
Serial.println(maxTemp)
Serial.print("STATUSSECONDS=")
Serial.println(maxSeconds)
Serial.print("STATUSTEMP=")
Serial.println(temperature)
Serial.print("STATUSTHIGH=")
Serial.println(tempHigh)
stringOK=true
}//inputString.startsWith("STATUS")
IfcommandisSTATUS,theprogramsimplyoutputsallinformationtoserial.

}//inputString.startsWith("CMD")
stringOK?Serial.println("CommandExecuted"):Serial.println("Invalid
Command")
Signalifavalidorinvalidcommandhasbeenreceived.

//clearthestringfornextiteration
inputString=""
stringComplete=false
}//stringComplete
Variablehousekeepingforthenextcommanditeration.

if(statusReport){
temperature=(tempVal*0.0048828125.5)*100
Serial.print("STATUSTEMP=")
Serial.println(temperature)
Serial.print("STATUSTHIGH=")
Serial.println(tempHigh)
statusReport=false
}
}
IftheinterruptroutinehasraisedthestatusReportflag,someinformationisprinted
toserialandtheflagiscleared.
Notethatthecurrenttemperaturevalueiscalculatedatthispoint:therefore,ifyou
issueaSTATUScommandinbetweenthestatusReportinterval,you'llgettheold
temperaturevalue.
Asalreadynoted,serialEvent()occurswheneveranewdatacomesinthe
hardwareserialRX.Thisroutineisrunbetweeneachtimeloop()runs,sousing
delayinsideloopcandelayresponse.Multiplebytesofdatamaybeavailable.
voidserialEvent(){
while(Serial.available()){
//getthenewbyte:
charinChar=(char)Serial.read()
//addittotheinputString:
inputString+=inChar
//iftheincomingcharacterisanewlineoracarriagereturn,setaflag
//sothemainloopcandosomethingaboutit:
if(inChar=='\n'||inChar=='\r'){
stringComplete=true
}
}
}
Eachbyteisreadfromserialandaddedtoinputstringuntil"\n"or"\r"is
encounteredtosignifythestringend:inthiscasethestringCompleteflag,thatis
checkedbyloop(),isset.Usingbothcarriagereturn,\r,andnewline,\n,ensures
thecodeisabletodetectthestringendfromavarietyofinputsincludingother
serialterminalsthantheArduinoIDESerialMonitor.
NoteaboutBluetoothandSerial
Inmanyexamples,includingtheonefromJYMCUseller,
(http://hobbycomponents.com/index.php/arduinojymcubluetoothwirelessserial
portmodule.html)youcanfindtheBluetoothmoduleconnectedondifferent
ArduinodigitalPins(eg.10and11)andaccessedviatheSoftwareSeriallibrary.
Basedupontheresultsofmytests,SoftwareSerialworksperfectlywhenthe
moduleisusedtosendinformationonly,buttheArduinoUnoisnotfastenough
whenreceivingcommands.Ididn'ttrytoreducethespeedoftheSoftwareSerial
connection(inexamplesitisoftensetto2400bps)becausetheMITAppInventor
appdoesn'tseemtosupportBluetoothconnectionspeedsetting.
WithSoftwareSerial,serialEvent()willnotwork:oneneedstorenameit(eg.
mySerialEvent())andcallitexplicitlyatthebeginningofloop().

Step4:AppInventorCodeIntroduction

ConnectArduinoUnotoAndroidviaBluetooth bypmosconi(/member/pmosconi/)
Download(/id/ConnectArduinoUnotoAndroidviaBluetooth/?download=pdf)
(/id/ConnectArduinoUnotoAndroidviaBluetooth/) 6Steps

Collection IMadeit! Favorite Share

(http://cdn.instructables.com/FYE/IOSQ/HTX5KJJA/FYEIOSQHTX5KJJA.LARGE.jpg)
(http://cdn.instructables.com/F4W/W2C1/HTX5KJJH/F4WW2C1HTX5KJJH.LARGE.jpg)

BeforebeingabletousetheAndroidapplication,youneedtopairtheBluetooth
modulewithyoursmartphone.
PowertheArduinoboard,turnonBluetoothontheAndroidphoneandsearchfor
Bluetoothdevicesnearby:theJYMCUmodulewillpresentitselfasHC06,the
pairingpasswordis1234.
ThekeycomponentoftheBluetoothArduinoConnectionAppisthe
BluetoothClientwhiletheArduinoboardwillactasServer:thismeansthatthe
appwillalwaysinitiatetheconnection.WhenyoupowertheArduinoboard,the
BluetoothmoduleredLEDstartsblinkingpushtheapp"ConnecttoDevice"button
andselectyourmodulefromthelist:theredLEDlightbecomessolidandthe
connectionstatuswillchangeto"Connected".
Again,thishasnothingtodowithBluetoothMaster/Slave,butstillcanbe
confusing:youBluetoothmoduleneedstobeSlavebutit(orrathertheArduino
sketch)willbehaveasServerintheClientServer
(http://en.wikipedia.org/wiki/Client%E2%80%93server_model)communicationwith
theAndroidapp.
YoucaninstalltheBluetoothArduinoConnectionAppdirectlyfromAndroidPlay
Store(https://play.google.com/store/apps/details?
id=appinventor.ai_pmosconi.BTArduinoConnection),oryoucanimportthefullapp
codeintoyourMITAppInventorprojectsbydownloadingtheattachedfile.
BluetoothArduinoConnectionAppisdevelopedwithMITAppInventor2the
followingstepwillprovideadetailedexplanation.

BTArduinoConnection.aia (/files/orig/FLF/VAGT/HUFW7NI4/FLFVAGTHUFW7NI4.aia)62KB

Step5:AppInventorCodeDetails
(http://cdn.instructables.com/FYQ/FQCB/HTX5KJMA/FYQFQCBHTX5KJMA.LARGE.jpg)

(http://cdn.instructables.com/FWY/3HQC/HUHT1JZ6/FWY3HQCHUHT1JZ6.LARGE.jpg)
(http://cdn.instructables.com/F3M/3BGP/HUHT1KYD/F3M3BGPHUHT1KYD.LARGE.jpg)

ThekeycomponentsoftheArduinoBluetoothConnectionappare:
aListPickerforBluetoothpaireddevices(ListPicker1)
(http://cdn.instructables.com/F5V/96W2/HUHT1LV9/F5V96W2HUHT1LV9.LARGE.jpg)
(http://cdn.instructables.com/F1I/8NP6/HUHT1KIH/F1I8NP6HUHT1KIH.LARGE.jpg)
3buttons,eachcontrollingthecorrespondingcolorboardLED(RedLedBtn,
GreenLedBtn,YellowLedBtn)
abuttonsendingtheSTATUScommand(GetStatusBtn)
abuttonwithanassociatedtextboxtosetthestatusreportinterval(SecondsBtn
andSecondsTxBx)
ahugemultilineStatuslabeldisplayingtheinforeceivedfromtheArduino
board(Status)
theBluetoothClientobjectmentionedinthepreviousstep(BluetoothClient1)
aclockcomponentthatfiresaninterrupteverysecondwhentheclientis
connected(Clock1)
Whatfollowsisanappcodedescriptionbaseduponthepicturesabove.
Figure1
VariablesforLED'sstatusandintervalaresetandinitializedwhentheappscreen
isopened.
Figure2
TheconnectionListPickerobjectListPicker1workswithtwomethods:
1. alistofavailable(paired)Bluetoothdevicesispreparedandshowedtotheuser
2. whentheuserselectsadevice,theConnectmethodoftheBluetoothClient
objectiscalledinordertostarttheconnection:ifitsucceeds,thisisdisplayed
intheappropriatelabelandtheClockinterruptisactivatedsothatmessages
fromthedevicecanbereceived.
Figure3
HereweshowhowtosendcommandstotheArduinoboard.
WhentheGetStatusBtnispressed,theSendTextmethodoftheBluetoothClient
objectisinvokedandthetextcommandisissued:notethe"\n"addedattheendof
the"CMDSTATUS"stringsothattheserialEvent()functionintheArduinosketchis
abletoknowwhenthemessageisover.
ThecodetotoggleaLEDonoroffisslightlymorecomplex:
weusethecorrespondingvariabletokeeptrackofitscurrentstatus:ifit'son,
wewanttoturnitoffandtheotherwayroundso,first,wetogglethevariableas
itwereboolean
wethenupdatethebuttonlabelwiththenewstate
finally,BluetoothClient1.SendTextiscalledtotransmitthecommand.
Thecodefortheothercommandsisnotshownsinceitisverysimilar.
Figure4
EverytimetheClock1timerfires,thisroutineisexecuted:itistheequivalentof
Arduino'sserialEvent()iftherearebytestobereceivedbyBluetoothClient1,they
arecopiedintheStatuslabel.NotethattheBluetoothClientobjecthasamethod
returningthelenghtofthemessagebeingreceived.

Step6:Conclusion

Connect Arduino Uno to Android via Bluetooth


InthisinstructableIhavedemonstratedausefulwaytoconnectanArduinoboard
andanAndroidsmartphoneviaBluetooth.Thecommunicationistwowaysothat
theboardisnotonlyreportingitsstatustotheapp,butitisalsoreceiving
commandsfromit.
Furthermore,asimpleextensionwouldallowtosendcommandsfromArduinotothe
phone:e.g.:takeapictureorsendatextmessageatthepressofabuttononthe
board.
TheArduinosketchcanbethefoundationforremotecommandprocessingandit
usesaninterrupttoexecutesomeactionschecktemperatureandswitchona
LEDalarmandtosendastatusheartbeat:thistechniquecanbeappliednotonly
overBluetoothcommunicationbutalsowithothermeanssuchasEthernet.
TheMITAppInventorapplicationusesaninterrupttoo:itistheequivalentof
Arduino'srepetitionofloop()+serialEvent()functionsanditissimilarlyusedto
receivemessages.
IhopeIhavealsobeenabletoexplainandclarifysomekeyBluetootharchitecture
aspectsthatcanbeconfusing(andwerewhenIfirststartedtheproject):namely
MasterSlaveandClientServerconcepts.
Wehaveabenicecommentpolicy.
Pleasebepositiveandconstructive.
IMadeit! AddImages MakeComment

140of Next(http://www.instructables.com/id/ConnectArduinoUnotoAndroidviaBluetooth/?
52 &sort=ACTIVE&limit=40&offset=40#DISCUSS)

CsillaS(/member/CsillaS/) 3daysago Reply

1.WhenIgooutofrangetheconnectionislost(thereisnowarningattemptsto
reconnect).
(/member/CsillaS/)
2.Imovebackintorange..mustreconnectthephonereceivethestatusofthe
LED,butthenewstatusnotupdateintheappwiththecurrentstateoftheLED
(attachedprintscreen).

(http://cdn.instructables.com/F5K/VATW/IDK894BV/F5KVATWIDK894BV.LARGE.jpg)
flag

tharindu.irashana(/member/tharindu.irashana/) 12daysago Reply

thisismyprojectandroidarduinobluetooth
(/member/tharindu.irashana/)
Thesoftwarecanbeusedtocontroltheelectricalequipmentinyourphoneto
yourhome.
Itcanbeusedonyourdesignandmanydesignscanbecautious.
ThesoftwarehasbeendesignedinGoods10interfacesrequiredtocontrol.
Theserialsendcommandcanbeusedtocontrolanyamountofequipment.
Youcangetitwiththefilecontainsinstructionsonhowtocreatethedevice.
TheneedforthisbasicArduinocodeavailable.
Wewishtoprovidethenextversionofthesoftwarecancontrolfromanywherein
theworld.
Butasforyourideas,suggestionspleasesendittousintheforumbysoftware
formoreinformation
http://dcmote.blogspot.com/

(http://cdn.instructables.com/FQK/CXHG/ID7UXUG5/FQKCXHGID7UXUG5.LARGE.jpg)

flag

ShashankR3(/member/ShashankR3/) 19daysago Reply

GreatInstructable!OnequestionthoughIfIweretomakesomethingsimilar,but
justwantedtheArduinotosenddatatotheApp,dataasinbits0or1,would
(/member/ShashankR3/)
Serial.println()orSerial.write()beappropriate?
Thanks.

flag

AleA1(/member/AleA1/) 1monthago Reply

thisismycircuit
(/member/AleA1/)
(http://cdn.instructables.com/FYH/QID5/IC0AUGYD/FYHQID5IC0AUGYD.LARGE.jpg)

flag

AleA1(/member/AleA1/) 1monthago Reply

Hi,iwoullikeyourhelpforaprojectthatihavetotelecontrollwithandroidphone
andhc05a220vbulb.Actuallyiamusinga5vreley,aPhotoresistorSensor
(/member/AleA1/)
ModuleLightDetectionLightforArduino,androidphone,arduinouno.Untillnow
thisisthecodeihaveused,isnotcomplete.iamaskingyourhelpforthiscode
becausetherearecaseswhenitypetomyandroidphonea1itdotgiveme
alwaysa49toserialmonitor(arduino)ortotheaboveconditionihavespecified
thatifthevalueigiveisequalto49thebulbmuststayon2secondsandoff
8seconds,butitdoesthereverse,howcanisolvethisproblem
Serial.print(ReadBT)
if(ReadBT==49)
{
Delay=8000
Serial.println("DDDDDDDDDDDDD")
}
else
{
Delay=2000
Serial.println("CCCCCCCCCCCC")
}

digitalWrite(Relay,HIGH)//turnonrelay
delay(10000Delay)//timeOFF
digitalWrite(Relay,LOW)//turnoffrelay
delay(Delay)//timeON
}

Thisisthecodeihavecreateduntilnow

///////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include<SoftwareSerial.h>
intRelay=7
intBTtx=10
intBTrx=11
intReadBT
intDelay

SoftwareSerialbluetooth(BTtx,BTrx)//TX|RX

voidsetup(){

//putyoursetupcodehere,torunonce:

Serial.begin(9600)//opensserialport,setsdatarateto9600bps

bluetooth.begin(9600)
bluetooth.print("$$$")
delay(100)
bluetooth.println("U,9600,N")
bluetooth.begin(9600)
Serial.println("setupcomplete.")
pinMode(Relay,OUTPUT)
}

voidloop(){
//iftheresdatafromthebluetoothmodule
if(bluetooth.available()){
ReadBT=(int)bluetooth.read()
Serial.println("BBBBBBBBBBB")
//echoittotheserialmonitor
//Serial.print("btmodulesaid:")
Serial.print(ReadBT)
}

//iftheresdatafromtheserialmonitor
if(Serial.available()){
ReadBT=(int)Serial.read()
Serial.println("AAAAAAAAA")
//sendittothebluetoothmodule
bluetooth.print(ReadBT)
}

Serial.print(ReadBT)
if(ReadBT==49)
{
Delay=8000
Serial.println("DDDDDDDDDDDDD")
}
else
{
Delay=2000
Serial.println("CCCCCCCCCCCC")
}

digitalWrite(Relay,HIGH)//turnonrelay
delay(10000Delay)//timeOFF
digitalWrite(Relay,LOW)//turnoffrelay
delay(Delay)//timeON

2.Ihaveboughtthislightsensorformyproject:http://www.ebay.com/itm/1PC
PhotoresistorSensorModuleLightDetectionLightforArduino/251673864995?
_trksid=p2045573.c100033.m2042&_trkparms=aid%3D111001%26algo%3DREC.SEED%26ao%3D1%26asc%3D20131017132637%26meid%3D
anywonehelpmewithacodehowtosenslightintensityduring
day/night(consideringeventheconditionthatwhenitisbad/cloudytimeidont
wantmyllamptogetturnedon,iwantthebulbtogetturnedonwhenthesensor
sensthedark(forexample8pm)andtoturnoffthebulbwhenitislight(7pm))

flag

rehmp(/member/rehmp/) 1monthago Reply

ThisiswhatI'msearchingfor.Thankyouforthisveryinformativepost!Canyou
helpmewithmycurrentproject?MyproblemisIneedtocomparetheAndroid
(/member/rehmp/)
phone'sapp(Speedometer)valuetotheArduinoprogrammedspeedlimit.SoI
needtoconnectmyAndroidapptoArduinousingbluetooth/serialconnection.
WhatisthecodeIneedtoputinmyapp?AndwhatisthecodeIneedtoputin
Arduino?Thanks.I'manewbie.

(http://cdn.instructables.com/F4W/B3JM/IBU5AGGN/F4WB3JMIBU5AGGN.LARGE.jpg)

flag

hsnter(/member/hsnter/) 1monthago Reply

Hi!Ilikeyourproject,itsreallyhelpfulforme.Butistillneedhelpaboutsome
details.Iwillusearduinonanoandhc05bluetoothmoduleonmyownproject.But
(/member/hsnter/)
howcanimaketheworkmodeasaslave?IknowthatihavetowriteaATcode.
ButhowwillIwritethisATcodeontheprogramofArduino?Thanksagain..

flag

LordPharaoh(/member/LordPharaoh/)
1monthago Reply

Thisisareallygreattutorial,Iwaslookingforthisforawhilethanks!ButbeforeI
makeit,Ihaveaquickquestion:doyouknowhowmuchmemoryandprocessing
(/member/LordPharaoh/)
thistakesontheArduinosideofthings?Iwasplanningonusingthiswithan
unbufferedeInkdisplay,whichtakesabitoverhalf(accordingtoAdafruit,
anyway)oftheArduino'spower.IjustwanttobesuretheArduinocansupport
bothatthesametime,andifnot,buyanotherATMega.Speakingofwhich,I'm
planningontakingthisoutofArduinointoanATMega328there'snothingin
yourcodewhichlookslikeitwouldrequireanythinganATMegacan'tdoamI
correct?
Thanksagainforthegreattutorial!

flag

pmosconi(/member/pmosconi/)(author) LordPharaoh
1monthago Reply
Hiandthanks!
(/member/pmosconi/)
Inreplytoyourquestions:processingisnegligible
andmemoryismostlyrelatedtothesizeofthe
stringsyouareusinginadditionusingprogram
memorycanfurtherreducethecodefootprint(ifyou
arenotfamiliarwithit,thisisanexcellenttutorial:
https://learn.adafruit.com/memoriesofanarduino/...
Whenmovingthecodetootherplatforms,including
ATMega,Istronglyadvisetogetridofthe
serialEvent()functionandtomovethecodeatthe
topofloop().
Itgoeslikethis:
if(Serial.available()){
readBytes=Serial.readBytesUntil('\n',cmd,
sizeof(cmd))
cmd[readBytes]='\0'
}
ThiswayitwillworkforanySerialport.
Regards

flag

LordPharaoh(/member/LordPharaoh/) pmosconi 1monthago Reply

Also,thanksforthetutorialitreallyhelped.
(/member/LordPharaoh/)
flag

LordPharaoh(/member/LordPharaoh/) pmosconi 1monthago Reply

Awesome!Thankyousomuchforyourpromptreply!
(/member/LordPharaoh/)
flag

RubenO3(/member/RubenO3/) 2monthsago Reply

Whatkindofrangecanyougetwiththis?
(/member/RubenO3/)
flag

pmosconi(/member/pmosconi/)(author) RubenO3 2monthsago Reply

I'vetestedtheBTmoduleupto10mt,withathinwallinbetween.
Thetheoreticalrangeismuchhigher.
(/member/pmosconi/)

flag

SadanandT(/member/SadanandT/) 3monthsago Reply

Thisisanothernicepostonarduinoandandroidinterfacing,withtroubleshooting
techniques
(/member/SadanandT/)

http://knowledgecess.com/arduinoandroidinterfacingexamplecodeand
troubleshooting/
flag

win89(/member/win89/) 3monthsago Reply

howtoconnectandroidtoarduinousebluetoothautomaticallywithoutfistpair
before?
(/member/win89/)

flag

pmosconi(/member/pmosconi/)(author) win89 3monthsago Reply

Youneedto.codeanativejavaandroidappforthis:it'snotpossiblewith
MITAppInventor.
(/member/pmosconi/)

flag

win89(/member/win89/) 3monthsago Reply

awesomeproject
(/member/win89/)
flag

win89(/member/win89/) 3monthsago Reply

flag
(/member/win89/)

dagopeter(/member/dagopeter/) 3monthsago Reply

Hipmosconithiscodeisreallyawfullyinterestingforme.Youhavesogood
commentswrittenintoyoursketchfileforarduino.AtleastIhaditputalltogether
(/member/dagopeter/)
manuallyandunderstoodalotofyourexplanationsofthecode.ButonethingI
foundnowhereontheweb.Whatthehellmeansthe"?"intoyourcode:
elseif(command.equals("YELLOW")){//YELLOW=ON|OFF
value.equals("ON")?digitalWrite(led1Pin,HIGH):digitalWrite(led1Pin,
LOW)
stringOK=true
IfoundreallynoexplanationwhetherintheArduinocommandorsyntaxplease
givemechanceIdonotunderstandit.Bynomeans.Thanksforananswer.
Peter

flag

pmosconi(/member/pmosconi/)(author) dagopeter 3monthsago Reply

HiPeter,'?'isastandardC++operatorcalled"ternaryoperator"
(http://www.cprogramming.com/reference/operators/te...
(/member/pmosconi/)

it'smeaningis<condition>?<executewhentrue>:<executewhen
false>
Forourpurposes,it'sequivalentto
if(<condition>){
<executewhentrue>
}
else{
<executewhenfalse>
}
Ifyouneedtoknowmoreaboutthedifferencebetweenifthenelseand?,
seethelanguagereference.
Hopethishelps.

flag

stercenio(/member/stercenio/)
3monthsago Reply

Thisisawesometutorial.Thanksforsharing.
(/member/stercenio/)
flag

stercenio(/member/stercenio/) 3monthsago Reply

Thisisawesometutorial.Thanksforsharing.
(/member/stercenio/)
flag

sudarshan.venkatraman.1(/member/sudarshan.venkatraman.1/)
6monthsago Reply
Iamnewtothehardwareinterfacingandstuffs..
SomeonepleaseguideonwheretotypetheARDUINO
(/member/sudarshan.venkatraman.1/)
code..andalso..incaseiwannaPLOTagraphusingthe
valuethatigetfromthekitbyusingplotlybutwithoutan
ethernetshield,whatamisupposedtodo???Kinda
urgent

flag

sudarshan.venkatraman.1(/member/sudarshan.venkatraman.1/)
6monthsago Reply
Iamnewtothehardwareinterfacingandstuffs..
SomeonepleaseguideonwheretotypetheARDUINO
(/member/sudarshan.venkatraman.1/)
code..andalso..incaseiwannaPLOTagraphusingthe
valuethatigetfromthekitbyusingplotlybutwithoutan
ethernetshield,whatamisupposedtodo???Kinda
urgent

flag

sudarshan.venkatraman.1(/member/sudarshan.venkatraman.1/)
6monthsago Reply

Iamnewtothehardwareinterfacingandstuffs..Someonepleaseguideon
wheretotypetheARDUINOcode..andalso..incaseiwannaPLOTagraph
(/member/sudarshan.venkatraman.1/)
usingthevaluethatigetfromthekitbyusingplotlybutwithoutanethernetshield,
whatamisupposedtodo???Kindaurgent

flag

pmosconi(/member/pmosconi/)(author) 6monthsago Reply

Manythanksforyourkindness!!
(/member/pmosconi/) flag

sammy011(/member/sammy011/) 6monthsago Reply

HiPmosconi,
(/member/sammy011/)
ThisisexactlywhatIwaslookingfor.Thanksforinstructable.
IamhavingsomechallengesindisplayingTEMPvalueonandroidphone.Inmy
caseitisprintingfullstring.Willyoubeabletoshareyourandroidjavacode?aia
fileaboveappearstobebinary.
Appreciateyourhelp.Thanks

flag

pmosconi(/member/pmosconi/)(author) 6monthsago Reply


sammy011

Hisammy011,IdevelopedtheAndroidapplicationwithMITAppInventor
(/member/pmosconi/)
(http://appinventor.mit.edu/explore/(http://appinventor.mit.edu/explore/))
thusitisnotnative.Fromthelinkyou'llfindhowtomanagetheaiafile,
whichbtwisazipcontainingthewholeAppInventorproject.
Inanycase,whatdoyoumeanbyprintingfullstring?MaybeIcanstillhelp
you.

flag
sammy011(/member/sammy011/) pmosconi 6monthsago Reply

ThanksPmosconiforreply.
(/member/sammy011/)
Iresolvedtheissuewithmysetuptoday.TheissuewasIsupposedtouse
lightweightsdkfornRF8001BLE.Iaddeditandappworkedlikecharm.
Thanksforyourresponseandoffertohelp.:)
+1follow

flag

numancelik34(/member/numancelik34/) 7monthsago Reply

(/member/numancelik34/)
DearPmosconi,
IuseArduinoUnoformy
project,onceItrytopairBluetoothtoPC,it'sworkedandthenItry
toseemyprogramisworking.IuseJYMCUbluetoothmoduleforthis
project.TheoutcomingportisshownasCOM11,butwhenIwanttotry
toseeintools>SerialPortmenuintheArduinoprogram,thereisno
comport11atallthere.IjustcanseeComport9,butIneedtosee
COM11theretocommunicatewiththPC.Couldyouplease
helpinthisproject,IhavetosolvethisproblemassoonasIcan,so
couldpleasegetbacktomeASAP,thatwouldbeverygrateful.ManyThanksand
BestRegards..
flag

pmosconi(/member/pmosconi/)(author) numancelik34
7monthsago Reply
Hinumancelik34,
havealookatthis:
(/member/pmosconi/)
http://ecno92.blogspot.it/2012/10/installingand
testingjymcubtchip.html
ItmighthelpwiththePCconnection.
flag

numancelik34(/member/numancelik34/) pmosconi 7monthsago Reply

Stillsameissue,theoutgoingCOMportdoesn'tappearintools>Serial
Port,thusIcannotcommunicatewiththePCandsendcommandsfrom
(/member/numancelik34/)
thePCtotheArduino.Idon'thaveanyideawhatthereasonis.Doyou
haveanyothersolutionstothisproblem?

flag

pmosconi(/member/pmosconi/)(author) numancelik34
7monthsago Reply
IfthePCbtportisworkingwithotherdevices,I
havenoideaotherwisetheproblemliesinthePC
(/member/pmosconi/)
settings.Sorry,butIdon'tbelieveIcanofferany
additionalhelp
flag

pradipta03(/member/pradipta03/) 7monthsago Reply

DoyouhaveanyideahowcanIdothesamethingusingthewifimodule?have
twowifimoduleinmyhouseandwanttousewifiratherthanthebluetooth.Isit
(/member/pradipta03/)
possible?
Cheers!

flag

pmosconi(/member/pmosconi/)(author) 7monthsago Reply


pradipta03

Bluetoothintheendislikehavingaserialcableconnectingthe2devices
(/member/pmosconi/)
wifiiswaymorecomplicated:you'llusetcpoveritandyou'llneedatleast
awebserviceonthearduino.
flag
zefram38(/member/zefram38/) 9monthsago Reply

reallynicejob.
(/member/zefram
38/) I'veinmindprojectbaseonArduinoUno+SensorDHT11==>Moisture+
temperatureSensor.
WithDHT11Sensor,weneedtouseDHTlibrary.
herebyasamplesquetch:
#include"DHT.h"
#defineDHTPIN8
#defineDHTTYPEDHT11//#defineDHTTYPEDHT22(pouruncapteurDHT22)
DHTdht(DHTPIN,DHTTYPE)
floath=0
floatt=0
voidsetup(){
Serial.begin(9600)
dht.begin()
Serial.print("TestConnexion")
}
voidloop(){
h=dht.readHumidity()
t=dht.readTemperature()
if(isnan(t)||isnan(h))
Serial.println("Lectureimpossible!")
else{
Serial.print("Humidite:")
Serial.print(h)
Serial.print("%\t")
Serial.print("Temperature:")
Serial.print(t)
Serial.println("*C")
}
delay(1000)
}
Iwaswonderinghowitispossible(withfewmodifications)toadaptyourcode
withthissensorinsteadoftheTMP36?
thereisafewdifferencewithyoursquetch:
PindefinitionisDigitalinsteadofAnalogic
Readingvalue(temp/moisture)ismadeinsidetheloop.
Thx4urhelp.

flag

sau.beo.739(/member/sau.beo.739/) 10monthsago Reply

HowcanIconvertthemasterslaverelationship(Androidisslaveandarduinois
master),oranywaytosendmessageorcontrolandroidbyarduinoviabluetooth?
(/member/sau.beo.739/)

flag

pmosconi(/member/pmosconi/)(author) sau.beo.739
10monthsago Reply
Youcan'tchangethemasterslaveBTrelationship
becausethephonechipisofmastertype.
(/member/pmosconi/)
Anyway,you'llprobablylookingatclientserver
communication:theclientstartstheexchange(the
Androidappinthisexample)whiletheserver
(Arduino)keepslisteningforincomingclient
connections.Youcancertainlyswapthislogicby
changingthelogicofbothapplications.
Inanycase,alsoasitisnowyoucanhaveArduino
sendinputtotheAndroidapp:thisishappening
withstatusmessagesthataredisplayedinthebig
textboxinthelowerhalfoftheappscreen.

flag

SabriM(/member/SabriM/) 10monthsago Reply

Isandroidinterfacesourcecodeavailable?Opensource?
(/member/SabriM/)
flag

pmosconi(/member/pmosconi/)(author) SabriM 10monthsago Reply

Hi,
thecodeisavailableasanattachmenttotheInstructable(itiscalled
(/member/pmosconi/)
BTArduinoConnection.aia)anditisopensource.
pmosconi
flag

140of Next(http://www.instructables.com/id/ConnectArduinoUnotoAndroidviaBluetooth/?
52 &sort=ACTIVE&limit=40&offset=40#DISCUSS)

Wehaveabenicecommentpolicy.
IMadeit! AddImages MakeComment
Pleasebepositiveandconstructive.
FEATURED CHANNELS

LifeHacks Beauty Woodworking Minecraft Breakfast LaserCut Organizing Arduino


(/tag/type (/tag/type (/tag/type (/tag/type (/tag/type (/tag/type (/tag/type (/tag/type
id/category id/category id/category id/category id/category id/category id/category id/category
IntelIoT home/channel home/channel workshop/channelplay/channel food/channel workshop/channelhome/channel technology/channel
(/id/intel/) lifehacks/) beauty/) woodworking/) minecraft/) breakfast/) lasercutting/) organizing/) arduino/)
Newsletter
Join2million+toreceiveinstant
inspirationinyourinbox.

enteremail I'min!

Mobile
Downloadourapps!

Android(https://play.google.com/store/apps/details?id=com.adsk.instructables)
iOS(https://itunes.apple.com/app/instructables/id586765571)
Windows(http://apps.microsoft.com/windows/enus/app/7afc8194c771441a959054250d6a8300)
AboutUs FindUs
WhoWeAre(/about/) Facebook(http://www.facebook.com/instructables)
Advertise(/advertise/) Youtube(http://www.youtube.com/user/instructablestv)
Contact(/about/contact.jsp) Twitter(http://www.twitter.com/instructables)
Jobs(/community/PositionsavailableatInstructables/)
Pinterest(http://www.pinterest.com/instructables)
Help(/id/howtowriteagreatinstructable/)
Google+(https://plus.google.com/+instructables)
Tumblr(http://instructables.tumblr.com)
Resources
ForTeachers(/teachers/)
ArtistsinResidence(/air)
GiftProAccount(/account/give?sourcea=footer)
Forums(/community/)
Answers(/tag/typequestion/?sort=RECENT)
Sitemap(/sitemap/)

TermsofService(http://usa.autodesk.com/adsk/servlet/item?siteID=123112&id=21959721) |
PrivacyStatement(http://usa.autodesk.com/adsk/servlet/item?siteID=123112&id=21292079) |
LegalNotices&Trademarks(http://usa.autodesk.com/legalnoticestrademarks/) | MobileSite(http://m.instructables.com)
(http://usa.autodesk.com/adsk/servlet/pc/index?id=20781545&siteID=123112)
2015Autodesk,Inc.

You might also like