physics 124: lecture 3physics124.barreiro.ucsd.edu/wp-content/uploads/...valid divider options pwm...
TRANSCRIPT
Physics124:Lecture3
Motors:Servo;DC;StepperMessingwithPWM(and2-wayserial)
TheMotorShieldFromT.Murphy’sPHYS124lectures
ThreeTypes(forus)
• Servomotor– PWMsetsposition,usedforR/Cplanes,cars,etc.– 180° rangelimit,typically– 5Vsupply
• Steppermotor– Forpreciseangularcontrolorspeedcontrol– Canrotateindefinitely– Lotsofholdingtorque
• DCmotor– simplesttechnology;giveuponprecisecontrol– goodwhenyoujustneedsomethingtoSPIN!
2Phys124:Lecture3
WhenanyoldPWMwon’tdo
• ThefunctionanalogWrite() givesyoueasycontroloverthedutycycleofPWMoutput– butnocontrolatalloverfrequency
• ConsidertheHitec servomotorswe’llbeusing:
• Wantsa50Hzpulserate,andadutycyclefrom4.5%to10.5%(11/255to27/255)todrivefullrange
3Phys124:Lecture3
WhatfrequencyisArduino PWM?
• Dependsonwhichoutputisused• Pins5and6:default~977Hz– 16MHzclockratedividedby214 =16384
• Pins3,9,10,11:default488Hz– 16MHz/215
• Neitherisatalllikethe50Hzweneedfortheservomotor
Phys124:Lecture3 4
Whatchoicedowehave?• Wecanchangetheclockdivideronanyofthreecounters
internaltotheATMega328– timer/counter0,1,and2,considerregistermap:
– noteinparticularthelowest3bitsinTCCR2B– Timer/CounterControlRegisters,WaveformGenerationMode,
CompareMatchOutput– settingtheseaccordingtothefollowingrubricscalesspeed
Phys124:Lecture3 5
ValidDividerOptionsPWMpins
Register scaler values Divisor Approx. frequencies(Hz)
5, 6 TCCR0B 1,2,3, 4,5 1,8,64,256,1024 62500,7812, 977,244,61.0
9,10 TCCR1B 1,2,3,4,5 1,8,64,256,1024 31250,3906,488,122,30.5
3,11 TCCR2B 1,2,3,4,5,6,7 1,8,64,256,1024… 31250,3906,977,488,244,122,30.5
Phys124:Lecture3 6
• Defaultsinred• Limited choices,wecan’tpreciselyhit50Hztarget• Closestistousetimer0withdivideroption5(61Hz)• 0.9to2.1mspulsescorrespondto14/255to33/255• only20possiblestepsbythisscheme
Canyoufindoutwhyabovescalervaluesinbinarydon’tmatchtheCStableabove?
http://playground.arduino.cc/Main/TimerPWMCheatsheet
HowtosetdividerandchangePWMfreq.
• It’sactuallynotthathard– candoinsetuporinmainloop
• BrokenDown:– modifyingTCCR0Bassociatedwithpins5&6– & isbitwiseAND operator– 0b11111000isbinarymask,saying“keepfirstfiveas-is”– whilezeroingfinalthreebits(because0ANDanythingis0)– | isbitwiseOR operator,effectivelycombiningtwopieces– 0x05ishexfor5,whichwillselect61.0HzonTimer0– ifTCCR0Bstartedasvwxyzabc,itendsupasvwxyz101
Phys124:Lecture3 7
TCCR0B = TCCR0B & 0b11111000 | 0x05;
• Ifyouwanttoknowmore,understandbetter:Lesson12ofthisclassSecretsofArduinoPWM:https://www.arduino.cc/en/Tutorial/SecretsOfArduinoPWMTimerPWMcheatsheet:http://playground.arduino.cc/Main/TimerPWMCheatsheetUnderstandingTCCRnA/B:http://www.righto.com/2009/07/secrets-of-arduino-pwm.html
Phys124:Lecture3 8
FastPWM:
Phase-correctPWM:
CodetointeractivelyexplorePWMfrequencies
• Willuseserialcommunicationsinbothdirections
– continuedonnextslide…
Phys124:Lecture3 9
const int LED = 5; // or any PWM pin (3,5,6,9,10,11)char ch; // holds character for serial command
void setup(){
pinMode(LED,OUTPUT); // need to config for outputSerial.begin(9600);
}
…continued
Phys124:Lecture3 10
void loop(){
analogWrite(LED,128); // 50% makes freq. meas. easierif (Serial.available()){ // check if incoming (to chip)ch = Serial.read(); // read single character, or Serial.parseInt()
if (ch >=‘0’ && ch <=‘7’){// valid rangeif (LED == 3 || LED == 11){ // will use timer2TCCR2B = TCCR2B & 0b11111000 | int(ch - ‘0’);Serial.print(“Switching pin ”);Serial.print(LED);Serial.print(“ to setting “);Serial.println(ch);
}}if (ch >=‘0’ && ch <=‘5’){// valid for other timers
if (LED == 5 || LED == 6){ // will use timer0TCCR0B = TCCR0B & 0b11111000 | int(ch – ‘0’);Serial.print(same stuff as before…);
}if (LED == 9 || LED == 10){ // uses timer1TCCR1B etc.
} } } } // would indent more cleanly if space
Usingtheinteractiveprogram
• Useserialmonitor(Tools:SerialMonitor)– makesurebaudrateinlowerrightissameasinsetup()– cansendcharacterstoo– inthiscase,typesingledigitandreturn(orpresssend)– getbackmessagelike:
• Switching pin 11 to setting 6
– andshouldseefrequencychangeaccordingly
Phys124:Lecture3 11
RiggingaServotosort-ofwork
• Originalmotivationwasgettinga50Hzservotowork
– continuednextslide…
Phys124:Lecture3 12
const int SERVO = 5;char ch; // for interactive serial controlint level = 23; // 23 is 1.5 ms; 14 is 0.9; 33 is 2.1
void setup(){
pinMode(SERVO, OUTPUT); // set servo pin for outputSerial.begin(9600);TCCR0B = TCCR0B & 0b11111000 | 0x05; // for 61 HzanalogWrite(SERVO, level); // start centered
}
Continuation:mainloop
• Beinglazyandonlyacceptingsingle-charactercommands,limitedtotenvalues,mappingonto20– themap() functionisusefulhere– thech - ‘0’ does“ASCIIsubtraction”
Phys124:Lecture3 13
void loop(){
if (Serial.available()){ // check if incoming serial datach = Serial.read(); // read single characterif (ch >=‘0’ && ch <=‘9’){// use 10 step range for demo
level = map(ch-’0’,0,9,14,33); // map 0-9 onto 14-33analogWrite(SERVO, level); // send to servoSerial.print(“Setting servo level to: “);Serial.println(level);
}}delay(20); // interactive program, so slow
}
Abetter(andeasier!)way• Thepreviousapproachwasapoorfit– poormatchtofrequency,andnotmuchresolution
• Arduino hasalibraryspecificallyforthis:Servo.h• VariouslibrariescomewiththeArduino distribution– in/Applications/Arduino.app/Contents/Resources/Java/librariesonmyMac
– Handlesstepperandservomotors,LCDs,memorystorageineitherEEPROM(on-board)orSDcard;severalcommoncommunicationprotocols(ethernet—forusewithshield,SPI,2-wire,andemulatedserial)
– canlookatcodeasmuchasyouwant
Phys124:Lecture3 14
EEPROM/ Firmata/ SD/ Servo/ Stepper/Ethernet/ LiquidCrystal/ SPI/ SoftwareSerial/ Wire/
ExampleusingServolibrary
• Watchhoweasy:onedegreeresolution
Phys124:Lecture3 15
// servo_test . . . . slew servo back and forth thru 180 deg#include <Servo.h>
Servo hitec; // instantiate a servoint deg; // where is servo (in degrees)
void setup(){hitec.attach(9,620,2280); // servo physically hooked to pin 9// 620, 2280 are min, max pulse duration in microseconds// default is 544, 2400; here tuned to give 0 deg and 180 deg
}void loop(){for(deg = 0; deg <= 180; deg++){ // visit full range
hitec.write(deg); // send servo to degdelay(20);
}for(deg = 180; deg >= 0; deg--){ // return trip
hitec.write(deg); // send servo to degdelay(20);
}}
AvailableServoMethods• attach(pin)
– Attachesaservomotortoani/opin.• attach(pin,min,max)
– Attachestoapinsettingminandmaxvaluesinmicroseconds;defaultminis544,maxis2400
• write(deg)– Setstheservoangleindegrees.(invalidanglethatisvalidaspulsein
microsecondsistreatedasmicroseconds)• writeMicroseconds(us)
– Setstheservopulsewidthinmicroseconds(givesveryhighresolution)• read()
– Getsthe lastwrittenservopulsewidthasananglebetween0and180.• readMicroseconds()
– Getsthe lastwrittenservopulsewidthinmicroseconds• attached()
– Returnstrueifthereisaservoattached.• detach()
– Stopsanattachedservofrompulsingits i/opin.
Phys124:Lecture3 16
Libraries:Documentation
• Learnhowtousestandardlibrariesat:– http://arduino.cc/en/Reference/Libraries
• Butalsoanumberofcontributedlibraries• Upside:workanddeepunderstandingalreadydone• Downside:willyoulearnanythingbypickinguppre-madesophisticatedpieces?
Phys124:Lecture3 17
DCMotor
• Coiltoproducemagneticfield,onrotatingshaft• Permanentmagnetorfixedelectromagnet• Commutator toswitchpolarityofrotatingmagnetasitrevolves– the“carrot”isalwaysoutfront(andwillalsogetpushfrombehindifswitchoveristimedright)
Phys124:Lecture3 18
DCTorque-speedCurve• Seehttp://lancet.mit.edu/motors/motors3.html
• Stallsatτs;noloadatωn
• Outputmechanicalpowerisτω– areaofrectangletouchingcurve– maxpoweristhenPmax =¼τsωn
Phys124:Lecture3 19
ElectricalExpectations
• Windinghasresistance,R,typicallyinthe10Ω range
• Ifprovidedaconstantvoltage,V– windingeatspowerPw =V2/R– motordeliversPm =τω– currentrequiredisItot =(Pw +Pm)/V
• Atmaxpoweroutput(Pm =¼τsωn)– turnsoutwindinglossiscomparable,for~50%efficiency
Phys124:Lecture3 20
Example2.4Vmotor
• Randomonlinespecfor2.4Vmotor(bewareflippedaxes)– noteatpowermax0.0008Nm;0.7A;8000RPM(837rad/s)
• totalconsumption2.4×0.7=1.68W• outputmechanicalpower0.0008×837=0.67W;efficiency40%• atconstantV=2.4,totalpowerconsumptionrisesà 3Wtowardstall• 1.25AatstallimplieswindingR =V/I =1.9Ω
Phys124:Lecture3 21
Anotherrandomexample
• Noteprovisionofstalltorqueandno-loadspeed– suggestsmaxoutputpowerof
¼×2π(5500)/60×0.0183=2.6W– abouthalfthisatmaxefficiencypoint
2π(4840)/60×0.00248=1.25W– atmaxefficiency,0.17×12=2.04W,suggesting61%eff.– impliedcoilresistance12/1.06≈11Ω (judgedatstall)
• Lesson:forDCmotors,electricalcurrentdependsonloadingcondition– currentismaximumwhenmotorstrainingagainststall
Phys124:Lecture3 22
ServoInternals
• AServomotorisjustaseriouslygear-reducedDCmotorwithafeedbackmechanism(e.g,potentiometer)toshutitoffwhenitissatisfiedwithitsposition– anddrivemotorfasterorslowerdependingonhowfarofftarget
Phys124:Lecture3 23
DCmotor
potentiometer
gearreduction
CleverSteppers
• Steppermotorsworkinbabysteps• Insimplestversion,therearetwoDCwindings– typicallyarrangedinnumerousloopsaroundcasing– dependingondirectionofcurrentflow,fieldisreversible
• Rotorhaspermanentmagnetsperiodicallyarranged– butadifferingnumberfromtheexternalcoils
Phys124:Lecture3 24
teethonrotor
8“dentures”aroundoutside
NEMAstandard(NationalElectricalManufacturersAssociation),NEMA17:faceplate1.7in
ACarefullyChoreographedSequence
• Fourdifferentcombinationscanbepresentedtothetwocoils(A&B;eachbi-directional)– eachcombinationattractstherotortoa(usu.slightly)differentposition/phase
– steppingthroughthesecombinationsinsequencewalkstherotorbythehandtothenextstep
Phys124:Lecture3 25
Inpractice,rotorhasmanypolesaround (inteeth,often), soeachstepismuchfiner.
ToothedAnimation• Noteteethare
notphasedwith“dentures”allthewayaround– eachis90° from
neighbor• Thissequenceis
typicalofcenter-tapsteppers– canactivateone
sideofcoilatatime
• Noteusuallyhavemorethanfour“dentures”aroundoutside
Phys124:Lecture3 26
SteppingSchemes
• Cangoinfullsteps,halfsteps,orevenmicrostep– fullstepiswhereonecoilisonandhasfullattentionofrotor– iftwoadjacentcoilsareon,they“split”positionofrotor– sohalf-steppingallowsfinercontrol,buthighercurrentdraw
• everyotherstepdoublesnominalcurrent
– insteadofcoilsbeingallonoralloff,canapplydifferingcurrents(orPWM)toeach;calledmicrostepping• socanselectacontinuousrangeofpositionsbetweenfullsteps
• Obviously,controllingasteppermotorismorecomplicatedthanourotheroptions– mustmanagestatesofcoils,andstepthroughsequencesensibly
Phys124:Lecture3 27
TheStepperLibrary
• PartoftheArduino StandardLibraryset• Availablecommands:– Stepper(steps,pin1,pin2)– Stepper(steps,pin1,pin2,pin3,pin4)– setSpeed(rpm)– step(steps)
• ButArduino cannotdrivestepperdirectly– can’thandlecurrent– needtransistorstocontrolcurrentflow– arrangementcalledH-bridgeideallysuited
Phys124:Lecture3 28
Examplestrippedcode
Phys124:Lecture3 29
#include <Stepper.h>#define STEPS 100 // change for your stepper
Stepper stepper(STEPS, 8, 9, 10, 11);
int previous = 0;
void setup(){stepper.setSpeed(30); // 30 RPM
}
void loop(){int val = analogRead(0); // get the sensor value
// move a number of steps equal to the change in the// sensor readingstepper.step(val - previous);
// remember the previous value of the sensorprevious = val;
}
AUnipolar StepperMotor:CenterTap
• Aunipolar stepperhasacentertapforeachcoil– halfofcoilcanbeactivatedatatime– candrivewithtwoArduino pins(leftarrangement)– orfourpins(right)– bothuseULN2003orULN2004DarlingtonArray
Phys124:Lecture3 30
Centertapnotshownoncoil!
Centertap->
Drivingacoil:
Phys124:Lecture3 31
ADarlingtonarrayprovidesbufferstohandlecurrent
EachchannelisapairoftransistorsinaDarlingtonconfiguration
• wheninputgoeshigh, theoutputwillbepulleddownnearground.(detailsinnextslides)
• whichthenpresentsmotorwithvoltagedropacrosscoil(COMMONisatthesupplyvoltage)
Parenthesis:Transistorasaswitch
Phys124:Lecture3 32
Operateineithercut-off(OFF)orsaturation(ON)regions
Example:Bipolarjunction transistor(BJT)
http://www.electronics-tutorials.ws/transistor/tran_4.html
Phys124:Lecture3 33
Parenthesis:Transistorasaswitch
OFF
ON
http://www.electronics-tutorials.ws/transistor/tran_4.html
Phys124:Lecture3 34
NPNTransistorasaswitch
PNPTransistorasaswitch
Sinkscurrent
Sourcescurrent
http://www.electronics-tutorials.ws/transistor/tran_4.html
𝐼" = 𝛽𝐼&
BacktotheDarlingtontransistor
Phys124:Lecture3 35
EachDarlington:
Exampleuses:
Whatisthatdiodenexttothemotor?
Typeequationhere.
𝐼"~𝛽6𝐼&
Studentquestion:Flyback/freewheeldiode?
Phys124:Lecture3 36https://en.m.wikipedia.org/wiki/Flyback_diode
Eliminatesthesuddenvoltagespikeseenacrossaninductive loadwhenitssupplycurrentissuddenly reduced/interrupted.
Unipolar hookup;controlwithfourpins
• Yellowmotorleadsarecentertap,connectedtoexternalpowersupply𝑉8 (jackhangingoffbottom)
Phys124:Lecture3 37
ABipolarStepperMotor:NoCenterTap
• Inthiscase,thecoilmustseeonesideatgroundwhiletheotherisatthesupplyvoltage
• Atleftis2-pincontrol;rightis4-pincontrol– H-bridgeisL293Dorequiv.– transistorsjustmakeforlogicinversion(1inopp.2in,etc.)
Phys124:Lecture3 38
H-bridgeInternals• AnH-bridgeisso-calledbecauseofthearrangementof
transistorswithamotorcoilspanningacross– twotransistors(diagonallyopposite)willconductatatime,witha
motorcoilinbetween,e.g.,onebridgepercoil
Phys124:Lecture3 39Noticetheflyback diodes.
24waysofmakinganH-bridge:http://www.talkingelectronics.com/projects/H-Bridge/H-Bridge-1.htmlhttp://www.modularcircuits.com/blog/articles/h-bridge-secrets/h-bridges-the-basics/
L293D:quadrupolehalf-Hdrivers
Phys124:Lecture3 40
BipolarHookup;controlwithfourpins
• Inputsupplyshownasjackhangingoffbottom
Phys124:Lecture3 41
Steppermotorwiring
Phys124:Lecture3 42
Full-stepandhalf-stepbipolar drives
Phys124:Lecture3 43
Fullstep
Halfstep
Internalwiringexamples…todriveyou&yourmotorcrazy
Phys124:Lecture3 44
Moreathttp://www.allaboutcircuits.com/textbook/alternating-current/chpt-13/stepper-motors/
TheMotorShield
• Wehavekitshieldsthatcandrivea“motorparty”– 2servosplus2steppers,or– 2servosplus4DCmotors,or– 2servosplus2DCmotorsplus1stepper
• Allowsexternalpowersupply:motorscantakealotofjuice
Phys124:Lecture3 45
TheMotorShield’sAssociatedLibrary
• Seeinstructionsat– http://learn.adafruit.com/adafruit-motor-shield– Installlibrarylinkedfromabovesite– followinstructionsfoundattopofabovepage– mayneedtomakedirectorycalledlibraries intheplacewhereyourArduino sketchesarestored• specifiedinArduino preferences
– andstoreinittheunpackedlibrariesasthedirectoryAFMotor
• Onceinstalled,justincludeinyoursketch:– #include <AFMotor.h>
• Openincludedexamplestogetgoingquickly
Phys124:Lecture3 46
ExampleCode
• StepperCommandsinAFMotor– #include <AFMotor.h>
• grablibrary
– AF_Stepper my_stepper(#S/R,port);• my_stepper isarbitrarynameyouwanttocallmotor• argumentsarestepsperrevolution,whichshieldport(1or2)
– my_stepper.setSpeed(30);• setRPMofmotorforlargemoves(here30RPM)
– my_stepper.step(NSTEPS,DIRECTION,STEP_TYPE);• takeNSTEPSsteps,eitherFORWARD orBACKWARD• candoSINGLE,DOUBLE,INTERLEAVE,MICROSTEP
– my_stepper.release();• turnoffcoilsforfreemotion
Phys124:Lecture3 47
StepTypes• SINGLE
– oneleadatatimeenergized,insequence3,2,4,1• ascounteddownwardonleftport(port1)onmotorshield
– normalstepsize• DOUBLE
– twoleadsatatimeareenergized:1/3,3/2,2/4,4/1• splitspositionofprevioussteps;tugofwar
– normalstepsize,buttwicethecurrent,power,torque• INTERLEAVE
– combinesbothabove:1/3,3,3/2,2,2/4,4,4/1,1– stepsarehalf-size,alternatingbetweensinglecurrentand
doublecurrent(so50%morepowerthanSINGLE)• MICROSTEP
– usesPWMtosmoothlyrampfromofftoenergized– inprinciplecanbeusedtogoanywherebetweenhardsteps
Phys124:Lecture3 48
DCMotorswithmotorshield/AFMotor
• DCmotorsarehandledwiththefollowingcommands– #include <AFMotor.h>
• grablibrary
– AF_DCMotor mymotor(port);• portis1,2,3,or4accordingtoM1,M2,M3,M4onshield
– mymotor.setSpeed(200);• justaPWMvalue(0−255)tomoderatevoltagesenttomotor• notRPM,notload-independent,etc.— crudecontrol
– mymotor.run(DIRECTION);• FORWARD,BACKWARD,orRELEASE• depends,ofcourse,onhookupdirection
Phys124:Lecture3 49
ServosontheShield• TwoServohookupsareprovidedontheshield• Reallyjustpower,ground,andsignalcontrol
– signalcontrolisArduino pins9and10– useServo.h standardlibrary– pin9à Servo2onshield;pin10à Servo1onshield
Phys124:Lecture3 50
Powerjumper
Thisismykindof(stepper)party:12!
Phys124:Lecture3 51
BeagleBone GreenBNCtotriggermotion
RJ45ðcablesgotosteppers
Phys124:Lecture3 52
BeagleBone Green
Announcements
• RememberTAofficehours:– TBD
• Turninprev.week’slabbystartofnextlabperiod,at2PM(daydep.onMon/Tuesection)– candropinslotonTAroominbackofMHA3544anytime
Phys124:Lecture3 53