Download as pdf or txt
Download as pdf or txt
You are on page 1of 41

JOBSHEET1:

SimpleArduinoSerialCommunication
ThegoalistostartfromaverybasicformofArduinoSerialcommunication,andprogressively
addorimprovecomponents.
StageOne: EchoingdatawiththeArduino
StageTwo: UsingDelimiterstosplitdata.
StageThree:ArduinoMaths,simpleaddition
StageFour: SendingadoubletoanArduino,andthendoublingit.
StageFive: SendingSensordatafromtheArduinototheSerialMonitor
StageSix: AsimpleProcessingSketch
StageSeven:ArduinoandProcessingjoinforcesformorefun
StageEight: AsimpleprojectthatshowsSerialcommunicationfromArduinotoProcessing
StageNine: AsimpleprocessingsketchthatswitchesanLEDontheArduino
StageTen: Aprocessingsketchthatreadsfromatextfile
StageEleven:AprocessingsketchthatreadsdatafromatextfileandsendstotheArduino
Letusbegin.

Stage1:ECHOECHO
PartsRequired:
Computer
USBcable
ArduinoUNO(orequivalent)
ArduinoIDE
The following code will make the Arduino ECHO anything you send to it. Therefore, if you
typea3,theArduinowillsendbacka3.IfyoutypealetterF,theArduinowillsendbacka
letterF.
EnterthefollowingcodeintoyourArduinoIDEanduploadittoyourArduino.
ArduinoSketch
/*SimpleSerialECHOscript:WrittenbyScottC03/07/2012*/
/*UseavariablecalledbyteReadtotemporarilystore
thedatacomingfromthecomputer*/
bytebyteRead;
voidsetup(){
//TurntheSerialProtocolON
Serial.begin(9600);
}
voidloop(){
/*checkifdatahasbeensentfromthecomputer:*/
if(Serial.available()){
/*readthemostrecentbyte*/
byteRead=Serial.read();
/*ECHOthevaluethatwasread,backtotheserialport.*/
Serial.write(byteRead);
}
}

Instructions
1.OncetheArduinosketchhasbeenuploadedtotheArduino.OpentheSerialmonitor,which
lookslikeamagnifyingglassatthetoprightsectionoftheArduinoIDE.Pleasenote,thatyou
needtokeeptheUSBconnectedtotheArduinoduringthisprocess,astheUSBcableisyour
communicationlinkbetweenyourcomputerandtheArduino.

2.TypeanythingintothetopboxoftheSerialMonitorandpress<Enter>onyourkeyboard.
ThiswillsendaseriesofbytestotheArduino.TheArduinowillrespondbysendingbackyour
typedmessageinthelargertextbox.

3. Please note that we are using Serial.write(byteRead);on line 18 to get the Arduino to
ECHOthemessagebacktoyouonyourcomputer.
ThingstoTry
1.Deletelines16to18,andreplacethemwiththefollowingline:
Serial.write(Serial.read());
ThisessentiallyeliminatesthebyteReadvariableinthesketchabove.Butwewillbeusingit
lateron,soonceyouhavetesteditout,putthecodebacktogetherasoriginallydisplayed.
2.Replaceline18withaSerial.printlninsteadofSerial.write
Serial.println(byteRead);
Onceuploaded,type1<enter>2<enter>3<enter>intotheSerialMonitor.
Youshouldsee:
49
50
51
Serial.printandSerial.printlnwillsendbacktheactualASCIIcode,whereasSerial.writewill
3

sendbacktheactualtext.SeeASCII

codesformoreinformation.
3.Trytypinginnumberslike1.5or2.003or15.6intotheSerialMonitorusingSerial.write
andSerial.printorSerial.printlncommandsasdescribedbefore.
You will notice that the decimal point transmits as a number using Serial.print or
Serial.println,andwilltransmitasadecimalpointwhenusingSerial.write

STAGE2:Delimiters
Howdoyouhandle2ormorenumberswhensendingorreceiving?
Let us say that you have number pairs that you want the Arduino to interpret. How do you
separatethenumbers?TheanswerisDelimiters.
YoumaybefamiliarwithCSV(commaseparatedvalue)files,whereeachfieldisseparatedby
acomma(,).Thecommaisausefulwayofseparatingorgroupinginformation.
Letssayyouhavethefollowingstreamofnumbers:
12345678910
HowwillyourArduinoknowifthisisasinglenumber,oraseriesofnumbers?
Eg:
12,34,56,78,91,0
123,456,78,910
1,2,3,4,5,6,7,8,9,10
12345678910
Thecommadelimitershelptoidentifyhowthenumbersshouldbeinterpreted.
IntheechoexampleinStage1above,youwouldhavenoticedthatwhenweused
Serial.print(byteRead);thatthevaluesdisplayedoneafteranotherinasimilarfashionto
12345678910.
YouwouldhavealsonoticedthatSerial.println(byteRead);providedalinebreakbetween
eachvaluesent.Anddependingonthenumberssent,itcouldhavelookedlikethis:
12
34
56
78
91
0
TheSerial.println()functionessentiallyusesalinefeedtoseparatethevaluesbeingsent.This
line break can be used as a delimiter, but we will look at that later on. For now we will
concentrateonusingacomma(,).
WewillnowgettheArduinoto"listen"forthecommatohelpitidentifyanewnumber.
According to the ASCIIcode
site, a comma is equal to byte code 44. So when the Arduino
readsabytecodethatisequalto44,wewillgetittoprintalinefeed.
EnterthefollowingsketchintoyourArduinoIDEanduploadittoyourArduino.
5

ArduinoSketch
/*SimpleSerialECHOscript:WrittenbyScottC04/07/2012*/
/*Stage2:Delimiters*/
/*UseavariablecalledbyteReadtotemporarilystore
thedatacomingfromthecomputer*/
bytebyteRead;
voidsetup(){
//TurntheSerialProtocolON
Serial.begin(9600);
}
voidloop(){
/*checkifdatahasbeensentfromthecomputer:*/
if(Serial.available()){
/*readthemostrecentbyte*/
byteRead=Serial.read();

/*Listenforacommawhichequalsbytecode#44*/
if(byteRead==44){
Serial.println();
}else{
/*ECHOthevaluethatwasread,backtotheserialport.*/
Serial.write(byteRead);
}
}
}

Instructions
1.OncethecodehasbeenuploadedtotheArduino,opentheSerialMonitoronceagainand
typethefollowingsequenceofnumbers:
1<enter>2<enter>3<enter>
YoushouldseetheSerialmonitordisplaythefollowingnumber:123
2.Whilestillintheserialmonitor,typethefollowing:
,<enter>1<enter>,<enter>2<enter>,<enter>3<enter>,

Pleasenotethecommasbetweeneachnumericalentry.Youshouldnowseeapatternlikethis:
1
2
3
3.Whilestillintheserialmonitor,typethefollowing:
12,23,34,45,<enter>
Pleasenotethecommasbetweeneachnumericalentry.Youshouldnowseeapatternlikethis:
12
23
34
45
Youwillnoticethatthecommashavebeenreplacedbylinefeeds,andeachnumbershould
displayonanewline.
4.Whilestillintheserialmonitor,typethefollowing:
1,,2,,3,<enter>
Youshouldseethefollowingpattern:
1
2
3
Sohopefullythatexplainstheconceptofdelimitersandhowtheycanbeusedtoseparatea
streamofnumbers,nomatterhowlongittakestogettotheArduino.WeusedanIFstatement
to listen for the comma, but we could have used any other delimiter provided we knew the
bytecode.

STAGE3:ArduinoMaths:Simpleaddition
Inthisstage,wearegoingtogettheArduinotodosimplemaths.Wewillsendittwointegers
(orwholenumbers),andtheArduinowilldothehardworkandsendustheanswerinnotime
atall.
This might seem like a simple task, but when you send a number like 27 to the Arduino, it
does not receive the number 27. It receives 2 and then 7 in byte form. In other words, the
Arduinowillseethebytecodes50andthen55aspertheASCII

tableonthispage.
One way to convert this byte code back to a 2 and a 7 is to subtract 48 from each byte
received,providingthebyteisintherange48to57inclusive(whichequatestothenumbers
09).
Wearenotdoneyet.Wethenneedtojointhesenumberstomake27.
Step1:Subtract48fromthebytesreceived,onlyifthebytesareintherange48to57.
Example:5048=2
5548=7
Step2:Multiplythepreviousnumberby10,beforeaddingthemostrecentbytereceived.
Example:(2x10)+7=27
If we have a number like 1928, then we would create this number using the following
calculation
1=1
(1x10)+9=10+9=19
(19x10)+2=190+2=192
(192x10)+8=1920+8=1928
Step3:Usea"+"signasadelimitersothattheArduinocanmoveontotheSecondnumber
Step4:CapturethesecondnumberasperStep2.An"="signwilltelltheArduinothatithas
reachedtheendofthesecondnumber,andtoproceedtostep5.
Step5:Addthe2numberstogetherandsendbacktheanswer.
Thefollowingcodewillcarryoutthe5stepsabove.
EnterthefollowingsketchintoyourArduinoIDEanduploadittoyourArduino.

ArduinoSketch
/*SimpleSerialECHOscript:WrittenbyScottC05/07/2012*/
/*Stage3:ArduinoMaths:SimpleAddition*/
/*Globalvariablesneededforprogrammingworkflow
byteRead:holdsthevaluebeingreadfromtheCOMport
num1:holdstheentirefirstnumber
num2:holdstheentiresecondnumber
answer:holdsthesumofnum1andnum2
mySwitch:enablestheswitchbetweennum1andnum2*/

bytebyteRead;
longnum1,num2,answer;
booleanmySwitch=false;
voidsetup(){
/*TurntheSerialProtocolONand
initialisenum1andnum2variables.*/
Serial.begin(9600);
num1=0;
num2=0;
}
voidloop(){
/*checkifdatahasbeensentfromthecomputer:*/
while(Serial.available()){
/*readthemostrecentbyte*/
byteRead=Serial.read();

//listenfornumbersbetween09
if(byteRead>47&&byteRead<58){
//numberfound

/*IfmySwitchistrue,thenpopulatethenum1variable
otherwisepopulatethenum2variable*/
if(!mySwitch){
num1=(num1*10)+(byteRead48);
}else{
num2=(num2*10)+(byteRead48);
}
}

/*Listenforanequalsign(bytecode61)
tocalculatetheanswerandsenditbacktothe
serialmonitorscreen*/
if(byteRead==61){
answer=num1+num2;

Serial.print(num1);
Serial.print("+");
Serial.print(num2);
Serial.print("=");
Serial.println(answer);

/*Resetthevariablesforthenextround*/
num1=0;
num2=0;
mySwitch=false;

/*Listenfortheadditionsign(bytecode43).Thisis
usedasadelimitertohelpdefinenum1fromnum2*/
}elseif(byteRead==43){
mySwitch=true;
}
}
}

Instructions
1.OncethecodehasbeenuploadedtotheArduino,opentheSerialMonitoronceagainand
typethefollowingsequence:
1+2=<enter>
YoushouldgetthefollowingmessagesentbacktoSerialMonitor
1+2=3
ThingstoTry
1.Enterthissequence:
10<enter>
+<enter>
10<enter>
=<enter>
Result:10+10=20
2.Enterthissequence:
10<enter>
20<enter>
10

+5=<enter>
Result:1020+5=1025
3.Enterthissequence:
10+20+30=<enter>
Result:10+2030=2040
Ihavespecificallywrittenthisscripttoaddtwowholenumberstogether.Ifyoustartto
introducemorecomplicatedcalculations,theresultsbecomeunpredictable.
4.Enterthissequence:
1.2+1.0=<enter>
Result:12+10=22
Onceagain,Ihaveonlydesignedthisscripttohandlewholenumbers.Therefore,decimal
pointsareignored.
5.Enterthissequence:
5+10=<enter>
Result:5+10=15
Thisscriptignoresthenegativesign,andtreatsthe5asapositive5.
Ihavedonethisonpurpose.IwantedtoshowyouhowtheArduinoreadsnumbersfromthe
comport,andhoweasyitistoexcludevitalfunctionalityinyourcode.Ihavekeptthisscript
simple,however,ifyouwantedto,youcouldmaketheArduinodealwitheachoftheabove
situationsandmore.Multiplication,divisionandsubtractionishandledinthesameway.
ThisisthelastthingIwantyoutotrybeforewegotothenextstage:
6.Enterthissequence:
2147483646+1=<enter>Result:2147483646+1=2147483647
2147483647+1=<enter>Result:2147483647+1=2147483648
Notethatthemaximumsizeofa"long"numberis2147483647.Ifyouaddonetothisnumber,
theresultisequaltotheminimumsizeofa"long"whichis2147483648.

11

STAGE4:SendingdoublestoArduino:Thedoubledoubler
Now we get to some tricky business. Sending and receiving Doubles (to and from) the
Arduino.
Upuntilnow,Ihavetriedtokeepitsimpleusingwholenumbers,buttherewillcomeatime
whenyouwillwanttosendafractionofanumberthroughtheSerialline.
Totestourprogram,wewillwanttosendaverysmallnumbertotheArduino,multiplythe
numberby2,andreturnitback.
Ourfinaltestistotryanumberlike:0.000001
andthenanumberlike:123.321
IMPORTANTNOTE:WhentheArduinosendsafloatoradoublethroughtheCOMportusing
Serial.print() or Serial.println(), it will automatically send the number to 2 decimal places.
A number like 1.2345 will appear as 1.23, and a number like 1.9996 will appear as 2.00
To demonstrate this, we will get the Arduino to send these floats/doubles to the Serial
Monitor.
EnterthefollowingsketchintoyourArduinoIDEanduploadittoyourArduino.
ArduinoSketch
/*Stage4:SimpleTransmissionofaDouble
WrittenbyScottCon7/7/2012*/
/*DeclarethedoublesthatwillbesenttotheSerialMonitor*/
doublemyDub1,myDub2;
/*ThispartoftheprogramonlyrunsONCE*/
voidsetup(){
/*TurnONSerialCommunication*/
Serial.begin(9600);
/*Assignavalue1.2345and1.9996totheDoublesbeingsent*/
myDub1=1.2345;
myDub2=1.9996;

/*SendthevaluestotheSerialMonitor*/
Serial.print("myDub1(1.2345):");
Serial.println(myDub1);
Serial.print("myDub2(1.9996):");
Serial.println(myDub2);
}

12

voidloop(){
//Loopdoesnothing
}

WhenyouopentheSerialmonitor(afteryouhaveuploadedthesketchabove),youwillnotice
thefollowingoutput:
myDub1(1.2345):1.23
myDub2(1.9996):2.00
Thebluetextrepresentsthestring(orarrayofcharacters)beingsentusinglines19and21.
Theredtextrepresentstheactualdoublebeingsentusinglines20and22.
YouwillnoticethatmyDub2roundsto2.00.Thismayormaynotbewhatyouwant.
Ifyouwishtoincreasethenumberofdecimalplaces,thenyouwillneedtochangelines20
and22tothefollowing:
20Serial.println(myDub1,4);
22Serial.println(myDub2,4);
Thenumber4highlightedinred,indicatesthenumberofdecimalplacesyouwishtosend.
Tryit!Andtrychangingthisnumbertosomethingbiggerorsmaller.
OknowthatweunderstandthislittleSerial.print(double,decimals)trick,wewillnowgetthe
ArduinotoechobackaDouble.
Beforewejumpin,perhapsweshouldtryandmapoutourstrategy.Forthiswewillchoosea
simpledecimaltomakeiteasier.Sointhisexample,wewillchoose0.1
Oncewegetthisworking,wecanthendoourfinaltest(asmentionedabove).
Ifwesend0.1totheArduino,itwillreadthefollowingbytecode
480
46.
491
Wecanusethedecimalpointasadelimiter.
Wewillusethefollowing5stepstoechothedoublebacktotheSerialMonitor:
Step1:Arduinocollectsallnumbersbeforethedecimalpointusingthesametechniqueasin
Stage3.
Step2:WhentheArduinoreceivesbytecode46,itwillgointodecimalmode.
13

Step3:TheArduinowillcollectnumbersafterthedecimalpointusingasimilartechniqueto
step1.
Step4:Usemathstocreatethedouble,andthenmultiplyitby2
Step5:DisplaythedoubledDoublevalueintheSerialmonitor.
EnterthefollowingsketchintoyourArduinoIDEanduploadittoyourArduino.
ArduinoSketch
/*SimpleSerialECHOscript:WrittenbyScottC06/07/2012*/
/*Stage4:Doubledoubler*/
/*Globalvariablesneededforprogrammingworkflow

byteRead:holdsthevaluebeingreadfromtheCOMport
num1:holdsthenumberbeforethedecimalpoint
num2:holdsthenumberafterthedecimalpoint
complNum:holdsthecompletenumber(beforemultiplation)
answer:holdsthefinalvalueaftermultiplication
counter:isusedtoconvertnum2tothenumberafterthedecimal
numOfDec:countsthenumbersafterthedecimalpoint
mySwitch:enablestheswitchbetweennum1andnum2*/

bytebyteRead;
doublenum1,num2;
doublecomplNum,answer,counter;
intnumOfDec;
booleanmySwitch=false;
voidsetup(){
/*TurntheSerialProtocolONand
initialisenum1andnum2variables.*/
Serial.begin(9600);
num1=0;
num2=0;
complNum=0;
counter=1;
numOfDec=0;
}
voidloop(){
/*checkifdatahasbeensentfromthecomputer:*/
while(Serial.available()){
/*readthemostrecentbyte*/
byteRead=Serial.read();

14

//listenfornumbersbetween09
if(byteRead>47&&byteRead<58){
//numberfound
/*IfmySwitchistrue,thenpopulatethenum1variable
otherwisepopulatethenum2variable*/
if(!mySwitch){
num1=(num1*10)+(byteRead48);
}else{
num2=(num2*10)+(byteRead48);

/*Thesecountersareimportant*/
counter=counter*10;
numOfDec++;
}
}

/*Listenforanequalsign(bytecode61)
tocalculatetheanswerandsenditbacktothe
serialmonitorscreen*/
if(byteRead==61){
/*Createthedoublefromnum1andnum2*/
complNum=num1+(num2/(counter));

/*Multiplythedoubleby2*/
answer=complNum*2;

/*SendtheresulttotheSerialMonitor*/
Serial.print(complNum,numOfDec);
Serial.print("x2=");
Serial.println(answer,numOfDec);

/*Resetthevariablesforthenextround*/
num1=0;
num2=0;
complNum=0;
counter=1;
mySwitch=false;
numOfDec=0;

/*Listenforthedecimalpoint(bytecode46).Thisis
usedasadelimitertohelpdefinenum1fromnum2*/
}elseif(byteRead==46){
mySwitch=true;
}
}
}

15

ThingstoTry
1.Typethefollowingintotheserialmonitor:
1.2=<enter>Result:1.2x2=2.4
Makesurethatyoutypetheequalsign(=)beforeyoupressenter,otherwisetheArduinowill
notknowthatyouarefinished,andwillnotsendanythingback.
2.Typethefollowingintotheserialmonitor:
100.001=<enter>Result:100.001x2=200.002
YouwillnoticethattheArduinoisformattingthedecimaltotheSAMEnumberofdecimalsas
thatentered.
Thisiscontrolledbythevariable:numOfDec.
3.Nowforourfinaltest:Typethefollowingintotheserialmonitor:
0.000001=<enter>Result:0.000001x2=0.000002
Firsttest:PASSED
4.TypethefollowingintotheSerialmonitorforourlasttest:
123.321=<enter>Result:123.321x2=246.642
Secondtest:PASSED
BEWARE:Whileeverythinglooksperfect,letmetellyouthatitisn't.Buthopefullythiscode
willhelpyougetontherighttrack.Ifyoudecidetotypeinanumberlike123123.111222,you
willnotgettheansweryouexpected.
Ihavefoundthatthisprogramwillworkiftheamountofnumbersbeforeandafterthe
decimalpointarelessthanabout9.Eg.1234.1234willproducetherightresult.
However,11111.2222willNOT,becausethereare9numbersrepresented.
Ithinkthishassomethingtodowiththememoryallocatedtoadouble,butIamnotsure.
Idon'tknowifpeopleworkwiththesetypesofnumbers,butIamsurethereisaworkaround,
andIamsuresomeoneouttherecanworkitout.Idon'tpersonallyneedthiskindofprecision,
butthoughttomentionitjustincaseyoudo.

16

STAGE5:SendingsensordatatotheSerialMonitor
WeknowtheArduinoisverygoodatcopyCatgames,howaboutgettingtheArduinotosend
ussomedatafromoneofoursensors.WewillusetheSerialMonitortoviewthesensordata.
DisconnecttheUSBcable,andhookuponeofyourfavouriteanalogsensorstoyourArduino.
Forsimplicity,IamgoingtohookupapotentiometeraspertheFritzingsketchbelow.
PartsRequired

ArduinoUNO(orequivalent)
ComputerwithUSBcable
Breadboard
Potentiometer
3Wires

ArduinoFritzingSketch

Onceyouhaveattachedyoursensortotheboard,plugyourUSBcableintotheArduino,and
uploadthefollowingsketch.
ArduinoSketch
/*Stage5:SendSensorValuetoSerialMonitor
WrittenbyScottCon7/7/2012*/
intsensorVal=0;
voidsetup(){
//SetupSerialcommunicationwithcomputer
Serial.begin(9600);

17

}
voidloop(){
//Readthevaluefromthesensor:
sensorVal=analogRead(A0);

//SendthevaluetotheSerialMonitor
Serial.print("SensorValue=");
Serial.println(sensorVal);
//Intervalbetweenreadings=1second
delay(1000);
}

Instructions
1.OpentheSerialmonitorandwatchthereadingschangedependingontheinputconditions.
Inmycase,byturningthepotentiometerfromlefttoright,Igetanoutputsimilartothe
picturebelow.

AspertheArduinoreferencesite,AnalogReadreturnsanintegerbetween0and1023.Youcan
seethisistruebasedonthepictureabove.Butwhatifwedonotwantavaluebetween0and
1023.Letussaywewantavaluebetween0and100?
Youwouldhavetousethemap
function.Wewilldoitbychangingline13tothis:

18

13sensorVal=map(analogRead(A0),0,1023,0,100);
Themapfunctionisquiteacoolfunction,andgoodfuntoplayaroundwith.Soherearesome
thingstotry.
ThingstoTry
1.Changeline13tothefollowing,uploadtotheArduino
andthenopentheSerialMonitortoseetheeffect.
Trial1:
13sensorVal=map(analogRead(A0),0,1023,100,0);
Trial2:
13sensorVal=map(analogRead(A0),0,1023,0,1000);
Trial3:
13sensorVal=map(analogRead(A0),200,800,0,100);
InTrial1:Weseethatthevalueshavebeeninverted.Insteadofrangingfrom0upto100,they
nowgofrom100downto0.
InTrial2:Theanalogreadingsarenowmappedtoarangeof0upto1000.
InTrial3:Theanalogreadingsthatrangefrom200to800aremappedtoarangeof0to100.
Thereforeiftheanalogreadingsdropbelow200,wewillendupwithanegativevaluefor
sensorVal.
Iftheanalogreadingsgoabove800,wewillendupwithavaluegreaterthan100.Forthis
particularexample,myreadingsactuallyrangefrom33to137.
ThereforeanAnalogreadingof0=33
Analogreadingof200=0
Analogreadingof800=100
Analogreadingof1023=137
Whatifwedon'twanttheoutputtogobeyondourintendedlimitsof0to100?
Thenyouwouldhavetousetheconstrain

function.Thisessentiallytrimsthereadingrangeof
thesensor,andsetsaminimumandmaximumvalue.
Replaceline13withthefollowingcode:
13sensorVal=constrain(map(analogRead(A0),200,800,0,100),0,100);
ThereforeanAnalogreadingof0=0
Analogreadingof100=0
Analogreadingof200=0
Analogreadingof800=100
19

Analogreadingof955=100
Analogreadingof1023=100
Analogvaluesbetween200and800willproducearesultbetween0and100.
InStages

1to5,weexperimentedwiththeSerialMonitorontheArduinoIDEtotransmit
datatotheArduinoandreceivedatafromtheArduino.WeperformedsimpleSerial
communicationofdatainbothdirections.
We then moved from transmitting a String of characters to the more difficult task of
transmittingadoubleorafloat.
Finally,weusedtheSerialmonitortoreceivesensordatafromourArduino,andplayedwitha
coupleofArduinofunctions.
WewillnowlookatreplacingtheSerialMonitorwithamuchmoreexcitingprogramsuchas
"Processing"whichisafreeOpenSourceprogramthatinterfacesveryeasilywiththeArduino.
WewilluseafewprocessingscriptstobringourArduinoSensorprojectstolife!

20

Stage6:AsimpleProcessingSketch:BLINK
ArduinoIDEvsProcessingIDE

WhiletheprocessingIDElooksverysimilartotheArduinoIDE,itisimportantthatyourealise
thattheProcessingsketchwillrunonyourcomputer,andNOTontheArduino.Infact,youdo
notevenneedanArduinotorunaProcessingsketch.Andthatisexactlywhatwearegoingto
do:RunaProcessingsketchwithoutanArduino.
PartsRequired
Acomputer
ProcessingIDE
Once you have downloaded and installed the Processing IDE onto your computer, open the
programandcopythefollowingsketchintoit,andthenpresstheplaybutton.Thisisdifferent
fromtheArduinoIDE,inthatwedonothavetouploadittoanything,asitwillberunning
fromthecomputer.

ProcessingSketch
/*Stage6:SimpleProcessingBlinkSketch
CreatedbyScottConthe8/7/2012
*/

/*Setupthecolorvariablesandswitchingmechanism*/
colorRed=color(255,0,0);
colorWhite=color(255,255,255);
BooleanmySwitch=true;

21


/*Thesetupfunctiononlyrunsonce*/
voidsetup(){
/*Setthesizeofthewindowusingsize(width,height)*/
size(400,400);
}

/*Thedrawfunctionwillrefreshscreenonlyafterithas
processedallfunctionswithinit.WhichiswhyIneeded
aswitchtoswapbetweentheredandthewhitebackground
Thedraw()functionwillruninanendlessloop.*/

voiddraw(){
blink(mySwitch);//Calltoblinkfunction
delay(2000);//Theblinkingspeed(2secs)
}

/*Theblinkfunctionswitchesthebackgroundfromredtowhite
orfromwhitetored.*/

voidblink(Booleanswtch){
/*Ifswtchistrue,makethebackgroundred
otherwisemakeitwhite*/
if(swtch){
background(Red);//red
}else{
background(White);//white
}
/*TogglemySwitchbetweentrueandfalse*/
mySwitch=!mySwitch;
}

ThingstoTry
1. ChangetheWhitebackgroundtoablackbackground
Insertonline9:colorBlack=color(0,0,0);
Changeline38:background(Black);
2. Increasetheblinkrateto1second
Changeline25:delay(1000);
WARNING:Donotincreasethespeedtoomuch,itmaycauseanepilepticfit.
Nowthatwasn'ttoohardIhope.
AndifyouwantaverygoodsitetolearnProcessinghavealookatthese
22

Stage7:ArduinoandProcessingUnite
SohowdowegetourArduinotointerfacewithourcomputer?Well,iftheSerialMonitoron
theArduinoIDEisnotgoodenough,thenyoucoulduseanyprogramthatiscapableofSerial
communication. Fortunately, Processing is one of those programs, but you could use C++,
Java, Python, Microsoft Excel (using VBA), VB.Net, Gobetwino or some other programming
language.
Two programs will be created: One will be uploaded to the Arduino using the Arduino IDE,
andtheotherwillrunonthecomputer.InthisexamplewewilluseProcessingastheprogram
thatwillrunonthecomputer.
Enter the following sketch into the Arduino IDE and upload it to the Arduino. It serves to
generate a random number between 0 and 400 every 200msec and will send it to the
computerviatheUSBcable,usingSerialcommunication.
ArduinoSketch
/*Stage7:SimpleArduinoSerialRandomNumberGenerator
WrittenbyScottCon09/07/2012*/
voidsetup(){
Serial.begin(9600);//BeginSerialCommunication
}
voidloop(){
Serial.println(random(1,1000));//SendRandom#tocomputer
delay(200);//Delay200msbetweenvalues.
}

Instructions
Once the program has been uploaded to the Arduino, we will want to make sure that it is
performingtoexpectationsbeforemovingontotheProcessingscript.
Open the Arduino Serial Monitor and make sure that you see a bunch of random numbers
scrollingdownthepage.Ifnot,thengobackoveryourcodeandtryagain.Onceyouseethe
randomnumbers,thenitissafetomoveontothenextstep.
Processing
ThefollowingProcessingscriptwilldisplaytheRandomnumbersbeingsentfromtheArduino
in the Processing IDE debug window. This particular script is very much like a simplified
Arduino Serial Monitor, and it will show you that the Processing Script is successfully
communicatingwiththeArduino.

23

ProcessingSketch
/*SomeoftheSerialcodewasadaptedfromTomIgoe'sexample
onthissite:http://processing.org/reference/libraries/serial/Serial.html
andhttp://processing.org/reference/libraries/serial/serialEvent_.html

TherestofthisProcessingcodewaswrittenbyScottCon11/07/2012
*/
importprocessing.serial.*;/*NeededforSerialCommunication*/
/*Globalvariables*/
SerialcomPort;
String[]comPortList;
StringcomPortString;
/**/
voidsetup(){
size(100,100);/*Setthesizeofthewindow*/
background(0);/*Setthebackgroundtoblack*/

/*Gettheavailablecomports.Ifthereisatleastone
comportavailable,thenstartcommunicatingonit.
Iftherearemorethanonecomportsavailable,wewill
onlyopenthefirstone(i.e.comPortList[0])
ThebufferUntil('\n');statementwillgenerateaserialEvent
whenitreadsacarriagereturn*/

comPortList=Serial.list();
if(comPortList.length>0){
comPort=newSerial(this,comPortList[0],9600);
comPort.bufferUntil('\n');
}
}
/**/
voiddraw(){
/*TheserialEventfunctionwillupdatethedisplay*/
}
/**/
voidserialEvent(SerialcPort){
comPortString=cPort.readStringUntil('\n');
if(comPortString!=null){
comPortString=trim(comPortString);

/*PrinttotheDebugscreeninProcessingIDE*/
println(comPortString);

24

}
}

WhenyouruntheProcessingscript,alittleblackwindowwillappear.ThisistheProcessing
Graphicswindow,whichisnormallywherealltheactiontakesplace.Howeverinthesketch
above,thiswindowdoesnothing.InsteadwemakeuseoftheblackDebugwindowwhichis
partoftheProcessingIDE(belowthecodewindow).Ifeverythingwenttoplan,youshould
seerandomnumbersscrollingdowninasimilarfashiontotheArduinoSerialmonitor.Hereis
anexampleofwhatitshouldlooklike.

ThingstoTry
IfyouarehavingproblemswithCOMportselection.ThenhavealookattheCOMport
beingusedontheArduinoIDEtouploadsketchestotheArduino.Processinggenerally
usesthesameCOMport.SomakesuretoclosetheArduinoSerialMonitorbefore
runningtheProcessingsketches.

25

The image above shows that I am currently using COM PORT 6 on my computer to upload
ArduinoSketches.IntheProcessingsketchonline3235,Ihadthiscode:
if(comPortList.length>0){
comPort=newSerial(this,comPortList[0],9600);
comPort.bufferUntil('\n');
}
Wecanchangeline33togetProcessingtouseCOMport6exclusively.Wedothisbyreplacing
comPortList[0]with"COM6",asseenbelow:
if(comPortList.length>0){
comPort=newSerial(this,"COM6",9600);
comPort.bufferUntil('\n');
}

26

Stage8:ArduinoandProcessingRandomFontProject
ArduinoandProcessingarespeakingtoeachotherbythisstage,andwewillkeepouroriginal
ArduinoSketchtoproducerandomnumbersforus.Sure,wedon'tactuallyneedtheArduino
to do this for us, because Processing is more than capable of doing this itself, but we are
buildinguptowardsaninteractivesketch,soletsjustgothroughthemotions.
Justincaseyourmousescrollwheeldoesn'tmoveupwards,hereistheArduinoSketchagain:

ArduinoSketch
/*Stage8:SimpleArduinoSerialRandomNumberGenerator
WrittenbyScottCon09/07/2012
*/
voidsetup(){
Serial.begin(9600);//BeginSerialCommunication
}
voidloop(){
Serial.println(random(1,1000));//SendRandom#tocomputer
delay(100);//Delay100msbetweenvalues.
}

UploadtheArduinosketchtotheArduino,andthenputthefollowingcodeintotheProcessing
IDE:
ProcessingSketch
/*STAGE8:RandomFontSelectorwithhelpfromArduino
ScottC:http://arduinobasics.blogspot.com/
SomeoftheSerialcodewasadaptedfromTomIgoe'sexample
onthissite:http://processing.org/reference/libraries/serial/Serial.html
andhttp://processing.org/reference/libraries/serial/serialEvent_.html

TherestofthiscodewaswrittenbyScottCon11/07/2012
*/
importprocessing.serial.*;/*YouneedthisforSerialcommunication*/
/*GlobalVariables*/
SerialcomPort;
String[]comPortList;

27

StringcomPortString;
PFontfont;
String[]myFontList;
intfontNumber;
StringfontString;
/**/
voidsetup(){

size(500,500);/*setthesizeofthescreen,500x500*/
background(0);/*changethebackgroundofthescreentoblack*/

comPortList=Serial.list();/*GetAvailableCOMports*/
myFontList=PFont.list();/*GetAvailableFonts*/
if(comPortList.length>0){/*CheckifthereisatleastoneavailableCOMport*/
comPort=newSerial(this,comPortList[0],9600);/*OpenthefirstCOMportinthelist*/

comPort.bufferUntil('\n');/*Listenforthecarriagereturn*/
}/*whichwillgenerateaserialEvent*/
}
/**/
voiddraw(){
//TheserialEventwillcontrolthedisplay
}
/**/
voidserialEvent(SerialcPort){
comPortString=cPort.readStringUntil('\n');
if(comPortString!=null){
comPortString=trim(comPortString);

/*MaptheArduinovaluetothenumberoffonts*/
fontNumber=int(map(Integer.parseInt(comPortString),1,1000,1,myFontList.length));

/*SelectthefontbasedontheArduinoValue*/
fontString=myFontList[fontNumber];

/*Setthefont*/
font=createFont(fontString,48);
textFont(font);

//background(0);//Undothecommentforadifferenteffect

28

/*ChoosearandomEarthycolourforthefont*/
fill(random(200),random(100),0);
/*Displaythefontonthescreeninarandomposition*/
text(fontString,random(width)100,random(height)+10);
}
}

Theoutputofthissketchshouldlooksomethinglikethis:

29

Stage9UsingyourcomputertoswitchanLED
InthisstagewecreateasimpleArduinosketchwhichwillreceiveasimplecommandfromthe
ProcessingSketchtoswitchanLED.TheProcessingsketchwillallowyoutoturnanLED
on/offbyclickingontheProcessingApplicationwindow.Itwilldetectthepressofthemouse,
andwillsendacommandtotheArduinoviatheUSBSerialCOMport.
PartsRequired:
ArduinoUNOorcompatibleboard
USBcable
ArduinoandProcessingIDE(oncomputer)
ArduinoSketch
/*====================================================
Simplenumberreader:WrittenbyScottC07Apr2013
ArduinoVersion:1.04
=====================================================*
/
//TheonboardLEDisonpin#13
intonboardLED=13;
voidsetup(){
//BeginSerialcommunication
Serial.begin(9600);

//SettheonboardLEDtoOUTPUT
pinMode(onboardLED,OUTPUT);
}
voidloop(){
/*Readserialport,ifthenumberis0,thenturnoffLED
ifthenumberis1orgreater,turntheLEDon.*/
while(Serial.available()>0){
intnum=Serial.read()'0';
if(num<1){
digitalWrite(onboardLED,LOW);//TurnOffLED
}else{
digitalWrite(onboardLED,HIGH);//TurnOnLED
}
}
}

30

ProcessingSketch
/*===================================================
ToggleSwitch:SendNumbertoArduino
WrittenbyScottCon07Apr2013
ProcessingVersion:2.0b8
===================================================*/
importprocessing.serial.*;
SerialcomPort;
booleanledState=false;//LEDisoff
voidsetup(){
//OpenCOMPortforCommunication
comPort=newSerial(this,Serial.list()[0],9600);
background(255,0,0);//StartwithaRedbackground
}
voiddraw(){
}
voidmousePressed(){
//ToggleledONandOFF
ledState=!ledState;

//IfledStateisTruethensendavalue=1(ON)toArduino
if(ledState){
background(0,255,0);//Changethebackgroundtogreen

/*Whenthebackgroundisgreen,transmit
avalue=1totheArduinototurnONLED*/
comPort.write('1');
}else{
background(255,0,0);//Changebackgroundtored
comPort.write('0');//Send"0"toturnOFFLED.
}
}

31

Stage10:ReadingfromaTextFile
WearenowgoingtogivetheArduinoarest(foramoment)andconcentrateonaProcessing
Sketchthatwillreadfromatextfile.Oncewelearnthisskill,wecanthenbuildthis
ProcessingfunctionalityintoourArduinoProjects.ReadingfromatextfileinProcessingis
actuallyquiteeasyifyouusetheloadStrings()method.However,itisbestifyoumakethings
easyforyourselfbyusingdelimiters.Themostcommondelimitterisa"comma".Thecomma
allowsthecomputertogroupinformationaccordingtoyourneeds.
11,22,33,44,55,66
1,1,2,2,3,3,4,4,5,5,6,6
112,223,334,455,566
Theexamplesabovecontainthesamenumbersbutaredelimittedindifferentways.
Wearegoingtoimportafewdifferentnumbers/lettersandstoretheminanarray.Wewill
theniteratethroughthearraytodisplaythevalueswithin.
Soletusnowcreatethetextfile.Copyandpastethefollowingtextintonotepadandsavethe
file,butrememberwhereyousaveit,becausewewillneedtoknowlocationandthenameof
thefileinordertoreadfromin.
CopyandPasteintoNotepad:
00,200,A,B,C,10.2,0.1,wx,yz,arduinobasics
Savethefile
Iamgoingtocallmyfiledata.txt,andwillbesavingittomyDdrive,sothefilewillbe
locatedhere:
D:/data.txt
Wewillnowcreatetheprocessingsketchtoreadthetextfileanddisplaythedataonthe
screen.
Wewillusethecommadelimiterstoseparatethedatasothatitdisplaysinthefollowingway:

32

ProcessingSketch
/*=================================================
ReadTextFileandDisplayonScreen:
WrittenbyScottCon15thApril2013using
Processingversion2.0b8

References:
DisplayingText:http://processing.org/reference/text_.html
ReadingTextFile:http://processing.org/reference/loadStrings_.html
================================================*/
voidsetup(){
size(180,250);
background(255);

/*Readthetextfile*/
String[]lines=loadStrings("D:/data.txt");
intnumOfLines=lines.length;
for(inti=0;i<numOfLines;i++){
/*Splitthedatabasedona","delimiter.*/
String[]data=splitTokens(lines[i],",");
intdataCount=data.length;

for(intj=0;j<dataCount;j++){
/*Setthesizeandcolourofthetext*/
textSize(16);
fill(100,100,255,50+(j*20));

/*Displaythetextonthescreen*/
text(data[j],10,16+(16*j));

33

}
}
}
voiddraw(){
}

Thecodeabovehastheabilitytodisplaydatafrommultiplelineswithinthetextfile,however
forsimplicity,Ihavechosentouseasingleline.IfIwantedtodisplaymorethanoneline,I
wouldhavetochangethe"forloops".

34

Stage11:ReadTextFileandsendtoArduino
Instage10weusedtheProcessingprogramminglanguagetoimportalineofdatafromatext
file,breakupthelineintopieces(basedoncommadelimiters)andthendisplayedthedataon
the Computer Screen. We will now use this knowledge and take it one step further. We will
createatextfile,importthedatausingprocessing,butthistimewewillsendthedatatothe
Arduino. Meanwhile the Arduino will be waiting patiently for this data, and once it receives
thedata,itwillreactaccordingtoourneeds.Wearegoingtokeepthissimple.Thegoalisto
sendtwodifferentlettersfromtheComputertotheArduino.OneletterwillturnanLEDon,
andtheotherletterwillturntheLEDoff.WewillalsosendanintegertotelltheArduinohow
longtokeeptheLEDonoroff.
GOAL:TurnanLEDonandoffbyreadingatextfile.

Ourfirststepinthisprocessistocreateatextfilethatwillstoreourimportantdata.Wewill
storetwovariablesinthisfile.ThefirstvariablewillbeusedtotelltheArduinowhetherwe
wanttoturntheLEDonorwhetherwewanttoturntheLEDoff.Wewillusetheletter"O"to
turntheLEDon,andusetheletter"X"toturntheLEDoff.
Thesecondvariablewillbeatimebasedvariable.ItwillbeusedtotelltheArduino"howlong"
tokeeptheLEDonoroff.Wewillstorethisvariableasanintegerandwillrepresenttimein
"milliseconds".
1000milliseconds=1second
Itmakessensetokeepthesetwovariablesasapair,howeverwewillseparatethemusinga
35

comma delimitter. We will separate each command by putting the variables on a new line.
Copyandpastethefollowingdataintonotepad(orequivalenttexteditor),andsavethefileto
yourharddrive.Ihavesavedthisfileas:
D:/LEDdata.txt
TextFileData:Hereisthedatatoputintoyourtextfile(notepad):
X,50
O,45
X,40
O,35
X,30
O,25
X,20
O,15
X,10
O,5
X,10
O,15
X,20
O,25
X,30
O,35
X,40
O,45
X,50
O,55
X,60
O,65
X,70
O,75
X,80
O,85
X,90
O,95
X,100
O,200
X,200
36

O,200
X,500
O,500
X,500
O,500
X,20
O,20
X,20
O,20
X,20
O,20
X,20
O,20
X,20
O,20
X,200
O,20
X,20
O,20
X,20
O,20
X,20
O,20
X,20
O,20
X,20
O,20
X,200
O,20
X,20
O,20
X,20
O,20
X,20
O,20
X,20
37

O,20
X,200
O,20
X,20
O,20
X,20
O,20
X,20
O,20
X,20
O,20
X,20
O,20
X,20
O,20
X,20
WewillnowsetuptheArduinotoacceptdatafromtheComputerandreacttotheLetters
"O"toturntheLEDon
"X"toturntheLEDoff
"E"willbeusedtotestforasuccessfulSerialconnection.
WewillalsogettheArduinotointerpretthesecondvariablewhichwillbeusedtosetthe
amountoftimetokeeptheLEDonoroff.
ArduinoSketch
/*ReadTextFileData:WrittenbyScottCon24April2013
ArduinoIDEversion:1.0.4
*/
/*GlobalVariables*/
bytebyteRead;//Usedtoreceivedatafromcomputer.
inttimeDelay;//timethattheLEDisOnorOff
intmaxtimeDelay=10000;//Maximumtimedelay=10seconds
intledPin=13;//LEDconnectedtopin13onArduinoUNO.
voidsetup(){
//Setpin13(ledPin)asanoutput
pinMode(ledPin,OUTPUT);
//TurntheSerialProtocolON
Serial.begin(9600);

38

}
voidloop(){
/*checkifdatahasbeensentfromthecomputer:*/
if(Serial.available()){
/*readthemostrecentbyte*/
byteRead=Serial.read();

switch(byteRead){
case69://Thisisanenquiry,sendanacknowledgement
Serial.println("A");
break;
case79://Thisisan"O"toturntheLEDon
digitalWrite(ledPin,HIGH);
break;
case88://Thisisan"X"toturntheLEDoff
digitalWrite(ledPin,LOW);
break;
case46://Endofline
//Makesuretimedelaydoesnotexceedmaximum.
if(timeDelay>maxtimeDelay){
timeDelay=maxtimeDelay;
}
//SetthetimeforLEDtobeONorOFF
delay(timeDelay);
Serial.println("S");
timeDelay=0;//ResettimeDelay;
break;
default:
//listenfornumbersbetween09
if(byteRead>47&&byteRead<58){
//numberfound,usethistoconstructthetimedelay.
timeDelay=(timeDelay*10)+(byteRead48);
}
}
}
}

OurnextstepistoimportthedatainthetextfileintoProcessingandthensendthedatatothe
Arduino.YoumaywanttoreviewStage10ofthistutorialforanotherexampleofimporting
textfiledataintoProcessing.Youmayalsowanttoreviewstage7whichshowshowtoreceive
datafromanArduino.
WewillimportallofthedatafromthefilewhenwepushabuttonontheProcessingWindow,
andsendthisdatatotheArduinoviatheUSBcablethatisconnectedtothecomputer.Weare
goingtousethesameCOMportthattheComputerusestouploadArduinoSketches,therefore
39

itisimportantthatyouclosetheArduinoSerialMonitorbeforeyouruntheprocessingsketch,
otherwiseyouwillgetanerrorwhichstatesthattheCOMportisnotavailable.
ProcessingSketch

/*TextFileDatasender(Stage11)
WrittenbyScottCon24thApril2013
usingProcessingVersion2.0b8
*/
importprocessing.serial.*;
SerialcomPort;//ThecomportusedbetweenthecomputerandArduino
intcounter=0;//Helpstokeeptrackofvaluessent.
intnumItems=0;//Keeptrackofthenumberofvaluesintextfile
StringcomPortString;//StringreceivedFromArduino
StringtextFileLines[];//Arrayoftextfilelines
StringlineItems[];//Arrayoflineitems
voidsetup(){
comPort=newSerial(this,Serial.list()[0],9600);//SetuptheCOMport
comPort.bufferUntil('\n');//GenerateaSerialEventwhenanewlineisreceived
background(255,0,0);//StartwithaRedbackground
}
/*Drawmethodisnotusedinthissketch*/
voiddraw(){
}
//Whenthemouseispressed,writean"E"toCOMport.
//TheArduinoshouldsendbackan"A"inreturn.Thiswill
//generateaserialEventseebelow.
voidmousePressed(){
comPort.write("E");
}
voidserialEvent(SerialcPort){
comPortString=cPort.readStringUntil('\n');
if(comPortString!=null){
comPortString=trim(comPortString);

/*IftheStringreceived=A,thenimportthetextfile
changethebackgroundtoGreen,andstartbysendingthe
firstlineofthetextfiletotheArduino*/

if(comPortString.equals("A")){
textFileLines=loadStrings("D:/LEDdata.txt");
background(0,255,0);
sendLineNum(counter);

40

/*IfthetheStringreceived=S,thenincrementthecounter
whichwillallowustosendthenextlineinthetextfile.
Ifwehavereachedtheendofthefile,thenresetthecounter
andchangethebackgroundcolourbacktored.*/
if(comPortString.equals("S")){
counter++;
if(counter>(textFileLines.length1)){
background(255,0,0);
counter=0;
}else{
sendLineNum(counter);
}
}
}
}
/*ThesendLineNummethodisusedtosendaspecificline
fromtheimportedtextfiletotheArduino.Thefirst
lineitemtellstheArduinotoeitherswitchtheLEDonoroff.
Thesecondlineitem,tellstheArduinohowlongtokeepthe
LEDonoroff.ThefullstopissenttotheArduinotoindicate
theendoftheline.*/

voidsendLineNum(intlineNumber){
lineItems=splitTokens(textFileLines[lineNumber],",");
comPort.write(lineItems[0]);
comPort.write(lineItems[1]);
comPort.write(".");
}

41

You might also like