Tải bản đầy đủ (.pdf) (105 trang)

Introduction to STM32 ARM microcontroller

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (2.41 MB, 105 trang )




IntroductiontoSTM32ARM
Microcontrollerwith
STMHAL-Library&SW4STM32




Forthosewhodon’twanttousembed.
Thisbookincludesexplanationsaboutkeyperipheralsandmajorfunctions,inaddition,
buildingafreeARMofflinedevelopmentenvironment,automaticprogramgeneration
CubeMX,FreeRTOSintroduction.
ThisbookisoptimalforSTmicrocontrollerbeginners!












Index
1. Introduction
2. EnvironmentDevelopment
2-1.Downloadofintegrateddevelopmentenvironment


2-2.Installofintegrateddevelopmentenvironment
2-2-1.InstallJavaSE
2-2-2.InstallSW4STM32
2-3.SW4STM32Settings
2-4.EclipseLocalization
2.5.Autosavesettingbeforebuild
2-6.AddExplorerLink
2-4.Downloadfirmwritingsoftware
2-5.Installfirmwritingsoftware
2-6.DownloadCubeMX
2-7.installCubeMX
2-8.InstallCubeMXPackage
2-9.InformationCubeMXPackage
3.AboutSTM32Microcontroller
3-1.STM32MicrocontrollerSelection
3-2.STMicrocontrollerIntroduction
3-3.AfterGettingNucleoBoard
4.LightingLED
4-1.AutoCodeGenerationwithCubeMX
4-1-1.BoardSelection
4-1-2.SettingofCubeMX
4-2.ImportProjecttoSW4STM32
4-3.Coding
4-4.WriteFirmware
4-4-1.WritefromEclipse
4-4-2.Writewithmbedfunction
4-4-3.WritewithST-LinkUtility
5.Debug
5-1.DebugwithOpenOCD
5-2.DebugwithUART

5-2-1.CubeMXSetting
5-2-2.AddCode
5-2-3.UseofFloatingPoint
6.SPICommunication
6-1.CodeGenerationwithCubeMX
6-1-1.BoardSelect
6-1-2.CubeMXSetting
6-1-3.SPIWiring
6-1-4.SPICoding
7.I2CCommunication


7-2.I2CWiring
7-3.I2CCoding
8.Timer
8-1.IntervalTimer
8-1-1.CubeMXSetting
8-1-2.CalcInterruptInterval
8-1-3.Coding
8-2.OutputCompare
8-2-1.CubeMXSetting
8-2-2.CalcPWMFrequency
8-2-3.Coding
8-3.ReadFromQuadratureEncoder
8-3-1.CubeMXSetting
8-3-2.Coding
9.ExternalEventTrigger
9-1.CubeMXSetting
9-2.Coding
10.ADConversion

10-1.SoftwareTrigger
10-1-1.CubeMXSetting
10-1-2.Coding
10-2.TimerTrigger
10-2-1.CubeMXSetting
10-2-2.Coding
10-3.InputImpedance
11.UARTCommunication
11-1.UARTTransfer
11-1-1.CubeMXSetting
11-1-2.Coding
11-2.UARTRecieve
11-2-1.CubeMXSetting
11-2-2.Coding
12.DAConversion
12-1.CubeMXSetting
12-2.Coding
13.RealTimeClock
13-1.CubeMXSetting
13-2.RTCWiring
13-3.Coding
14.UseofDSP
14-1.MATHLibrary
14-2.FFT
14-2-2.Coding
15.FreeRTOS
15-1.CubeMXSetting
15-2.Coding
16.UseofSDCard



16-1.CubeMXSetting
16-2.FatFSLibrarySetting
16-2-1.DownloadFatFS
16-2-2.ModifyLibrary
15-6.WiringSD
16-4.Coding
17.MountingPCB
17-1.Peripherals
17-2.SerialDebug
17-3.WriteFirm
18.Conclusion
Appendix
















1.Introduction

Amicrocontollerthatisinstalledinelectronicdevicesareclosetohome.Amongthe
microcontollers,theSTM32microcontrollerisoneofthemostpopularARM-based
microcontrollersusedinvariousproducts,withmanylineups.However,theyarenotonly
complicatedanddifficulttosetup,butalsodifficulttobuildintegrateddevelopment
environment.TheSTM32microcontrollerisdifficultforbeginner.

Inrecentyearsithasbecomeeasytoprogramwithsimplecodewithoutbuilding
integrateddevelopmentenvironmentwithonlinecompilercalledmbed.However,since
mbedisanonlinecompiler,thereisresistancetousingworkcodesinthecloud,regardless
ofplay.Meanwhile,attheendof2015,STunveiledthefreeintegrateddevelopment
environment,SystemWorkbenchforSTM32(SW4STM32),andtheofflineintegrated
developmentenvironmentcanbeeasilyusedforfree.

AlthoughtheenvironmentthatcanusetheSTM32microcontollereasilyisprepared,
booksoftheSTmicrocontollerintheworldareexplainedusinglibrariescalledSTD
libraries,andhowitisuseddiffersfromHALlibrarypromotedbySTinrecentyears.
HALlibraryisinsufficientininformation.


Withthisbackground,IfeltthelimitsofprocessingspeedofPICmicrocontollerthatI
haveusedforover5years,decidedtoshiftfromPICmicrocontollertoSTM32
microcontollerin2016.Basedontheexperienceatthattime,Icompiledthisbookasan
introductiontoSTM32microcontoller.

Unlikegeneralintroductorybooks,wechosetheorderofchaptersratherthanevery
functionofmicrocontoller,inorderthatengineerswhostartmanybuilt-insystemswork.
Also,asatarget,itistargetedatthosewhohavelearnedbasicoperationofPCandcan
understandClanguageatminimum.




*Samplecodewillbereleasedsequentiallyonthefollowinglink.
URL   />
 



































2.EnvironmentDevelopment
2-1.Downloadofintegrateddevelopmentenvironment
SystemWorkbenchforSTM32(SW4STM32)canbeusedfreeofcharge,butuserregistrationis
necessarytodownload.RegistrationisrequiredseparatelyfromtheSTMaccount.
*SincetheloginscreenisnothttpsasofMarch2017,watchoutforusingaccountnamesand
passwordscarefully.

  URL   />
Aftercreatinganaccountandloggingin,click"SystemWorkbenchforSTM32"ontheleftsideand
click"DownloadingtheSystemWorkbenchforSTM32installer".

Pleasedownloadtheinstalleraccordingtoyourenvironment,32bitenvironmentor64bit
environment.
ItcanbeusednotonlyonWindowsbutalsoonMacOSandLinux.



2-2.Installofintegrateddevelopmentenvironment
ThistimewewillexplainaboutinstallingonWindows7machine.
2-2-1.InstallJavaSE
  SinceSW4STM32isanEclipse-basedintegrateddevelopmentenvironment,installationofJavaSE
isrequired.IfJavaSEisalreadyinstalled,pleaseproceedtothenextsection.Whenyoustarted

installingthedownloadedSW4STM32,installationisstoppedautomaticallywhenJavaSEisnot
installed.Then,theinstallationofJavaSEisurged,butthistimeJavaSEwillbeinstalledfirst.
  URL
/>


Ifyoucanagreeafterconfirmingthelicenseinformation,select"AcceptLicenseAgreement"atthe
topofthedownloadlink,thedownloadlinkbecomeseffectiveanddownloadingbecomespossible.
Pleasealsoselectfrom32bitsor64bitsforWindowsdependingontheenvironmentanddownloadit.
 

  AfterdownloadingtheinstallerofJavaSE,clicktheexecutablefileandinstallit.
 
2-2-2.InstallSW4STM32
RuntheinstallexecutablefileofSW4STM32withadministratorprivilegesandinstallit.Ontheway,
theST-Linkdriverinstallationscreenwillappear.Click"Install"toinstalltheST-Linkdriver.



2-3.SW4STM32Settings
  ClickSW4STM32shortcutlinkandstartSW4STM32.

Iftheerrormessage"Javawasstartedbutreturnedexitcode=13"hasappearedanditcannotbe
startedup,pleaseassociateSW4STM32withJavaSEasfollows.Inparticular,errorseemstooccurin
Windows7environmentinmanycases.


Javaerrormessageexample

  Ifanerrormessageliketheoneaboveappears,ifitcannotbestarted,modifytheEclipse

configurationfile.OpenC:¥Ac6¥SystemWorkbench¥eclipse.iniwithnotepadetc.andaddthe
followingtwolinesonthefirstline.
-vm
C:/ProgramFiles/Java/jdk1.8.0_121/bin/javaw.exe

※ "jdk1.8.0_121"intheredletterdiffersdependingontheversionofJavaSEinstalled.Inthecaseof
Windows,checktheversionwherethedirectoryexistsinExploreretc.,andadditbyreplacingthered
letterpartasnecessary.

Whenyoustartup,theworkspaceselectionscreenwillbedisplayed.Bydefault,the"workspace"
folderdirectlyundertheuserfolderistheworkingdirectory.





2-4.EclipseLocalization
ThereareseveralwaystomakeEclipseJapanese,butthistimewewilluseJapanesetomakeitBabel.
IfyouwanttouseitinEnglish,pleaseproceedtothenextsection.
Click"InstallNewSoftware"fromEclipse"Help".

Click"Add"fromtheinstallationscreen.


CheckthelinkforthelatestMarsfromthesiteofBabelbelow.
/>

Enter"BABEL"forthename,putthelatestURLforMARSinthelocationandclick"OK".   Inthis
time,theEclipseisMARS.PleasecheckanduseyourEclipseversion.


URL   />
Pleasepatientlywait.AreadingprogressbarwillappearinthelowerrightbaroftheEclipse
applicationandalistwillberetrieved.



Whenthelistisdisplayed,enter"ja"inthesearchfieldandsearchforJapanese.Inthat,check"Babel
LanguagePackforeclipseinJapanese"andclick"Next".Checkthelicense,check"accept",andclick
"Finish".


Downloadandinstallationwillstart.

Pleasecheckiflicensingorsecurityconfirmationscreenappearsagainduringinstallation.


Whentheinstallationiscompleted,aconfirmationmessageofsoftwarerestartwillbedisplayed.Please
click"Yes"andrestart.

Afterrebooting,itiscompletedwhenitisJapaneseizedandstartedup.



2.5.Autosavesettingbeforebuild
Inthedefaultsetting,unlessyousavethechangedcontentsatbuildtime,thechangecontentswillnot
bechanged.Byactivatingthepre-buildautosavesetting,changeswillbeautomaticallysavedatbuild
timeandyoucanpreventmistakesduetoforgettingtosave.
Check"Saveautomaticallybeforebuild"in"Window"→"Settings"→"General"→"Workspace"and
click"Apply".




2-6.AddExplorerLink
  BydefaultEclipsedoesnothaveanexplorerlinktoaccessfileslocatedlocallyfromtheproject.
Followtheprocedurebelowtoaddalink.
ChooseExecute→ExternalTools→ConfigureExternalTool.Doubleclickontheprogramandadda
newone.
Name:Explorer
Location:C:¥Windows¥explorer.exe
Workingdirectory:${workspace_loc}
Arguments:/select,${resource_loc}
Uncheck"Buildbeforelaunch"onthe"Build"tabanduncheck"Assigntoconsole"onstandardinput/
outputof"Common"tab.



WhenyouclicktheExternalExecutionbutton,Explorerwillbedisplayed.




2-4.Downloadfirmwritingsoftware
  DownloadthewritersoftwareST-LinkUtilityforwritingtotheSTM32microcontoller.Ifyouhave
notcreatedanSTMaccount,pleasecreateitbeforedownloading.
URL   />







2-5.Installfirmwritingsoftware
  RuntheinstallationexecutableofST-LinkUtilitywithadministratorprivilegesandinstallit.Onthe
way,theST-Linkdriverinstallationscreenwillappear.Click"Install"toinstalltheST-Linkdriver.



2-6.DownloadCubeMX
CubeMXissoftware(boardsupportpackage,BSP)thatautomaticallygeneratestheminimum
necessarycodeforthemicrocontoller.Click"GetSoftware"fromtheURLbelowtodownloadthe
software.

URL
/>


2-7.installCubeMX
  Runtheinstallationexecutablefilewithadministratorprivilegesandinstallit.



2-8.InstallCubeMXPackage
  InordertoautomaticallygeneratethecodewithCubeMX,itisnecessarytohaveapackageofthe
correspondingSTmicrocontollerseries.LaunchCubeMXandclick"Help"→"InstallNewlibraries".

  PackagesavailableforeachseriesofSTmicrocontolleraredisplayed.Althougholderversionsof
packagesarealsoavailable,checkthelatestversionofthepackageandclick"InstallNow",especially
fornoreason.
BecausetheboardtobeusedatthistimeisSTM32F4andSTM32F3,checkthelatestversionofeach
andclick"InstallNow".






  Checktherequiredpackagesandclick"InstallNow"toautomaticallyinstallthepackagesfromthe
Internet.
However,ifthereisnonetworkenvironmentorthenetworkisnotstable,itispossibletoaddthe
packageoffline.DownloadthepackageofSTM32F3andSTM32F4from"Obtainingsoftware"atthe
followingURL.
  URL   />
/>

  LaunchCubeMX,click"Help"→"InstallNewlibraries",click"FromLocal",selectthedownloaded
zipfile,andofflinepackageinstallationstarts.




2-9.InformationCubeMXPackage
IfyouaddCubeMXpackage,youcanuseCubeMXtogeneratecodeautomatically,youcanalsouse
relatedlibrariessuchassamplecode,FATlibrary,USBlibrary,FreeRTOSandsoon.
TheCubeMXlibraryisinstalledbydefaultinthefollowingdirectory.Pleaserefertothesamplecode
etc.byallmeans.


C:¥Users¥(username)¥STM32Cube¥Repository




3.AboutSTM32Microcontroller
3-1.STM32MicrocontrollerSelection
AlthoughtheSTsellingtheSTM32microcontolleralsosellsother8-bitmicrocontollers,wewill
explainabouttheSTM32microcontollerbecausethemainstayisSTM32whichisanARM-based32bitmicrocontoller.
STM32isaprocessorforbuilt-incalledCortexMamongARMprocessors,andtheseriesdiffersfrom
CortexAusedforsmartphonesandothers.CortexAisanARMprocessorthatexceeds1GHzbecause
itisusedwithOSandapplications.Meanwhile,CortexMisembeddedinappliancesandautomotive
equipment,soit'slowcostandlowpowerconsumption.
AmongtheCortexMseries,itisfurtherdividedintoM0,M3,M4,M7,H7,butinSTMitisdivided
intothreetypesofSTM32Fseries,STM32Lseries,andSTM32Hseriesaccordingtotheapplication.
TheSTM32Fseriesisforgeneraluse,theSTM32Lseriesforlowpowerconsumptionapplications,and
theSTM32Hseriesforhighperformancehighenduse.
Inaddition,sincethecodeusingtheHALlibrarydescribedthistimeisveryportable,itispossibleto
usealmostthesamefunctionindifferentserieseventhoughitisveryportable.Therefore,itisalso
possibletousedifferentseriesdependingontheapplication.



3-2.STMicrocontrollerIntroduction
  NucleoboardisrecommendedtostartSTM32microcontoller.Inthisdocument,weexplainusing
NucleoboardusingSTM32F411ofSTM32F4andSTM32F303ofSTM32F3amongSTM32F
series,whichisinexpensiveandeasytoobtainattheInternetandelectronicpartsstores.



3-3.AfterGettingNucleoBoard
  First,checktheversionoffirmwareonST-LinkwithST-LinkUtility,andmakesuretoupdateif
versionisold.TheinitialLEDprogramalsodoesnotworkproperlywhehthefirmwareversionofSTLinkisold.Itmovedsmoothlyifitwasthelatestfarm.
ConnecttheNucleoboardandthePCwiththeUSBcableandstarttheST-LinkUtility.Select
"Firmwareupdate"from"ST-Link"onthemenubar.





  Click"DeviceConnect",andifthefirmwareversionofST-Linkisold,click"Yes>>>>"andupdate
thefirmware.Afterupdating,youcanrecognizeitasST-LinkagainbyconnectingtheUSBcableagain.































4.LightingLED
4-1.AutoCodeGenerationwithCubeMX
Writingamicrocontollerportandperipheralinitializationcodefrom0makesitverypainful.CubeMX
isatooltoautomateit.Ifyouusethis,thedevelopmentisveryeasy.Sincecodesuchasinitialsettingis
generatedautomatically,itispossibletodrasticallyreducethetroubleofwritingmistakesandsetting
codes.

4-1-1.BoardSelection
Click"NewProject"todisplaythemicrocontollerselectionscreen.

SinceweareusingtheSTM32F411Nucleoboardthistime,clickonthe"BoardSelector"tababove
andselecttheSTM32F411Nucleoboard.Thetabof"MCUSelector"isusedforincorporatinga
microcontollerasastandaloneboardintoaself-madeboardoranembeddedboardwithoutusingthe
Nucleoboard.EvenifyouselectthemicrocontollerontheNucleoboard,itisalmostthesame,butin
thecaseoftheNucleoboard,itisbettertoselect"BoardSelector"becausetheLEDsontheNucleo
boardandperipheralcircuitsaredefinedfromthebeginning.

WhenselectingtheSTM32F411NucleoboardTypeofBoard"Nucleo64",MCUSeries"STM32F4"
Whenselected,theboardisnarroweddownanddisplayed.Forthistime,selectthesecond"NUCLEOF411RE"fromthetopandpress"OK".

4-1-2.SettingofCubeMX
  GreenLEDisalreadydefinedonthePA5pinofthemiddlemicrocontoller.Therefore,inthecaseof
LEDlighting,thatisall.
Click"ProjectSettings"andsettheprojectnameandprojectsettingsfordevelopmentinthe



×