BME 301 - New Jersey Institute of Technology

57
BME 301 7-Arduino 1

Transcript of BME 301 - New Jersey Institute of Technology

Page 1: BME 301 - New Jersey Institute of Technology

BME301

7-Arduino

1

Page 2: BME 301 - New Jersey Institute of Technology

ArduinoBasics

2

Page 3: BME 301 - New Jersey Institute of Technology

Overview

•  Learnhowtouseamicroprocessorsystem/platformdevelopmentboard

•  ArduinoUNO•  Hardware•  Software•  Projects

3

Page 4: BME 301 - New Jersey Institute of Technology

Computers•  Whatisacomputer

o FastNitwitq Performinstructionsveryquicklyq Needstobetoldwhattodo.

•  Computertypeso Mainframeso Minicomputerso PersonalComputerso Microprocessors

•  Allhavesimilarhardwareandneedsoftwareorprogramstooperatethem

4

Page 5: BME 301 - New Jersey Institute of Technology

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

Page 6: BME 301 - New Jersey Institute of Technology

GeneralPurposeComputersVsSpecialPurposeComputersVsMicroprocessors

•  Generalpurposecomputersaredesignedtohandleavarietyoftasks.

•  Specialpurposecomputerswhichcanbeprogrammedtoperformadesiredtask.

•  Ingeneral,amicroprocessorfallsintotheSpecialPurposeComputerclass.

•  VariousMicroprocessorso  Intel8088o ZilogZ80o Motorola6800o Etc.

6

Page 7: BME 301 - New Jersey Institute of Technology

MicroprocessorSystemsorPlatforms

•  Microprocessorscontaincomponentstoafforddevelopmentofcomputerbasedsystems.

•  Varioustypeso Arduinoo RaspberryPio Etc.

7

Page 8: BME 301 - New Jersey Institute of Technology

Arduino•  Arduinoisanopen-sourcehardwareandsoftwarecompany1

•  Buildssingleboardmicrocontrollersandmicrocontrollerkits1

•  Arduinoboarddesignsuseavarietyofmicroprocessorchipsandcontrollers.1o Unoo MegasimilartotheUnobutbiggerwithmoreI/Oporto  Lilypadusedforwearableprojectso NanosmallerthantheUnoo Etc.1wikipedia.org/wiki/Arduino

8

Page 9: BME 301 - New Jersey Institute of Technology

ArduinoBoardHardware

9

Page 10: BME 301 - New Jersey Institute of Technology

ArduinoBoard

10

Page 11: BME 301 - New Jersey Institute of Technology

ArduinoBoard•  Microprocess

or:ATmega328P

•  USBPort:

ConnecttoComputer

11

Page 12: BME 301 - New Jersey Institute of Technology

ArduinoBoard•  ResetButton:

Resetstheprogrambutdoesnotremovetheprogramfrommemory

•  DCPower:

ConnecttoexternalDCPowerSource

12

Page 13: BME 301 - New Jersey Institute of Technology

ArduinoBoard•  DigitalPins:Canbe

usedasaninputoroutputandcantakeononeoftwovalues:0or5volts.NotethatPins0and1canbeusedforserialcommunications.

•  AnalogInPins:Used

asanAnaloginputandcantakeonanyvaluefrom0to5volts.

•  PowerPins:Provides5volts,3.3voltsandGroundReference

13

Page 14: BME 301 - New Jersey Institute of Technology

ArduinoBoard•  ONLED:When

illuminatedindicatesthattheArduinoisoperating

•  RXandTXLEDs:

IndicatesthattheArduinoisreceiving/transmittingData(e.g.whentheprogramisdownloadedfromthecomputer

•  LLED:ProgrammableLEDviaDigialpin13

14

Page 15: BME 301 - New Jersey Institute of Technology

PulseWidthModulation

•  Someofthedigitalpins(~3,~5,~6,~9,~10,~11)withtildescanoutputaPWMsignal

15

Page 16: BME 301 - New Jersey Institute of Technology

PulseWidthModulation•  50%DutyCycle•  25%DutyCycle

•  75%DutyCycle

•  100%DutyCycle

16

•  PWMisa(approximately)490Hzsquarewavewhereaportion(percentage)ofthesignalishighwhiletheremainderofthesignalislow.

•  Thepercentageof

thehighportioniscalledtheDutyCycle.

Page 17: BME 301 - New Jersey Institute of Technology

ArduinoS/W

17

Page 18: BME 301 - New Jersey Institute of Technology

ArduinoS/W•  Arduinoprovidesaopen-sourcedevelopmentinterface

knowastheIntegratedDevelopmentEnvironment(IDE).•  IDEsupportsprogramfacilityforprogramdevelopment,

verification,anddownloadingtotheArduinoboard.•  IDEsupportaserialmonitorandserialplottertoallow

userstointerfacewiththeprogramrunningontheArduinoboard.

•  IDEprovidessomebasicprogramsfortheusertolearnhowtoprogramtheArduinoboard.

•  TheIDErunsonPCsandMacsandcanbedownloadedatwww.arduino.cc/en/main/software.

•  AnArduinoprogramiscalledaSketchandiswritteninC/C++.

18

Page 19: BME 301 - New Jersey Institute of Technology

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

Page 20: BME 301 - New Jersey Institute of Technology

Firststepsforrunningasketch

1.  ConnecttheArduinoboardtoaUSBportonyourcomputer.

2.  OntheToolbar,selectTools>BoardandclickonyourArduinoboard

3.  OntheToolbar,selectTools>PortandclickontheportyourArduinoisconnected.(com1,com2orcom3forPCsor/dev/cu.usbmodem-XXXXforMac.

20

Page 21: BME 301 - New Jersey Institute of Technology

WhereExampleSketchesarefound

21

Onthetoolbar,selectFile>Examplesandchosethedesiredsketch.

Page 22: BME 301 - New Jersey Institute of Technology

ArduinoSketchStructure•  Sketchexecutablestatementsendwiththecharacter;

•  Commentsareusedtodocumentthesketchq  Multiplelinecommentsbeginwiththecharacters/*andendwiththe

characters*/q  Singlelinecommentsbeginwiththecharacters//andcanbeplacedina

linebyitselforwithinthesamelineasanexecutablestatement.

•  Declareglobalvariablesarea(notneededalways)isaplacetodefinevariablenamesusedinthesketchandtheirvalues.Thisappearsasthefirstexecutablestatements(i.e.,beforetheSetupandLoopareas).

•  Setuparea(alwaysneeded)iswherestatementsarekeptthatonlyrunonceinthesketch.

•  Looparea(alwaysneeded)iswherestatementsarewhicharecontinuouslyexecutedinlooporrepetitivemanner.

22

Page 23: BME 301 - New Jersey Institute of Technology

AnExampleSketch

23

Page 24: BME 301 - New Jersey Institute of Technology

SketchAreas

24

PreliminaryComments

Page 25: BME 301 - New Jersey Institute of Technology

SketchAreas

25

DeclareGlobalvariables

Page 26: BME 301 - New Jersey Institute of Technology

SketchAreas

26

Setup

Page 27: BME 301 - New Jersey Institute of Technology

SketchAreas

27

Loop

Page 28: BME 301 - New Jersey Institute of Technology

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

Page 29: BME 301 - New Jersey Institute of Technology

SetupandLoopStatements/FunctionsCont’d

•  Notethatthewordsetupandloopthereareleftandrightparentheseswithnothingbetweenthem.q ThistellstheC/C++complierthatthesetupandloopdonothave

anyspecialinputstorunthem.

•  Notethatthestatementswithinthesetupandloopareasbeginwiththecharacter{andendwiththecharacter}.

29

voidsetup(){//declarepin9tobeanoutput:pinMode(led,OUTPUT);}

voidloop(){//setthebrightnessofpin9://statementswereremovedforconvenienceanalogWrite(led,brightness);delay(30);}

Page 30: BME 301 - New Jersey Institute of Technology

DeclareVariablesArea

•  IntheDeclareVariablearea,variablesmaybedefinedwiththeirvalue.

intled=0;//assignthevalueofzerotoanintegervariablenamedled.

•  Thesevariablesmaybeusedthroughoutthesketchbyboththesetupandloopfunctionsandarecalledglobalvariables.

•  Notevariablesmayalsobedefinewithinfunctionslikesetup()andloop().Theycanonlybeusedwithinthefunctiontherearedeclaredandarecalllocalvariables.

30

Page 31: BME 301 - New Jersey Institute of Technology

SerialMonitor

•  ToaccesstheSerialMonitorclickonTools>SerialMonitor.

•  TheSerialMonitorsupportswriting/readingdatato/fromtheArduinoboard.

31

Page 32: BME 301 - New Jersey Institute of Technology

SerialPlotter

•  ToaccesstheSerialPlotterclickonTools>SerialMonitor.

•  TheSerialPlottersupportsplottingwaveformsinrealtime.

32

Page 33: BME 301 - New Jersey Institute of Technology

Functions

IntmyFunction(intx){intresult;result=x*x;returnresult}

33

voidsetup(){Serial.begin(9600);}voidloop(){inti=2;k=myFunction(i);Serial.println(k);delay(500)}

Page 34: BME 301 - New Jersey Institute of Technology

ArduinoBoardSyntax1,2

1.  M.Banzi&M.Shiloh,GettingStartedwithArduino,3rdEdition,MakerMedia,2014

2.  https://www.arduino.cc/reference/en/

34

Page 35: BME 301 - New Jersey Institute of Technology

BasicStructure•  DeclareVariables

intled=9;//Declaresthevariableledasonethatstoresintegersandissettothevalue13

•  Setupwherecodewillonlybeexecutedonce.voidsetup(){/*Addstatementstosetupsketchoperation*/}

•  Loopwherecodewillberepeatedlyexecuteduntiltheboardpoweristurnedoff.

voidloop(){/*Addstatementstoperformsketchoperation*/}

35

Page 36: BME 301 - New Jersey Institute of Technology

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

Page 37: BME 301 - New Jersey Institute of Technology

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

Page 38: BME 301 - New Jersey Institute of Technology

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

Page 39: BME 301 - New Jersey Institute of Technology

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

Page 40: BME 301 - New Jersey Institute of Technology

DataTypes(cont’d)4.  Characterdatatypes

Charactersuse1bytepercharacterandaredefinedformatssimilartoarrays.

char–Uses1bytepercharacter

charstring1[3]=“BME”;

String–similartochar

Stringstring1[3]=“BME”;

40

Page 41: BME 301 - New Jersey Institute of Technology

DataTypes(cont’d)5.  Conversionofvaluestoadatatype

float(x)-convertsthevalueofxintoafloatingpointdatatype(float)x– alternativeform

Usingthissyntax,conversionofavaluetoadatatypecanbeusedfortheotherdatatypes:int,unsigned,long,unsignedlong,double,etc.

41

Page 42: BME 301 - New Jersey Institute of Technology

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

Page 43: BME 301 - New Jersey Institute of Technology

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

Page 44: BME 301 - New Jersey Institute of Technology

OtherOperatorsandSymbols

LogicalOperators

Symbol Function

&& LogicalAnd

|| LogicalOr

! Not

44

BitOperators

Operator Test

& BitwiseAnd

| BitwiseOr

^ BitwiseExclusiveOr

~ BitwiseNegation

Page 45: BME 301 - New Jersey Institute of Technology

ControlStatements

1.  IFStatement:ifconditionistrue,takeactionandcontinue.IFStatement:ifconditionistrue,takeaction.Otherwisetakeanotheraction.

45

if(condition){//Iftruetakeactionval=10;

}

if(condition){//Iftruetakeaction

}else{

//Iffalsetakeanotheractionval=20;

}

Page 46: BME 301 - New Jersey Institute of Technology

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

Page 47: BME 301 - New Jersey Institute of Technology

ControlStatementsContinued3.  WhileStatement:definesaloopwitha

conditionforrunningtheloop.Whentheconditionbecomesfalsetheloopends.

while(condition){while(var<=100){//whileavariablenamedvarlessthanorequalto100,runloop

delay(500);//delay1/2second//whenvar>100endloop

}

47

Page 48: BME 301 - New Jersey Institute of Technology

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;

}

Page 49: BME 301 - New Jersey Institute of Technology

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

Page 50: BME 301 - New Jersey Institute of Technology

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

Page 51: BME 301 - New Jersey Institute of Technology

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

Page 52: BME 301 - New Jersey Institute of Technology

InputandOutputFunctionsAnalogPins

1.  ReadsthestateofaninputAnalogpinandreturna

numberfrom0to1023whichcorrespondstoavoltagebetween0and5volts.

analogRead(pin);val=analogRead(0);//Readsanalogpin0andreturnsthevalueintovariablenamedval

2.  Youcannotwritetoananalogpin

52

Page 53: BME 301 - New Jersey Institute of Technology

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

Page 54: BME 301 - New Jersey Institute of Technology

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

Page 55: BME 301 - New Jersey Institute of Technology

SerialPlotter1.  Sameoperationattheserialmonitorexamplewhenserialportis

selectedawaveformplotofthedataisproduced.2.  PreparestheArduinotosend/receivedata.

Serial.begin(speed);Serial.begin(9600);//TypicalsettingfortheArduino

3.  Sendsdatatotheserialport.Serial.print(data);

55

Page 56: BME 301 - New Jersey Institute of Technology

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

Page 57: BME 301 - New Jersey Institute of Technology

Homework

1.  DescribethedifferencebetweenandthefunctionsofDigitalPinsandAnalogPinsontheArduino

2.  WhatisthepurposeoftheIDE?3.  Whatisthepurposeoftheserialmonitorand

serialplotter?4.  DescribethestructureofaSketch.5.  Whatisthecomputerlanguageusedforthe

Arudino?

57