Programming raspberry pi 3 upskill learning

216 15 0
  • Loading ...
1/216 trang
Tải xuống

Thông tin tài liệu

Ngày đăng: 23/11/2016, 15:17

In the current world embedded systems play a vital role in daytoday human life. The world of Electronics has evolved from manual control to semi automatic and now we have complete smart automations.So what will be the next evolutionary step?Today, we have complete automated systems that once programmed can work on their own. Still there are few aspects in these systems that cannot be completely automated. Here, the major deciding factors are human judgment and desire.Let’s see an example; consider a system to control your room temperature it can be designed to maintain certain temperature but that certain temperature needs to be set by user. It won’t be able to start itself prior you enter your room. You first need to enter the room and then set the temperature.So the next step in evolution is IOT. It would allow you to control your room temperature from any place you are. You can setup your air conditioner when you are 15 minutes away from your home. So that by the time you reach home your room temperature will be already set at a degree you prefer. ProgrammingTheRaspberryPi3:GettingStartedWithPython —byUpSkillLearning Copyright: Copyright © 2016 by UpSkill Learning All rights reserved No part of this publication may be reproduced, distributed, or transmitted in any form or by any means, including photocopying, recording, or other electronic or mechanical methods, without the prior written permission of the publisher, except in the case of brief quotations embodied in criticalreviewsandcertainothernon-commercialusespermittedbycopyrightlaw Dedication: Dedicatedtotheoneswholookattheworldfromadifferentperspective,theoneswhoare restless,theoneswhostriveforchange,theoneswhoseethingsdifferently,theoneswho don’tacceptthestatusquo,theoneswhochallengecurrentthinkingpatterns,theoneswho break down existing barriers, the ones who make the impossible possible, the ones who buildnewthings… TableOfContents Introduction-EmbeddedSystems&TheRaspberryPi MovingTowardASmarterInternet–TheInternetOfThings UnderstandingTheRaspberryPi Versions&Features UnderstandingTheRaspberryPi3 TheRaspberryPi3–HardwareSetup OperatingSystemsRequiredForRaspberryPi3 NOOBSforRaspberryPi3 ConnectingTheRaspberryPi3 StartingAndProgrammingRaspberryPi3 GeneralPurposeInputOutput(GPIO) UnderstandingAndAccessingPython3 LearnPythonInDetail Python–Features SettingUpTheEnvironment Identifiers Variables Whitespaces Comments Strings TypesOfOperations DataTypes FlowOfControl/DecisionMaking LoopsInPython Functions Modules FileHandling ExceptionHandling ClassesInPython TipsForPythonBeginners UnderstandingAndAccessingMathematica ProgrammingInMathematica AccessingCameraInRaspberryPi3 RaspberryPi3–GettingAheadWithIOT Conclusion-SculptingYourCareerInIOT Introduction EmbeddedSystems&TheRaspberryPi In the current world embedded systems play a vital role in day-to-day human life The worldofElectronicshasevolvedfrommanualcontroltosemiautomaticandnowwehave completesmartautomations Sowhatwillbethenextevolutionarystep? Today, we have complete automated systems that once programmed can work on their own Still there are few aspects in these systems that cannot be completely automated Here,themajordecidingfactorsarehumanjudgmentanddesire Let’s see an example; consider a system to control your room temperature - it can be designed to maintain certain temperature but that certain temperature needs to be set by user Itwon’tbeabletostartitselfprioryouenteryourroom Youfirstneedtoenterthe roomandthensetthetemperature SothenextstepinevolutionisIOT Itwouldallowyoutocontrolyourroomtemperature fromanyplaceyouare Youcansetupyourairconditionerwhenyouare15minutesaway from your home So that by the time you reach home your room temperature will be alreadysetatadegreeyouprefer There are many constraints come into picture while designing such advanced level of system Thesystemsyoudesignneedtorespondtominutechangesi.e itshouldbehighly responsive Also the Speed of operation is a must; we, humans prefer our system to be veryfast Thesystemshouldnottakealotoftimeinprocessingthegivenrequest Also thesystemshouldbecompact Bulkysystemsaredifficulttofitinwhereassmallonesare alwaysappreciatedastheycanbeadjustedinanycornerandgiveusfreedomtochooseits place Power is one of the most critical considerations these days If our system is battery operated then power will be the highest priority in design considerations So we need systemsthatconsumeverylowpower Aswe’veseeninthepreviousexample,tocontrolsystemremotelyweneedConnectivity ConnectivityisnothingbuttheabilityofasystemtoconnecttootherdevicesandInternet This can be achieved by Ethernet port on Pi and full network stack We also need to considerotherperipheralslikeADC,DAC,memoryandGPIO Thisinformationissimplyaboutautomationbutembeddedsystemshaveinfluenceover allaspectsofourlifefromT.V toCars,fromradiotowertosatellite-nearlyallourdayto day life is connected with embedded systems With these vast application comes variability Isitpossibletoclassifyallthesesystemsunderonlyoneembeddedsystem?Nowecan’t that But we can classify according to use, size and application and many more parameters Henceembeddedsystemshavebeendividedintomanysubsystems Sorememberthat,Firstweneedtoclassifyourapplicationunderrightembeddedsystem andthendecideonitsdevelopmentanddesignprocess Theabovediagramshowsasmallpossibledivisionofembeddedsystemsbutthiscanbe furtherclassifiedinmanymorewayslikeappliancesystems,automobileembeddedetc Todevelopanyprojectitsfuturedevelopmentmustalsobekeptinmindalongwith presentrequirements Todevelopsystemsmanydevelopmentboardsareavailablein market,FewexamplesareArduino,RaspberryPietc WhatisaRaspberryPi? ARaspberryPiisacredit-cardsizedcomputeroriginallydesignedforeducation,inspired bythe1981BBCMicro CreatorEbenUpton’sgoalwastocreatealow-costdevicethat wouldimproveprogrammingskillsandhardwareunderstandingatthepre-university level Butthankstoitssmallsizeandaccessibleprice,itwasquicklyadoptedbytinkerers, makers,andelectronicsenthusiastsforprojectsthatrequiremorethanabasic *Ifit’snotenabled,enableitandrebootyourPitobegin Nowyourcameraisconnectedandthesoftwareisenabled,youcangetstartedbytrying outthecamerapreview OpenPython3fromthemainmenu: *RefertoPythonchapterregardingtheuseofPython Openanewfileandsaveitascamera.py It’simportantthatyoudonotsaveitas picamera.py Enterthefollowingcode: frompicameraimportPiCamera fromtimeimportsleep camera=PiCamera() camera.start_preview() sleep(10) camera.stop_preview() SavewithCtrl+SandrunwithF5 Thecamerapreviewshouldbeshownfor10seconds, andthenclose Movethecameraaroundtopreviewwhatthecamerasees Thelivecamerapreviewshouldfillthescreen Ifyourpreviewwasupside-down,youcanrotateitwiththefollowingcode: camera.rotation=180 camera.start_preview() sleep(10) camera.stop_preview() Youcanrotatetheimageby90,180,or270degrees,oryoucansetitto0toreset Youcanalterthetransparencyofthecamerapreviewbysettinganalphalevel: frompicameraimportPiCamera fromtimeimportsleep camera=PiCamera() camera.start_preview(alpha=200) sleep(10) camera.stop_preview() alphacanbeanyvaluebetween0and255 Thenextimportanttaskforanycameraisstillimage Amendyourcodetoreducethe sleepandaddacamera.capture()line: camera.start_preview() sleep(5) camera.capture(‘/home/pi/Desktop/image.jpg’) camera.stop_preview() It’simportanttosleepforatleast2secondsbeforecapturing,togivethesensortimetoset itslightlevels Runthecodeandyou’llseethecamerapreviewopenfor5secondsbeforecapturingastill picture You’llseethepreviewadjusttoadifferentresolutionmomentarilyasthepicture istaken You’llseeyourphotoontheDesktop Double-clickthefileicontoopenit: Nowyou’veusedthecameratotakestillpictures,youcanmoveontorecordingvideo Amendyourcodetoreplacecapture()withstart_recording()andstop_recording(): camera.start_preview() camera.start_recording(‘/home/pi/video.h264’) sleep(10) camera.stop_recording() camera.stop_preview() Runthecode;itwillrecord10secondsofvideoandthenclosethepreview Toplaythevideo,you’llneedtoopenaterminalwindowbyclickingtheblackmonitor iconinthetaskbar: TypethefollowingcommandandpressEntertoplaythevideo: omxplayervideo.h264 UsingMathematicatocaptureimage: YoucantakepictureswiththecamerausingtheDeviceReadfunction Totakeastillpicturewiththecamera,typethefollowingcommand: img=DeviceRead[“RaspiCam”] Thentosavetheimageasafile,useExportandsupplythesavepathandthevariable containingtheimage: Export[“/home/pi/img.jpg”,img] RaspberryPi3–GettingAheadWithIOT During the past several years, in the area of wireless telecommunications a novel paradigmnamed“theInternetofThings”(IOT),whichwasfirstusedbyKevinAshtonin apresentationin1998,hasgainedmoreandmoreattentioninacademiaandindustry Byembeddingshort-rangemobiletransceiversintoawidearrayofadditionalgadgetsand everyday items, enabling new forms of communication between people and things, and betweenthingsthemselves,IOTwouldaddanewdimensiontotheworldofinformation andcommunication IOT would radically transform our corporations, communities, and personal spheres In the20thTyrrhenianWorkshoponDigitalCommunications,thebasicideaofIOThasbeen summarized as the pervasive presence around us of a variety of “things” or “objects”, suchlikeRadioFrequencyIDentification(RFID)tags,sensors,actuators,mobilephones, which, through unique addressing schemes, are able to interact with each other and cooperatewiththeirneighbouring“smart”componentstoreachcommongoals TheInternetofThings(IOT)hascapturedthemarketrecently IstheRaspberryPitherightchoicetousefordevelopingIOTprojects?Ifyes,wherewill itfitinthesystem?Toanswerthisquestion,let’sconsiderabasicblockdiagramofIOT Therecomesapartofhardwarethatcomesintopicturewhenthingsaretobeconnected with local network Raspberry Pi is complete OS based hardware and thus can host gateways for many of our applications With hardware feature like GPIO which can directlybecontrolledthrougheasyprogrammingitcanactasanend-device What does this intermediate level between local network and Things mean These days, with the humungous day-to-day development with IOT, new communication protocols havebeendeveloped The reason behind developing new protocols is to reduce overhead of messages and increase reliability Along with these factors they also needed to manage compatibility withbothend-deviceandnetwork Herethebridgescameintopicturethatconvertedone request format to other request format, e.g HTTP request to CoAP request Few of the newcommunicationprotocolsareCoAPandMQTT Let’sforaninstanceconsiderCoAP i.e constraintapplicationprotocol This is a very light weight protocol meaning it’s header is only bytes whereas that of HTTPis32 SothisismostsuitableforM2MdevicesusedinIOT Thiswillreducedata requirement It will also save a lot of bandwidth But it has some usage limitations To convertfromCoAPtoHTTPandviceversaweneedabridge Thisbridgecanbedesigned overRaspberryPithusimprovingcommunicationbetweendevicesandInternet TheaboveimagedescribesthegatewayorbridgingarchitectureofIOT Conclusion-SculptingYourCareerInIOT InternetofThings(IoT)isanewcomputingconceptwhereeachandeveryphysical object,aliveanddead,hasuniqueidentifierandconnectedwitheachotherwithoutany humanintervention,turningphysicalworldinahugeinformationsystem ThetermInternetofThingswasfirstcoinedbyKevinAstonin1999inapresentationto ProctorandGamble, “Ifwehadcomputersthatkneweverythingtherewastoknowaboutthings-usingdata theygatheredwithoutanyhelpfromus-wewouldbeabletotrackandcounteverything, andgreatlyreducewaste,lossandcost Wewouldknowwhenthingsneededreplacing, repairingorrecalling,andwhethertheywerefreshorpasttheirbest Weneedtoempowercomputerswiththeirownmeansofgatheringinformation,sothey cansee,hearandsmelltheworldforthemselves,inallitsrandomglory.” Incomputingworldnearly50Petabytesofdatasofargeneratedisthroughhuman intervention Withlatestdevelopmentintechnology,convergencesofwirelesstechnology andubiquitousandcheaplyavailablesensorshavemadethingssmartintermsofdata generation,processinganddataexchange It’snotfarawaythateveryobjectwillbeconnectedtointernet Gartnerestimatesthatby 2020internetconnecteddevicesnumberwouldbe26billion,excludingdesktops,tablets andsmartphones Andrevenuegeneratedbythemwouldbeexceeding$300billion Fore.g todayincardrivergetsallkindsofindicatorslikefuellevel,tirepressure,oil leveletc…directlyondashboardpanel Itmeanscaritselftellsdriverwhenitrequires servicingandaccordinglydrivercantakeaction Infactinfutureitmightsendautomated emailtoauthorizedservicestationdetailingallreportssothatwithoutanymanualcallcar canbeserviced Onestepaheaddriverlesscarisanotherexamplewhereoncedestination isfed,itcalculatesrouteforyouconsideringmeetingschedulefromyourcalendar,traffic condition,tollrouteetc…Smartrefrigeratorsletyouwritegrocerylistonscreenandsyncs itwithyourphone ThesearethefewexamplestoshowhowIOTisrevolutionizingthe worldincomingyears HowdoYOUbecomeanexpertonIoT-InternetofThings? Asyou’velearntinthisbook,“Buildathing Connectittotheinternet Dosomething interestingwithit Repeat.” Youmaybeabletoacceleratetheprocessbyreadingaboutthingsthathavebeen connectedtotheinternet,butthere’snosubstitutefordoingityourself,especiallynow thatalloftheequipmenttogetstarted(sensors,controllers,radios)isatleastanorderof magnitudecheaperthanitoncewas TheInternetOfThingsWantsYou! Thankstohigh-speedserviceproviders,ubiquitousWiFiandrainbowsofsensors,our worldisawashinInternet-connectedtechnologies Thisalways-onInternetissometimesa convenienceandoftenahassle,butit’salwaysagatewaytomyriadopportunities Those opportunitiesincreaseexponentiallyastheInternetofThingscontinuestoevolve ThepossibilitiesoftheIoTarenearlylimitless IoThascreatednewsectorsintheworld economyandlotofnewjobs Excitingopportunitiesawaitgraduatesintheworldofmass interconnectivity Companiesmakingconnectedthingswillhavetothinknotjustabouthowthedevice worksbuttheentiresystemonwhichitwillrun,sotherewillalsobegreatscopefor networkexperts Bandwidthwillneedtobeincreasedanddatatransferlatencytothecloudwouldhaveto bereduced Therewillbeagreatercallforsecurityanalystsastherobustnessofdevices connectedtotheinternetwillinevitablybequestioned “TheInternetofThingswillneedabroadrangeofengineeringandsoftwareskillsand whenyouwidenthingsout,you’relookingforpeopletowriteappsinthecloudandothers tocomeupwithnewservices,databasesanduser-interfaces,” 10NewJobsCreatedByTheInternetOfThings: AgriculturalTechnologist:Moderncropmanagementinvolveshandlingspecialized datatomaximizeoutput 3-DPrintingEngineer:As3-Dprintingbecomesmoreandmoreubiquitous, engineerswhocanworkwiththetechnologywillbeingreaterandgreaterdemand GridModernizationEngineers:Techniciansmonitoringelectricityconsumptionon apowergridinFrance WearableTechDesigner:Smartwatchesarejustthetipoftheicebergwhenit comestowearabletech MedicalRobotDesigner:Speciallydevelopedrobots,beingcheckedbya technicianforhelpingsurgeonsperformbrainprocedures DataSecurityExpert:Moreconnectivitythroughoutourlivesmeansmore opportunitiesforhackers CloudComputingSpecialist:Workingwithcloudstorageandimplementing seamlessintegrationwithon-siteresourcesisallpartofacloudcomputing specialist’swork IntermodalTransportDesigners:Freightcontainershavebeenusedfordecadesto transportgoods,butnowthey’reconnectedtosophisticatedtrackingsystems CounterHackers:Jobopportunitiesforcounterhackersaren’tlikelytodryup anytimesoon TheTimeIsNow: RightNow,ThereisHUGEskillshortageinIOTandthisisYOURCHANCEtostart learningmoreaboutIOTandgetaheadinyourCareer&Life ********* DearReader,ifyoulikedwhatyouread,pleaseleaveanhonestreviewinAmazon ******** ******* Ifyouwanttotellusaboutthequalityorimprovementareasinthisbook,please writetoupskillpublishing@gmail.com Wereadallyourcomments,feedbackandinputsandensuretomakereadingthis bookapleasantexperiencebyconstantlyupdatingit ThisguideisdevelopedtohelpyoutogetstartedwithRaspberryPi3& ProgrammingPython Ifweservedthispurpose,weconsideritasuccess ******** [...]... Small fluctuations in power output may make Raspberry Pi misbehave Bad qualitypowersupplymayevendamageyour Raspberry Pi Ethernetcable* Togive raspberry Pi internetconnectivityyoumustconnectEthernetcableinRJ45 jack Lastbutthemostimportantpartis Raspberry Pi 3 .!!! OperatingSystemsRequiredFor Raspberry Pi 3 Raspberry Pi 3 isaminicomputer Andweallknowthatcomputersneedoperatingsystem... 40GPIO FullHDMIport EthernetPort Camerainterface Displayinterface MicroSDcardslot VideoCoreIV25graphicscore UnderstandingThe Raspberry Pi 3 InFebruary2016 Raspberry Pi 3 replacedallthepreviousmodelsof Raspberry Pi Ithas thefeaturesof: A1.2GHz64bitquadcoreARMv8CPU 802.11nWirelessLAN Bluetooth4.1 BluetoothLowEnergy(BLE) Theaboveimageis Raspberry Pi 3 B Like Raspberry Pi 2ithas:... developmentofselfdesignedboards Logoof Raspberry Pi One such board is Raspberry Pi Raspberry Pi boards are credit card sized single board computersdevelopedby Raspberry Pi FoundationinUnitedKingdom Raspberry Pi was launchedwithintentiontoencourageteachingcomputerbasicsinschoolsanddeveloping countries Manyversionsof raspberry Pi areavailableinthemarketformorethan4yearsandhave... Theaboveimageis Raspberry Pi 3 B Like Raspberry Pi 2ithas: 4USBport 40GPIO FullHDMIport EthernetPort Camerainterface Displayinterface MicroSDcardslot VideoCoreIV25graphicscore The Raspberry Pi 3 –HardwareSetup Raspberry Pi 3 providesbestplatformtodevelopanyembeddedsystem Duetoitsvast featuresitcanbeusedforanyproject Butbeforewegetstartedwith Raspberry Pi 3, we needtoconfigureandgetafewthingsready... generation Pi 1 was released in February20 13 ThisversionwaslaunchedwithtwomodelsAandB ButayearlaterA+ andB+modelswerelaunched LateroninFebruaryof2015 Raspberry Pi 2waslaunchedandayearlateri.e February 2016 Raspberry pi 3 waslaunched Pi zero which was almost half the size of Pi 2 was launched in November 2015 with smallerfootprintandlessGPIO Graphicimageof Pi zero... preloadedPython,Scratch,Sonic Pi, Java,Mathematicaandmanyothers RaspbianisbasedonDebianJessie It’safreeoperatingsystemoptimizedfor Raspberry Pi hardware Itisasetofutilitiesthatmakeyour Pi work Raspberry comeswith 35 ,000packages,pre-compiledsoftwarebundledinaformateasy toinstallon Pi HencewewillgowithRaspbian NOOBSfor Raspberry Pi 3 To download OS recommended way is to use NOOBS NOOBS stands for New Out of BoxSoftware... WithoutOStheycannotoperateatall Raspberry Pi doesrequireOS Therearea varietyofOSthatcanbeloadedin Raspberry Pi TheaboveimageshowsthevarietyofOSthatcaninstalledon Raspberry Pi theycomprise of UBUNTU SNAPPY WINDOWS10IOTCORE OSMC LIBREELEC PINET RISCOS WEATHERSTATION But RASPBIAN is the foundations official supported Operating system It comes with preloadedPython,Scratch,Sonic Pi, Java,Mathematicaandmanyothers... Thelowerspecificationversionof Raspberry Pi istheModuleA Ithas256MBofRAM, asingleUSBportbutnoportforEthernet ModelBisavariantwithhigherspecificationof Raspberry Pi 1 Ithas512MBofRAM, twoUSBPortsandadditional100mbEthernetport LateroninNovember2014,abitmoreadvanceversionof Raspberry Pi 1modelAwas launchedasModelA+ ThisversioncomparedtoModelAhad14moreGPIOpinsheader... over-current behaviour It has all the features from Model A+ i.e 40 GPIO,bettersocketforSDcard,lowerpowerconsumptionandbetteraudio Raspberry Pi 2 B replaced the Raspberry Pi 1 Model B+ completely Because of its advancedfeaturesandcompletebackwardcompatibility,it’seasilyadaptedinelectronics market Raspberry Pi 2Bhasthefollowingmajorfeatures: A900MHzquadcoreARMcortexA-7CPU... 3. )Wanttolearnabouthardware+softwareintegration?Noproblem,youcangetan Arduinosetupwitha Pi aswell 4.)Itscheap!Yes,youdoneedonlyamonitorandkeyboardforinitialsetup Weonlyhavegreatthingstosayaboutthe Raspberry Pi TogetstartedwithyourIOT journey,buya Raspberry Pi andreadthisbooktounderstandmoreabout Raspberry Pi MovingTowardASmarterInternet–TheInternetOfThings Imagine you
- Xem thêm -

Xem thêm: Programming raspberry pi 3 upskill learning, Programming raspberry pi 3 upskill learning, Programming raspberry pi 3 upskill learning

Gợi ý tài liệu liên quan cho bạn

Nạp tiền Tải lên
Đăng ký
Đăng nhập