BME 301 - New Jersey Institute of Technology
Transcript of BME 301 - New Jersey Institute of Technology
BME301
7-Arduino
1
ArduinoBasics
2
Overview
• Learnhowtouseamicroprocessorsystem/platformdevelopmentboard
• ArduinoUNO• Hardware• Software• Projects
3
Computers• Whatisacomputer
o FastNitwitq Performinstructionsveryquicklyq Needstobetoldwhattodo.
• Computertypeso Mainframeso Minicomputerso PersonalComputerso Microprocessors
• Allhavesimilarhardwareandneedsoftwareorprogramstooperatethem
4
ComputerHardware• MainComponentsCircuits
o CentralProcessingUnit(s)–CPUq Thisiswheretheinstructionsareperformed
o Memory–RandomAccessMemoryandReadOnlyMemoryq Thisiswherethedataandprogramthatisrunningisstored
o Timer/Clockq Thisisthehardwarethatcoordinatesthecomputeroperations
o Dataandcontrolbusesq Thisisthedigitalhighwayswheredataandcontrolmessagestransferwithinthe
computero InputandOutputinterfaces–I/Oports
q Thisisthedigitalhighwaysandconnectionstoenterdataanddisplayresults• PeripheralEquipment
o Keyboardso Monitorso DiskDrives
5
GeneralPurposeComputersVsSpecialPurposeComputersVsMicroprocessors
• Generalpurposecomputersaredesignedtohandleavarietyoftasks.
• Specialpurposecomputerswhichcanbeprogrammedtoperformadesiredtask.
• Ingeneral,amicroprocessorfallsintotheSpecialPurposeComputerclass.
• VariousMicroprocessorso Intel8088o ZilogZ80o Motorola6800o Etc.
6
MicroprocessorSystemsorPlatforms
• Microprocessorscontaincomponentstoafforddevelopmentofcomputerbasedsystems.
• Varioustypeso Arduinoo RaspberryPio Etc.
7
Arduino• Arduinoisanopen-sourcehardwareandsoftwarecompany1
• Buildssingleboardmicrocontrollersandmicrocontrollerkits1
• Arduinoboarddesignsuseavarietyofmicroprocessorchipsandcontrollers.1o Unoo MegasimilartotheUnobutbiggerwithmoreI/Oporto Lilypadusedforwearableprojectso NanosmallerthantheUnoo Etc.1wikipedia.org/wiki/Arduino
8
ArduinoBoardHardware
9
ArduinoBoard
10
ArduinoBoard• Microprocess
or:ATmega328P
• USBPort:
ConnecttoComputer
11
ArduinoBoard• ResetButton:
Resetstheprogrambutdoesnotremovetheprogramfrommemory
• DCPower:
ConnecttoexternalDCPowerSource
12
ArduinoBoard• DigitalPins:Canbe
usedasaninputoroutputandcantakeononeoftwovalues:0or5volts.NotethatPins0and1canbeusedforserialcommunications.
• AnalogInPins:Used
asanAnaloginputandcantakeonanyvaluefrom0to5volts.
• PowerPins:Provides5volts,3.3voltsandGroundReference
13
ArduinoBoard• ONLED:When
illuminatedindicatesthattheArduinoisoperating
• RXandTXLEDs:
IndicatesthattheArduinoisreceiving/transmittingData(e.g.whentheprogramisdownloadedfromthecomputer
• LLED:ProgrammableLEDviaDigialpin13
14
PulseWidthModulation
• Someofthedigitalpins(~3,~5,~6,~9,~10,~11)withtildescanoutputaPWMsignal
15
PulseWidthModulation• 50%DutyCycle• 25%DutyCycle
• 75%DutyCycle
• 100%DutyCycle
…
…
…
16
• PWMisa(approximately)490Hzsquarewavewhereaportion(percentage)ofthesignalishighwhiletheremainderofthesignalislow.
• Thepercentageof
thehighportioniscalledtheDutyCycle.
ArduinoS/W
17
ArduinoS/W• Arduinoprovidesaopen-sourcedevelopmentinterface
knowastheIntegratedDevelopmentEnvironment(IDE).• IDEsupportsprogramfacilityforprogramdevelopment,
verification,anddownloadingtotheArduinoboard.• IDEsupportaserialmonitorandserialplottertoallow
userstointerfacewiththeprogramrunningontheArduinoboard.
• IDEprovidessomebasicprogramsfortheusertolearnhowtoprogramtheArduinoboard.
• TheIDErunsonPCsandMacsandcanbedownloadedatwww.arduino.cc/en/main/software.
• AnArduinoprogramiscalledaSketchandiswritteninC/C++.
18
ArduinoIDE
19
Sketch/TextEditor
Console
MessageArea
Verify
Upload
New
Open
Save
Toolbar
SerialMonitor
Tab
• Editor:Wheresketchesarewritten
• Verify:TestswhetherthesketchmetstheC/C++syntaxrules
• Upload:Whentheverifyshowsnoerrors,sendthesketchtotheArduinoboard
• MessageAreaandConsole:Wheremessagesareoutputwhenverifyinganduploading
Firststepsforrunningasketch
1. ConnecttheArduinoboardtoaUSBportonyourcomputer.
2. OntheToolbar,selectTools>BoardandclickonyourArduinoboard
3. OntheToolbar,selectTools>PortandclickontheportyourArduinoisconnected.(com1,com2orcom3forPCsor/dev/cu.usbmodem-XXXXforMac.
20
WhereExampleSketchesarefound
21
Onthetoolbar,selectFile>Examplesandchosethedesiredsketch.
ArduinoSketchStructure• Sketchexecutablestatementsendwiththecharacter;
• Commentsareusedtodocumentthesketchq Multiplelinecommentsbeginwiththecharacters/*andendwiththe
characters*/q Singlelinecommentsbeginwiththecharacters//andcanbeplacedina
linebyitselforwithinthesamelineasanexecutablestatement.
• Declareglobalvariablesarea(notneededalways)isaplacetodefinevariablenamesusedinthesketchandtheirvalues.Thisappearsasthefirstexecutablestatements(i.e.,beforetheSetupandLoopareas).
• Setuparea(alwaysneeded)iswherestatementsarekeptthatonlyrunonceinthesketch.
• Looparea(alwaysneeded)iswherestatementsarewhicharecontinuouslyexecutedinlooporrepetitivemanner.
22
AnExampleSketch
23
SketchAreas
24
PreliminaryComments
SketchAreas
25
DeclareGlobalvariables
SketchAreas
26
Setup
SketchAreas
27
Loop
SetupandLoopStatements/Functions• SetupandloopareC/C++functionsandfollowtheC/C++
syntaxforfunctions.• Notethatboththesetupandloopstatementsbeginwith
thewordvoid.q ThistellstheC/C++complierthatthesetupandloopdonot
produceanyresultstobeusedbyotherpartsoftheprogram.
28
voidsetup(){//declarepin9tobeanoutput:pinMode(led,OUTPUT);}
voidloop(){//setthebrightnessofpin9://statementswereremovedforconvenienceanalogWrite(led,brightness);delay(30);}
SetupandLoopStatements/FunctionsCont’d
• Notethatthewordsetupandloopthereareleftandrightparentheseswithnothingbetweenthem.q ThistellstheC/C++complierthatthesetupandloopdonothave
anyspecialinputstorunthem.
• Notethatthestatementswithinthesetupandloopareasbeginwiththecharacter{andendwiththecharacter}.
29
voidsetup(){//declarepin9tobeanoutput:pinMode(led,OUTPUT);}
voidloop(){//setthebrightnessofpin9://statementswereremovedforconvenienceanalogWrite(led,brightness);delay(30);}
DeclareVariablesArea
• IntheDeclareVariablearea,variablesmaybedefinedwiththeirvalue.
intled=0;//assignthevalueofzerotoanintegervariablenamedled.
• Thesevariablesmaybeusedthroughoutthesketchbyboththesetupandloopfunctionsandarecalledglobalvariables.
• Notevariablesmayalsobedefinewithinfunctionslikesetup()andloop().Theycanonlybeusedwithinthefunctiontherearedeclaredandarecalllocalvariables.
30
SerialMonitor
• ToaccesstheSerialMonitorclickonTools>SerialMonitor.
• TheSerialMonitorsupportswriting/readingdatato/fromtheArduinoboard.
31
SerialPlotter
• ToaccesstheSerialPlotterclickonTools>SerialMonitor.
• TheSerialPlottersupportsplottingwaveformsinrealtime.
32
Functions
IntmyFunction(intx){intresult;result=x*x;returnresult}
33
voidsetup(){Serial.begin(9600);}voidloop(){inti=2;k=myFunction(i);Serial.println(k);delay(500)}
ArduinoBoardSyntax1,2
1. M.Banzi&M.Shiloh,GettingStartedwithArduino,3rdEdition,MakerMedia,2014
2. https://www.arduino.cc/reference/en/
34
BasicStructure• DeclareVariables
intled=9;//Declaresthevariableledasonethatstoresintegersandissettothevalue13
• Setupwherecodewillonlybeexecutedonce.voidsetup(){/*Addstatementstosetupsketchoperation*/}
• Loopwherecodewillberepeatedlyexecuteduntiltheboardpoweristurnedoff.
voidloop(){/*Addstatementstoperformsketchoperation*/}
35
SpecialSymbols• Semicolon-;
Everylineofcodemustendwithasemicolon.delay(1000);//delaythesketchby1second
• Parenthesis-(),squarebrackets-[]andCurlybrackets–{}Dataispassed/receivedto/fromafunctionwhichisplacedbetweenparenthesis.()Arraysaredefinedusingsquarebrackets.[]Blocksofcodeappearbetweencurlybrackets.{}intarray1[4]={1,3,4,7};voidloop(){
Serial.println(“ciao”);//Thewordciaoissenttotheserialmonitor}
• CommentsSinglelinecommentshavethecharacters//atthestartofthecommentsMulti-linecommentsappearbetweenthetwosetsofcharacters/*and*/
36
Constants• TheArduinosupportskeywordconstants.Hereareonesusedoften.
Seehttps://www.arduino.cc/reference/en/formore.HIGH|LOWUsedforpinstates:
1. ifthepinisusedasaninputthenit’saHIGHwhenavoltageof3.3voltsorgreaterappearsatthepinorit’saLOWwhenavoltageof1.5voltsorlessappearsatthepin.
2. ifthepinisusedasanoutputthentheboardplacesavoltageof5voltswhenthepinisdeclaredHIGHandplacesavoltageof0voltswhenthepinisdeclaredLOW.
INPUT|OUTPUTUsedtosetapintoeitheraninputoroutputport.true|falseUsedtotestacomparison.LED_BUILTINSetto13fortheon-boardLEDthatisconnectedtopin13.
37
DataTypes• TheArduinosupportsvarioustypesofdatatypes.Hereareonesused
often.Seehttps://www.arduino.cc/reference/en/formore.
1. Integerdatatype
int–Uses2bytesanddeclaresavariableasanintegerofvalue-32,768to32,768.unsignedint–Uses2bytesanddeclaresavariableasanintegerofvalue0to65,535.long–Uses4bytesanddeclaresavariableasanintegerofvalue-2,147,483,648to2,147,483,648unsignedlong–Uses4bytesanddeclaresavariableasanintegerofvalue0to4,294,967,295.
38
DataTypes(cont’d)2. Floatingpointdatatypes
float–Uses4bytes(1bitforsign,8bitsfortheexponent,and23forthevalue)anddeclaresavariableasfloatingpointnumberofvalue-3.4028235E38to3.4028235E38.double-Uses8bytes(1bitforsign,11bitsfortheexponent,and52forthevalue)anddeclaresavariableasfloatingpointnumberofvalue-1.79766931348623157E308to1.79766931348623157E308.2. 3.Arraydatatypesarray–Arraysaredefinedusingsquarebrackets,curlybrackets,andthefollowingformat.
intload[5]={1,2,3,4,5};
39
DataTypes(cont’d)4. Characterdatatypes
Charactersuse1bytepercharacterandaredefinedformatssimilartoarrays.
char–Uses1bytepercharacter
charstring1[3]=“BME”;
String–similartochar
Stringstring1[3]=“BME”;
40
DataTypes(cont’d)5. Conversionofvaluestoadatatype
float(x)-convertsthevalueofxintoafloatingpointdatatype(float)x– alternativeform
Usingthissyntax,conversionofavaluetoadatatypecanbeusedfortheotherdatatypes:int,unsigned,long,unsignedlong,double,etc.
41
ArithmeticOperators
ArithmeticOperator Test Example
+ Addition
- Subtraction
* Multiplication
/ Division
= Assignment
% Remainder r=7%5;//r=2
CompoundOperators
Symbol Function Example
++ Increment y=x++;//y=x+1
-- Decrement y=x--;//y=x-1
42
OtherOperatorsandSymbols
Relationshipandequalityoperatorsusedfornumberandstrings
Operator Test Example
== Equalto If(val==HIGH){
!= Notequalto If(val!=HIGH){
> Greaterthan If(val>HIGH){
< Lessthan If(val<HIGH){
>= Greaterthanorequalto
If(val>=HIGH){
<= Lessthanorequalto
If(val<=HIGH){
43
OtherOperatorsandSymbols
LogicalOperators
Symbol Function
&& LogicalAnd
|| LogicalOr
! Not
44
BitOperators
Operator Test
& BitwiseAnd
| BitwiseOr
^ BitwiseExclusiveOr
~ BitwiseNegation
ControlStatements
1. IFStatement:ifconditionistrue,takeactionandcontinue.IFStatement:ifconditionistrue,takeaction.Otherwisetakeanotheraction.
45
if(condition){//Iftruetakeactionval=10;
}
if(condition){//Iftruetakeaction
}else{
//Iffalsetakeanotheractionval=20;
}
ControlStatementsContinued2. ForStatement:definesaloopwithacounterinitialization,conditionforlooping,
counterincrement
InitializationoccursonceCondition:eachtimetheloopisexecutedtheconditionistested.Iftrueloopingcontinues.IffalseloopingendsandexecutionproceedstothestatementfollowingtheForStatementIncrement:eachtimethethroughtheloop,thecounterisincrementedandtheconditionisretested.
for(initialization;condition;increment){
for(inti=0;i<=100;i++){//foristartingat0,isit<=100,runloopandincrementI
delay(1000);//delayasecond //wheni>100endloop
}
46
ControlStatementsContinued3. WhileStatement:definesaloopwitha
conditionforrunningtheloop.Whentheconditionbecomesfalsetheloopends.
while(condition){while(var<=100){//whileavariablenamedvarlessthanorequalto100,runloop
delay(500);//delay1/2second//whenvar>100endloop
}
47
ControlStatementsContinued4. SwitchCaseStatement:definesaswitchandaseriesofcasestatements.
Whenthereisacasestatementmatchingtheswitch,thestatementsfollowingthecasestatementsareexecuted.Thedefaultcaseisexecutedifnomatchisfound.switch(var){
caselabel1;//statementsbreak;caselabel2;//statementsbreak;default;//statementsbreak;
}
48
switch(var){case1;delay(1000);//delay1secondbreak;case2;delay(500);//delay1/2secondbreak;default;delay(2000);//delay2secondsbreak;
}
MathematicalOperations1. Absolutevalue:findstheabsolutevalueofanumber,x.
abs(x)y=abs(-3);//y=3
2. Map:mapsavaluefromrangeofnumberstoanotherrange.map(value,fromlow,fromhigh,tolow,tohigh)y=map(20,1,50,1,100);//y=40
3. Minimum/Maximum:findstheminimum/maximumof2values.
min(val1,val2)max(val1,val2)y=min(3,4);//y=3y=max(3,4);//y=4
49
MathematicalOperationsContinued
4. Power:calculatesthevalueofanumberraisedtoapower.pow(base,exponent)y=pow(3,2);//y=9
5. Squareroot:calculatesthesquarerootofanumber.y=sqrt(value)Y=sqrt(64);//y=8
6. Trigonometricoperations:calculatesthesine,cosineandtangentofanumberinradians
sin(x)cos(x)tan(x)y=sin(3.14);//y=0y=cos(1.57);//y=0y=tan(0.78);//y=1 50
InputandOutputFunctionsDigitalPins
1. Configuringadigitalpinasaninputoroutputpinmode(pin,mode);pinmode(13,OUTPUT);//Turnspin13intoanoutput
2. TurnsadigitalpinHIGHorLOWdigitalWrite(pin,value);digitalWrite(13,LOW);//Turnspin13LOW
3. ControlsthePWMsignalatcertaindigitalpins;avalueof0turnsthepinoffandavaluesof255turnspinfullyon.
analogWrite(pin,value);analogWrite(13,127);//TurnsonaPWMwith50%dutycycle
4. ReadsthestateofaninputdigitalpinandreturnsHIGHorLOWdigitalRead(pin);val=digitalRead(13);//Readspin13andreturnsthevalueintovariablenamedval 51
InputandOutputFunctionsAnalogPins
1. ReadsthestateofaninputAnalogpinandreturna
numberfrom0to1023whichcorrespondstoavoltagebetween0and5volts.
analogRead(pin);val=analogRead(0);//Readsanalogpin0andreturnsthevalueintovariablenamedval
2. Youcannotwritetoananalogpin
52
TimeFunctions1. Returnsthenumberofmilliseconds(microseconds)thathavepassedsincethesketch
startedmillis();duration=millis()-lasttime;//computestimesincelasttimeinmilli-secondsmicros();duration=micros()-lasttime;//computestimesincelasttimeinmicro-seconds
2. Pausessketchforthenumberofmillisecondsspecified
delay(ms);delay(500);//delayfor½second
3. Pausessketchforthenumberofmicrosecondsspecified
delayMicroseconds(μs);delayMicroseconds(500);//delayfor½millisecond
53
SerialMonitor1. PreparestheArduinotosend/receivedata.
Serial.begin(speed);Serial.begin(9600);//TypicalsettingfortheArduino
2. Sendsdatatotheserialport.Serial.print(data);//printsdataSerial.println(data);//printsdatawithlinefeedSerial.print(75);//Printsthecharacters“75”Serial.print(75,HEX);//Prints“4B”(75inhexadecimal)Serial.print(75,BIN);//Prints1001011(75inbinary)Serial.println(75);//Prints”75”withacarriagereturnandlinefeedi.e.,“75\r\n”
3. Reads1byteofincomingserialdataSerial.read();data=Serial.read();//Putabyteofdataintothevariabledata
54
SerialPlotter1. Sameoperationattheserialmonitorexamplewhenserialportis
selectedawaveformplotofthedataisproduced.2. PreparestheArduinotosend/receivedata.
Serial.begin(speed);Serial.begin(9600);//TypicalsettingfortheArduino
3. Sendsdatatotheserialport.Serial.print(data);
55
Libraries1. InordertoextendtheArduino,librariesmayuses.
LibrariescontainfunctionswhichaidtheextensionoftheArduino.
2. Tousealibrary,itmustbeimportingorincludedintothesketch.#include<library.h>
3. Examplesa. LiquidCrystal– setCursor(),blink(),scrollDisplayLeft(),
scrollDisplayRight()b. Servo–attach(pin),servo.write(angle),servo.read()c. Stepper– setSpeed(rpms),step(steps)d. WiFi– WiFi.config(ip),WiFi.status()
56
Homework
1. DescribethedifferencebetweenandthefunctionsofDigitalPinsandAnalogPinsontheArduino
2. WhatisthepurposeoftheIDE?3. Whatisthepurposeoftheserialmonitorand
serialplotter?4. DescribethestructureofaSketch.5. Whatisthecomputerlanguageusedforthe
Arudino?
57