beginning arduino ov7670 camera developmentpdf.ebook777.com/039/b010y37xqg.pdf · the ov7670 camera...

203

Upload: ngohanh

Post on 26-Jul-2018

485 views

Category:

Documents


70 download

TRANSCRIPT

Page 1: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without
Page 2: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

i

BeginningArduinoov7670CameraDevelopmentRobertChin

Copyright©2015RobertChinAllrightsreserved.iiCopyright©2015RobertChinAllrightsreserved.iii

Page 3: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

TableofContents

AbouttheAuthor…………………………………………………………………………..ivIntroduction…………………………………………………………………………………vChapter1:IntroducingtheOmnivisionOV7670Camera………………………………1Chapter2:IntroducingtheArduino……………………………………………………..19Chapter3:ArduinoProgrammingLanguageBasics………………………………….39Chapter4:DigitalDesignReview……………………………………………………….53Chapter5:TakingPhotoswiththeOmnivisionov7670Camera–Part1…………..77Chapter6:TakingPhotoswiththeOmnivisionov7670Camera–Part2…………185AppendixA:CameraRegisterDefines………………………………………………..225AppendixB:ImageCaptureProgramVariables……………………………………..238iv

Page 4: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

AbouttheAuthor:

RobertChinhasaBachelorofSciencedegreeincomputerengineeringandisexperiencedinArduinocameradevelopment,C/C++,UnrealScript,Java,DirectX,OpenGL,andOpenGLES2.0.Hehaswritten3dgamesfortheWindows,andAndroidplatforms.Heistheauthorof“BeginningAndroid3dGameDevelopment”,and“BeginningIOS3dUnrealGamesDevelopment”bothpublishedbyApressandwasthetechnicalreviewerfor“UDKGameDevelopment”publishedbyCourseTechnologyCENGAGELearning.

v

Page 5: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

Introduction

ThisbookismeanttobeaquickstartguidetousingtheOmnivisionov7670digitalcamera.Ishowyouinadetailedstepbystephandsonexamplehowtotakephotoswiththeov7670camerausinganArduinoMega2560andhowtouseaSDcardreader/writertosavetheseimagestoanSDcard.Then,Ishowyouhowtotransfertheseimagestoyourcomputerandconvertthemtoacommonimageformatthatiseasilyviewable.ThisbookwouldalsobebeneficialtothosethatwanttodevelopArduinoprogramsforcamerasotherthantheov7670sincemuchoftheinformationpresentedherecanalsobeappliedtootherdigitalcameras.

Note:Chapter6:TakingPhotoswiththeOmnivisionov7670Camera–Part2isthechapteryouwanttoreadifyouwanttoquicklyputtogetheraworkingcamerasystem.Asummaryofthecontentofthebook’schaptersfollows.Chapter1:“IntroducingtheOmnivisionOV7670Camera”–InthischapterIdiscussindetailtheov7670cameraintermsofitsfeatures,operation,andstepsneededinordertotakeaphoto.

Chapter2:“IntroducingtheArduino”–HereIstartbygivingsomebackgroundinformationabouttheArduino.IthengiveanindepthdiscussionoftheArduinoMega2560board,andthenIguidethereaderthroughahandsonexamplewhereIshowyouhowtosetupyourArduinoandhowtogetasimpleprogramthatcontrolstheblinkingofalightworking.

Chapter3:“ArduinoProgrammingLanguageBasics”–InthischapterIdiscussthebasicsoftheArduinoprogramminglanguage.

Chapter4:“DigitalDesignReview”–InthischapterIcoverhowtheov7670worksatachiplevel.Icoverthemaincamerachip,theframebuffermemorychip,andhowthesetwochipsareconnectedtogether.Idiscussthegeneralproceduretocaptureavideoframetothecamera’sframebuffermemoryandhowtoreadtheimagedatafromthecamera’sframebuffermemory.

Chapter5:“TakingPhotoswiththeOmnivisionov7670Camera–Part1”–InthischapterIdiscusstheSDcardreader/writer,theI2Cinterface,andtheArduinoprogramor“sketch”IwrotetocaptureanimagefromthecameraandthentosaveitonaSDcard.Ialsocoverffmpegwhichisusedtoconverttheimagesproducedbythecameraintocommoneasilyviewableimages.

Chapter6:“TakingPhotoswiththeOmnivisionov7670Camera–Part2”–InthischapterIpresentahandsonexamplewhereIshowyoustepbystephowtotakeaphotowiththecameraandsaveittoanSDcardusingtheimagecapturesoftwareIdeveloped.Thischapterexplainseverythingfromtheconnectionsrequired,howtousetheimagecapturesoftware,andhowtoconvertthefinalimagestoaneasilyviewableformat.Thisisthechapteryouwanttoreadifyoujustwanttoquicklyputtogetheraworkingcamerasystem.

AppendixA:“CameraRegisterDefines”–ThisappendixlistsalltheimportantcameraregistersandvaluesAppendixB:“ImageCaptureProgramVariables”–Thisappendixlistsallthevariables

Page 6: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

thatwereusedinmyimagecaptureprogram.

Page 7: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

Chapter1

IntroducingtheOmnivisionOV7670CameraInthischapterIcovertheOmnivisionov7670camera.First,ashortdescriptionofthecameraisgivenfollowedbysomephotosofthecameraitself.Thenkeydigitalcameraterminologyneededtounderstandkeyconceptsinthisbookarecovered.Ithengiveamoreindepthexplanationofthecameraincludingdetailsofeachkeypartandthestepsbywhichanimageiscaptured,processedandtransmittedtotheArduino.

Page 8: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

WhatistheOV7670Camera?

Theov7670cameraisalowcostwidelyavailableCMOScameramadebyOmnivisionTechnologieslocatedinSantaClara,California.ItcomesintwoversionsonewithoutframebuffermemoryandonewithframebuffermemorywhichiscommonlycalledtheFIFOversion.InthisbookwewillusetheversionwiththeFIFOframebuffermemory.Theframebuffermemoryholdsimagedatathathasbeencapturedfromthecamera.TheimagedatacanthenbetransferredfromtheframebuffermemorytotheArduino’smemoryortoastoragedevicesuchasaSDCard.Theov7670cameracanbeusedwiththeArduinothroughitsSCCBinterfacethatiscompatiblewiththeArduino’sI2Cinterface.Thecameracanbefocusedmanuallybyturningthecameralensclockwiseandcounterclockwisewhichmovesthelensoutwardandinward.Thecameralensclockwiseandcounterclockwisewhichmovesthelensoutwardandinward.The1showsaphotoofthebacksideofanov7670camerawithframebuffermemorylabelled“Averlogic”.Figure1-2showsaphotoofthefrontofanov7670camera.Figure1-3showsapicturecapturedfromaov7670camera.

Page 9: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

Figure1-1.ov7670FIFOcameraversionbacksideshowingtheAverlogicframebuffermemory

Page 10: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

Figure1-2.ov7670FIFOcameraversionfrontsideshowingcameralens

Figure1-3.Picturecapturedfromanov7670camera

Page 11: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

KeyCameraTerminology

Thissectioncoverskeytermsrelatedtodigitalcamerasandtraditionalcameras.

•Pixel–Apixelisthesmallestunitthatmakesupadigitalimage.Itisgenerallyasmallsquareilluminatedelementthatcantakeonvariouscolors.Forexample,inFigure1-4youcanseethatthenumber“0”iscomposedofmanypixelsrepresentedinthefigurebyblacksquares.

Figure1-4.Groupofpixelsrepresentingtheimageoftheletter“O”•Resolution–Resolutionreferstothewidthandheightofanimageinpixels.•VGA–VGAreferstoacameraresolutionthatgeneratesimagesthatare640pixelswideand480pixelshigh.•QVGA–QVGAreferstoacameraresolutionthatgeneratesimagesthatare320pixelswideand240pixelshigh.

•QQVGA–QQVGAreferstoacameraresolutionthatgeneratesimagesthatare160pixelswideand120pixelshigh.SeeFigure1-5foracomparisonoftheVGA,QVGA,andQQVGAresolutions.

Page 12: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

Figure1-5.ComparisonofVGA,QVGA,andQQVGAresolutions

•CIF–CIFreferstoacameraresolutionthatgeneratesanimagethatis352pixelswideand288pixelshigh.SeeFigure1-6foracomparisonwiththeVGAmodes.

Figure1-

Page 13: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

6.ComparisonofCIFwithVGA,QVGA,andQQVGAresolutions

•YUV–YUVisanimageencodingmethodandisdiscussedinmoredetaillaterinthisbook.ThepixelsthatmakeupadigitalimagemustberepresentedinternallyinanimageformatandYUVisoneoftheavailableimageformatsusedtorepresentthesepixels.TheYUVformatincorporatesluminanceorbrightnessvaluesandcolorvalues.•YCbCr–YCbCrisanimageencodingmethodandisdiscussedinmoredetaillaterinthisbook.ThepixelsthatmakeupadigitalimagemustberepresentedinternallyinanimageformatandYCbCrisoneoftheavailableimageformatsusedtorepresentthesepixels.IntheYCbCrimageformatapixelincorporatesluminanceorbrightnessvalues,blueintensityvalues,andredintensityvalues.

•RGB–RGBisanimageencodingmethodandisdiscussedinmoredetaillaterinthisbook.ThepixelsthatmakeupadigitalimagemustberepresentedinternallyinanimageformatandRGBisoneoftheavailableimageformatsusedtorepresentthesepixels.IntheRGBimageformateachpixelcontainsared,green,andbluecomponent.Thered,green,andbluecomponentsareaddedtogetafinalcolor.Thered,green,andbluecomponentssetatthehighestsettingadduptowhitelight.Thered,green,andbluecomponentssettothelowestsettingrepresentthecolorblack.SeeFigure1-7.

Figure1-7.RGBimageformat

•RawBayerRGB–RawBayerRGBisanimageformatwhereeachpixelconsistsofrawsensordataofeitherred,green,orbluedependingonthecolorfilteratthatpixellocation.RawBayeristheformatthephotoisinitiallycapturedinbeforefurtherprocessing.RawBayerisdiscussedmoreindepthlaterinthisbook.

•Demosaicing–DemosaicingistheprocessbywhicharawbayerRGBimagecanbetransformedintoafullcolorimage.

•Exposure–Exposureistheamountoflightperunitareaandcanbeincreasedbycapturingaphotooveralongerperiodoftimeordecreasedbycapturingaphotooverashorterperiodoftime.Theendresultisthatthelongertheexposurethebrighterthecapturedimagewillbe.Theshortertheexposurethedarkerthecapturedimagewillbe.

Page 14: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

•AEC–AECstandsforAutomaticExposureControlandmeansthatthecamerawilladjusttheexposuresettingaccordingtocertainparameters.

•AGC–AGCstandsforAutomaticGainControlandcontrolstheluminanceorbrightnessofthephotothatistaken.•WhiteBalancing–WhiteBalancingistheadjustmentofthecolorsinanimagegenerallythecolorsred,green,andblueforcorrectingneutralcolorssuchasgrayorwhitesothattheyappeargreyorwhiteinthephoto.

•AWB–AWBstandsforAutomaticWhiteBalancingwhichmeansthatthecamerawillautomaticallyadjustthecolorsoftheimagesothatneutralcolorssuchasgreyorwhitewillappeargreyorwhiteinthecapturedphoto.

•BLC–BLCstandsforBlackLevelCalibrationwhichadjuststhelevelofblackintheimagewiththeobjectiveofmatchingtrueblack(zerobrightness)intheenvironmenttotrueblackinthecorrespondingcapturedimage.

•ABLC–ABLCstandsforAutomaticBlackLevelCalibrationthatautomaticallyadjuststheblacklevelinthecapturedimageaccordingtocertainparameters.

Page 15: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

OV7670CamerawithAL422BFIFOMemoryOverview

Thissectiongivesanindepthdescriptionoftheov7670camera.First,thegeneralcapabilitiesofthecameraaresummarized.Theneachfunctionalcomponentofthecameraisdescribedindetail.ThisisfollowedbyastepbystepdescriptionofhowanimageiscapturedbythecameraandthentransferredtotheArduino.

GeneralSummaryOfCapabilities

•GoodlowlightoperationbyusingNightMode•Lowoperatingvoltage(3.3Volts)suitableforembeddedportableappssuchasArduinobasedprojects•Maximumframecapturerateof30framespersecondusingVGAresolution•CompatiblewithArduinothoughuseofthecamera’sSCCBinterfacewhichiscompatiblewithArduino’sI2Cinterface•SupportsrawBayerRGB,RGB,YUV,andYCbCrimageformatsasoutput•SupportsVGA,QVGA,QQVGAresolutions

•Automaticimagecontrolfunctionsincluding:AutomaticExposureControl,AutomaticGainControl,AutomaticWhiteBalance,AutomaticBlackLevelCalibration.

•Supportsotherimageprocessingfeaturessuchasedgeenhancement,denoiseoperations,andcolorcorrection.•384K(393,216)bytesframebuffermemorywhichisenoughtoholdaVGAscreencaptureinrawBayerformat.

CameraFunctionalBlockDiagram

ThissectiondiscussestheindividualcomponentsoftheOmnivisionov7670camera.Eachcomponentislabeledwithanalphabetenclosedinacircle.Eachofthesecomponentsisthendiscussedindetail.SeeFigure1-8forthefullcamerafunctionalblockdiagram.

Page 16: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

Figure1-8.OV7670CameraFunctionalBlockDiagram

A.CameraLens

Theov7670hasalensthatcanbeadjustedbyscrewingitinorouttoadjustthefocusoftheimagetobecaptured.Lightfirstcomesthroughthislensbeforehittingthecamera’simagearray.SeeFigure1-9.

Figure1-9.CameraLens

B.ImageArray

Thecamera’simagearraycapturestheincomingimageandis656pixelswideand488pixelshigh.SeeFigure1-10.

Page 17: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

Figure1-10.Camera’sImageArray

Theimagearrayiscoveredwithcolorfiltersarrangedinablue-green/green-redpattern.Thatisonerowwouldcontaincolorfiltersalternatingbetweenblueandgreencoveringthesensorpixelonerowwouldcontaincolorfiltersalternatingbetweenblueandgreencoveringthesensorpixel11.

Figure1-11.BG/GRBayerFilterPattern

Thewaythebayercolorfiltersworkisthatthered,green,andbluefiltersonlyallowintheredgreen,orbluecomponentofthelightreflectedfromtheimageandthisintensitylevelismeasuredbytheimagesensorslocatedonthepixelcellsoftheimagearray.SeeFigure1-12.IncaseAonlytheredlightcomponentismeasuredbythepixelcellsensor.IncaseBonlythegreenlightcomponentismeasuredbytheimagesensor.IncaseConlythebluelightcomponentismeasured.Thus,eachpixelinarawbayerformatimagerepresentstheintensitylevelofeitherred,green,orbluelight.Eachfinalimagepixelmustcontainred,green,andblueinformationforthepixeltobecorrectlydisplayed.Therefore,therawbayerimagemustgothroughaprocesscalleddemosaicingtoestimatethemissingtwocolorcomponentsneededtodisplaythepixelcorrectly.

TheYUVandYCbCrcameraoutputformatsusethecamera’sbuiltindemosaicingalgorithmstogeneratethefinalcorrectimage.Thevaluesofeachpixelinthefinalimagearedeterminedbythelighthittingthatpixeldirectlyaswellasthelighthittingthesurroundingpixels.ThecameracanalsogenerateGRB,RGB555/RGB565formatswhichareconvertedfromYUV/YCbCr.TherawbayerimagescanbedemosaicedusingafreepublicdomainprogramcalledFFMPEG.IdiscussFFMPEGlateroninthisbookaswellastheseimageformats.

Page 18: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

Figure1-12.HowBayerColorFiltersWork

C.AnalogProcessing

Theov7670’sanalogprocessingincludesexposurecontrol,gaincontrol,andblacklevelcalibrationcontrol.Gaincontrolscanbesettomanualorautomatic.Thetermgainreferstotheluminanceorbrightnessoftheimage.Settingthegaintoautomatictellsthecameratocontroltheimage’sbrightnessautomaticallywithoutanyothercontrolinputssuppliedbytheuser.Blacklevelcalibrationcanbesettomanualorautomaticandadjuststheblackcolorinthecapturedimageasclosetotheactualimageaspossible.Theexposurecontrolcanbesettomanualorautomatic.The(AEC)automaticexposurecontrolmethodsusedcanbeaveragebasedorhistogrambased.(AEC)Automaticexposurecontroland(AGC)automaticgaincontrolsharethesamealgorithmsandareusedtogethertoadjusttheoverallluminanceorbrightnessoftheimage.SeeFigure1-13.

Figure1-13.AnalogProcessing

ThestrategyinaveragebasedcontrolofAECandAGCinvolveschangingtheexposureandgainfastifthemeasuredluminanceisoutsidethecontrolzone.Oncetheluminanceiswithinthecontrolzonetheexposureandgainischangedinsmalleramountsuntilthemeasuredluminanceiswithinthestableoperatingregion.Oncewithinthestableoperatingregiontherearenofurtherchangestothecamera’sexposureandgain.SeeFigure1-14.

Page 19: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

Figure1-14.AverageAEC/AGC

Forthehistogrammethodtheexposureandthegainarechangeduntiltheluminancehistogramreachesthedesireddistribution.WediscusstheaveragebasedandhistogrambasedAECandAGCcontrolmethodsmoreindepthlaterinthisbook.

D.CameraRegisters

Theregistersintheov7670cameraarememorycellsthatare1byteor8bitsinlengthandholdvaluesthatareusedtocontrolthecamera’sfunctionssuchasresolution,imageoutputformat,exposure,gain,framerate,etc.IfyouarenewtodigitaldesignIdiscussbytesandbitslaterinthisbooksodon’tworryifyouareunfamiliarwiththeseterms.Youcansetandreadthevaluesoftheseregistersthroughthecamera’sSCCBinterfaceusingtheArduino.SeeFigure1-15.

Figure1-15.CameraRegisters

E.SCCBInterface

Thisinterfaceisusedtoreaddatafromthecamera’sregistersandtowritedatatothecamera’sregisters.TheSCCBinterfaceonthecameraiscompatiblewiththeArduino’sI2CinterfaceandcodeusedtoactivateandusetheI2Cinterfacewillworkwiththecamera’sSCCBinterfacewithoutanymodifications.TherearetwopinswhicharetheclockwhichislabeledtheSIO_CandthedatawhichislabeledSIO_D.TheSIO_CisthesameastheSCLontheI2CinterfaceandtheSIO_DisthesameastheSDAontheI2Cinterface.TheSIO_CisconnectedtotheArduinoUNOthroughanalogpin5andisconnectedtothe

Page 20: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

ArduinoMEGAthroughdigitalpin21.TheSIO_DisconnectedtotheArduinoUNOthroughanalogpin4andconnectedtotheArduinoMEGAthroughdigitalpin20.SeeFigure1-16.

Figure1-16.TheSCCBInterface

F.TestPatternGenerator

Thetestpatterngeneratorisusedtodisplayastandardsetofverticalcoloredbarsthatareusedtodetermineifthecameraisworkingproperly.Notonlyshouldaverticalgroupofcoloredbarsbedisplayedclearlybutthecolorsmustalsobeintherightorder.Wegetintomoredetailregardingthetestpatterngeneratorlaterinthisbook.SeeFigure1-17.

Figure1-17.TheTestPatternGenerator

G.AnalogtoDigitalConverter

Theanalogtodigitalconverterconvertstherawbayerimagefromtheimagearraytoadigitalformatusinga10bitconverter.SeeFigure1-18.

Figure1-18.A/DConverter

H.50/60HzAutoDetect

The50/60Hzautodetectcanautomaticallydetectthefrequencyofartificiallightsuchasflorescentlightusedinanofficeorhome.Thisfeaturecanbeusedwiththecamera’sbandfilterfeaturestoremoveanylightbandingthatmayoccurinanimage.SeeFigure1-19.

Page 21: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

Figure1-19.50/60HzAutoDetect

I.Exposure/GainDetectionandControl

Thiscomponentofthecameraisresponsiblefordetectingandcontrollingtheexposureandgainoftheimagethatisprocessedintheanalogprocessingblock.Itreceivescontrolinformationfromthecamera’sregistersandthensetstheexposureandgainaccordingly.Forautomaticexposureandautomaticgaincontrolthecameraautomaticallycontrolstheexposureandgainbasedontheexposureandgaindetectedintheincomingimage.SeeFigure1-20.

Figure1-20.Exposure/Gaindetectionandcontrol

J.DigitalSignalProcessor(DSP)

Thedigitalprocessoror(DSP)receivesdigitalimagedatafromtheanalogtodigitalconverterandisresponsiblefor:•WhiteBalanceControl•GammaControl•ColorMatrix•SharpnessControl•De-Noise•AutomaticColorSaturationAdjustment•DefectPixelCorrectionSeeFigure1-21.

Page 22: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

Figure1-21.DigitalSignalProcessing(DSP)WhiteBalanceControl

Thewhitebalancecontrolforthecameraallowsforbothmanualandautomaticcontrol.Theobjectiveofwhitebalancecontrolistomakethewhitecolorsintheimagewhiteregardlessoflightcolorandcanbesettonormal(simple)modeoradvancedmode.

Thenormalmodeforautomaticwhitebalancemakestheaveragevaluesofthered,green,andbluecolorsforallthepixelsintheimageequalbychangingthered,green,andbluegains.Itassumesthattheaverageofallthecolorsintheworldisgray.Thenormalorsimplemodedoesnotdependonthecharacteristicsofthecameralensbeingusedtotakethephoto.

Theadvancedmodeforautomaticwhitebalanceusesthecolortemperaturetoadjustthered,green,andbluegains.Theadvancedmodedependsonthecharacteristicsofthespecificlensthatisbeingusedtotakethepicture.

Aseparatepre-gainvalueforthered,green,andbluechannelsisalsosupported.GammaControl

Gammacontrolprovidesgammacorrectiontotheimagewhichcontrolsitsluminanceorbrightness.Theusercansetindividualvaluesthatdefineagammacurvethatisusedtolightenordarkentheimage.

ColorMatrix

Thecolormatrixcanperformcolorcorrectionandcolorconversiononthecamera’simage.ThecolormatrixisusedinconversionfromrawbayerRGBtoYUV/YCbCr.Thematrixitselfis3by3andisactiveinimageformatsYUV/YCbCrandimageformatsderivedfromYUV/YCbCrsuchasRGB565,RGB555,andRGB444.

RawRGBvaluesareconvertedtoCrandCbvaluesbymultiplyingtheRGBvalueofapixelbytheColorMatrix.TheYvalueistakendirectlyfromthecamera’ssensorandisnotaffectedbytheColorMatrix.SeeFigure1-22.

Page 23: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

Figure1-22.YCbCrcolormatrixuse

TheColorMatrixisbuiltfromthevaluesincameraregistersMTX1,MTX2,MTX3,MTX4,MTX5,andMTX6.Allthatisneededistosetthoseregistersandthecamerawillusethenewvaluesinconvertingtheoriginalpictureintothefinalimage.SeeFigure1-23.

Figure1-23.TheColorMatrixvalueThesamematrixisusedforconversionofRGBvaluestoYUV.SeeFigure1-24.

Figure1-24.YUVcolormatrixuseSharpnessorEdgeEnhancementControl

Thesharpnesscontrolcanbeeithersettomanualorautomatic.Thesharpnessfeatureonlyworksonprocessedbayer,YUV/YCbCrimagesorthosethatarederivedfromthem.Therawbayerimagedoesnotcontainanydigitalprocessingincludingsharpnessoredgeenhancementadjustments.IfthesharpnesscontrolissettoautomaticthenthesharpnesswillvaryaccordingtoalimitssuppliedbytheuserinthecameraregistersREG75andREG76.Inautomaticmodethesharpnesschangesinverselywiththegain.Forexample,thehigherthegainthelowerthesharpness.

De-Noise

Thecamerahasabuiltinde-noisefunctionthatcanbesettomanualorautomaticmode.Inautomaticmodethede-noiselevelisproportionaltothegain.Thatisthegreaterthegainthestrongerthede-noiseappliedtotheimage.Thede-noisefunctionwillworkonprocessedbayerRGB,YUV/YCbCroranyderivedformatsuchasRGB555,RGB565,andRGB444.De-noisewillnotworkonrawbayerRGBsincethatformatdoesnotgothroughthedigitalsignalprocessor.

AutomaticColorSaturationAdjustmentThecameraanautomaticallyadjustcolorsaturationbasedongain.Thehigherthegaintheweakerthecolor.DefectPixelCorrectionThecamerahasbuiltinpixelerrorcorrectiontocompensateforbadpixelsontheimagearray.

K.ImageScaler

TheimagescalerreducesthesizeoftheVGAimage(ifdesired)thatisoutputbythe

Page 24: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

camera’sdigitalsignalprocessor.AllotherresolutionsareproducedbyscalingdowntheVGAimage.SeeFigure1-25.

Figure1-25.ImageScaler

L.FIFOFrameBufferMemory

TheFIFOframebuffermemoryismadebyAverLogicandthemodelisAL422B.ItholdstheimagesothatitcanbereadinbytheArduino.Itis384KwhichisenoughtoholdaVGArawbayerRGBimageof1byteperpixelwitharesolutionof640pixelswideby480pixelshigh.SeeFigure1-26.AnimportantitemtobeawareofisthattheFIFOmemorycanonlyhold1byteperpixelatVGAresolution.Ifyouattempttowritemorethan1byteperpixeltotheframebufferatVGAresolutionsuchastryingtousetheYUVimageformatmodewithVGAthentheimageyougetwillbeincorrect.

Page 25: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

Figure1-26.AverLogicAL422BFIFOmemory

M.VideoPort

TheimagefromtheFIFOmemorycanbeoutputthroughthecamera’svideoport.Thevideoportis1byteor8bitsinlength.Thus,wewillneedtoreadtheimagedatafromthecamera’svideois1byteor8bitsinlength.Thus,wewillneedtoreadtheimagedatafromthecamera’svideo27.

Figure1-27.VideoPort

SummaryofStepsNeededforTakingaPhoto

Thissectiongivesageneraloverviewofwhatstepsoccurwhenanimageiscaptured,processedandtransferredtotheArduinousingtheOmnivisionov7670digitalcamera.SeeFigure1-28.

Page 26: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

Figure1-28.Stepsintakingaphoto

Step#0–SettingtheCamera’sRegisters

Apreliminarystepbeforecapturingtheimageistosetthecameraresolution,settheimageoutputformat,andsetotherimageprocessingparametersthattheuserdesires.ThisisdonebytheArduinousingtheov7670camera’sSCCBinterfacetowritetherequiredvaluestothecamera’sregisters.

Step#1–TheCameraLens

Theimagethatistobecapturedbythecameramustfirstgothroughthecamera’slens.Itisherethatthefocuscanbeadjustedbytheuserbyscrewingthelensclockwiseorcounterclockwisetogetaclearimage.

Step#2–TheImageArray

Theimagearrayreceivestheincomingimageafteritgoesthroughthecamera’slens.Herethecamera’spixelcellsensorsdetectthered,green,andbluecomponentsoftheincominglight.Thesepixelcellsensorsarearrangedinarawbayerimageformatofalternatingrowsofbluegreen/green-redpattern.

Step#3–AnalogProcessing

Page 27: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

Next,theimagegoesthroughanalogprocessingwheretheanalogitemsliketheimageexposureandgainareadjustedaccordingtothecamera’sregistervalues.

Step#4–A/DConverter

Next,theanalogimageissentthroughtheanalogtodigitalconverterthatconvertstheimageintoitsdigitalformofbytesconsistingof0’sand1’s.

Step#5–DigitalSignalProcessor

Then,theimageisprocessedbythedigitalsignalprocessorthathandlesthingslikewhitebalance,edgeenhancement,andde-noising.

Step#6–ImageScaler

Next,thedigitallyprocessedimageissenttotheimagescalerwhereitisreducedinsizeaccordingtothevaluesinthecameraregistersthatcontrolthesizeofthefinalimagethatisoutput.RememberthatallimagesarefirstcapturedinVGAresolutionbutcanbescaleddownusingtheimagescaler.

Step#7–FIFO

Then,thefinalscaledimageissenttotheFIFOframebuffermemorywhichholdstheimagesothatitcanbereadandoutputtotheArduino.

Step#8–VideoPort

Next,thevideoportwhichconsistsof8outputpinsrepresenting8bitsor1byteistheactualphysicalpointwherewiresareattachedinordertosendtheimagedataouttothedevicethatwillreceivetheimagedata.

Step#9–Arduino

Finally,thewiresfromthevideoportonthecameraareconnectedtopinsontheArduinodesignatedasinputpins.Fromtheretheimagedataisreadinonebyteatatimeuntiltheentireimageisprocessed.Forexample,theimagecanbesavedtoaSDcardortransmittedviabluetoothtoanAndroiddevicetobedisplayed.

Page 28: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

Summary

InthischapterIcoveredtheOmnivisionov7670camera.Istartedwithadiscussionofkeytermsandconceptsrelatingtodigitalcamerasthatwereessentialinunderstandingtherestofthebook.ThenIwentintoadetaileddiscussionofthecamerainvolvingkeyfunctionsandthenIdiscussedthestepsanimagewentthroughwhenbeingcaptured,processedandthensentfromthecameratotheArduino.

Page 29: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

Chapter2

IntroducingtheArduinoInthischapterIintroduceyoutotheArduino.IfirstgiveabriefexplanationofwhattheArduinois.IthenspecificallyconcentrateontheArduinoMega2560.IdiscussthegeneralfeaturesoftheArduinoMega2560includingthecapabilitiesandkeyfunctionalcomponentsofthedevice.Next,IdiscusstheArduinoIDE(IntegratedDevelopmentEnvironment)softwarethatisneededtodevelopprogramsfortheArduino.IcovereachkeyfunctionoftheArduinoIDEandthenconcludewithahandsonexamplewhereIgivedetailedstepbystepinstructionsonhowtosetuptheArduinofordevelopmentandhowtorunandmodifyanexampleprogramusingtheArduinoIDE.

Page 30: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

WhatisanArduino?

TheArduinoisaopensourcemicrocontrollerthatusestheCandC++languagestocontroldigitalandanalogoutputstodevicesandelectronicscomponentsandtoreadindigitalandanaloginputsfromotherdevicesandelectronicscomponentsforprocessing.Forexample,theArduinocanreadininformationfromasensortoahomesecuritysystemthatwoulddetecttheheatthatahumanbeingemitsandsendsasignaltotheArduinotoindicatethatahumanisinfrontofthesensor.AfterreceivingthisinformationtheArduinocansendcommandstoacamerasuchastheov7670tostarttakingpicturesoftheintruderorintrudersandsavetheseimagestoaSDcardforlaterviewing.TherearemanydifferentArduinomodelsoutthere.However,inordertoperformtheexamplesinthisbookyouwillneedanArduinomodelwithenoughpinstoconnectboththecameraandthesdcardreader/writer.TheofficialArduinologoisshowninFigure2-1.

Figure2-1.OfficialArduinoLogo

Note:TheofficialwebsiteoftheArduinoprojectishttp://www.arduino.cchoweverin2014thereappearstobeasplitbetweenthefoundersoftheArduinoprojectastowhocontrolsthe“Arduino”trademarkname.Anotherwebsitecalledhttp://www.Arduino.orgwascreatedbythecompanyofoneoftheArduinofoundersthatsplitfromthemaingroup.

Page 31: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

TheArduinoMega2560

ThereareawiderangeofArduinomodelsrangingfrommodelsthataresmallandcanactuallybewornbytheusertoArduinomodelswithmanydigitalandanaloginput/outputpins.FortheexamplesinthisbookIrecommendtheArduinoMega2560.TheArudinoMega2560isanopensourcemicrocontrollerthathasenoughdigitalportstoaccommodatetheov7670cameraandasdcardreader/writerwithenoughdigitalandanalogportsforotherdevices,sensors,lights,andanyothergadgetsthatyoumayrequireforyourowncustomcameraprojects.ThereisanofficialArduinoMega2560boardmadebyacompanycalledArduinoSRLformerlySmartProjectsformedbyoneofthefoundersoftheArduino.SeeFigure2-2.

Figure2-2.TheOfficialArduinoMega2560

TherearealsounofficialArduinoMega2560boardsmadebyothercompanies.AgoodwaytotellwhichboardisofficialandwhichisunofficialisbythecolorofacomponentthatislocatedneartheArduino’susbport.ThecomponentonofficialArduinoboardsiscoloredametallicgold.Thecomponentonunofficialboardshasagreencolor.Thewritingonthecomponentalsodiffers.SeeFigure2-3.

Figure2-3Officialvs.Unofficial

Page 32: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

ArduinoBoards

TherearealsoothercompaniesthatmanufactureArduinoMega2560boardssuchasFunduino.SeeFigure2-4.Thename“Funduino”appearswheretheofficialArduino“Logo”wouldhaveappearedifthiswasanofficialArduinoboard.Alsonotethegreencomponentnexttotheusbport.SincetheArduinoschematicsareopensourceandothercompaniescanlegallymanufacturethisboardtherearemanycompetingcompaniesmakingthisboardandtheboardsvaryinqualityandprice.Generally,anunofficialArduinoMega2560isaround$16.00to$25.00andanofficialArduinoMega2560boardisaround$37.00to$65.00.

Figure2-4.UnofficialArduinoMega2560fromFunduino

TheArduinoMega2560Specifications

Microcontroller:ATmega2560OperatingVoltage:5VInputVoltage(recommended):7-12VInputVoltage(limits):6-20VDigitalI/OPins:54(ofwhich15providePWMoutput)AnalogInputPins:16DCCurrentperI/OPin:40mADCCurrentfor3.3VPin:50mAFlashMemory:256KBforstoringcodeofwhich8KBusedbythebootloaderSRAM:8KBEEPROM:4KBClockSpeed:16MHz

ArduinoMega2560Components

ThissectioncoversthefunctionalcomponentsoftheArduinoMega2560.

USBConnectionPort

TheArduinoMega2560hasaUSBconnectorthatisusedtoconnecttheArduinotothemaincomputerdevelopmentsystemviastandardUSBAmaletoBmalecablesoitcanbeprogrammedanddebugged.SeeFigure2-5.

Page 33: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

Figure2-5.USBConnector

9VBatteryConnector

TheArduinoMega2560hasa9voltbatteryconnectorwhereyoucanattacha9voltbatterytopowertheArduino.SeeFigure2-6.

Figure2-6.9voltbatteryconnector

ResetButton

ThereisaresetbuttonontheArduinoMega2560whereyoucanpressthebuttondowntoresettheboard.ThisrestartstheprogramcontainedintheArduino’smemory.SeeFigure

Page 34: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

2-7. Figure2-7.ResetButton

DigitialPulseWidthModulation

TheArduinoMegahasmanydigitalpinscapableofsimulatinganalogoutputthroughtheprocessofpulsewidthmodulation.Forexample,anL.E.D.lightgenerallyhasonlytwomodeswhichison(fullbrightness)oroff(nolightemitted).However,withdigitalpulsewidthmodulationtheL.E.D.lightcanappeartohaveabrightnessinbetweenonandoff.Forinstance,withPWM(PulseWidthModulation)anL.E.D.canstartfromanoffstateandslowlybrightenuntilitisatitshighestbrightnesslevelandthenslowlydimuntilbacktotheoffstate.Idiscusspulsewidthmodulationlaterinthisbook.ThedigitalpinsontheArduinoMega2560thatsupportPWMarepins2throughpin13.ThesePWMcapabledigitalpinsarecircledinFigure2-8.

Page 35: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

Figure2-8.Digitalpulsewidthmodulation

Communication

ThecommunicationsectionoftheArduinoMega2560containspinsforserialcommunicationbetweentheArduinoandanotherdevicesuchasabluetoothadapteroryourpersonalcomputer.TheTx0andtheRx0pinsareconnectedtotheUSBportandserveascommunicationfromyourArduinotoyourcomputerthroughyourUSBcable.TheSerialMonitorthatcanbeusedforsendingdatatotheArduinoandreadingdatafromtheArduinousestheTx0andRx0pins.Thus,youshouldnotconnectanythingtothesepinsifyouwanttousetheSerialMonitortodebugyourArduinoprogramsortoreceiveuserinput.IwilltalkmoreabouttheSerialMonitorlaterinthisbook.Inaddition,theArduinoMega2560hasthreemoresetsofserialcommunicationpinsthatarelabeledTx1/Rx1,Tx2/Rx2,andTx3/Rx3.SeeFigure2-9.

Page 36: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

Figure2-9.SerialCommunication

Theov7670camerawillcommunicatewiththeArduinothoughtheI2Cinterface.TheI2CinterfaceconsistsofanSDApinwhichispin20andisusedfordataandanSCLpinwhichispin21andisusedforclockingordrivingthedeviceordevicesattachedtotheI2Cinterface.TheSDAandSCLpinsarecircledinFigure2-10.

Figure2-10.I2CInterface

DigitalOutput/Input

TheArduinoMega2560hasmanymoredigitaloutput/inputpinsthentheArduinoUnowhichisapopularArduinomodelforbeginnerswithalimitednumberofdigitalandanalogoutput/inputpins.Thecamerawillneedmanydigitalpins.Thesdcardthatwillbeusedtosavethephotoswillalsoneeddigitalpins.Pins22through53aredigitalpinsontheArduinoMega2560.PinsdiscussedearlierthatarecapableofPWM(PulseWidth

Page 37: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

Modulation)arealsocapableofnormaldigitaloutput/input.SeeFigure2-11.

Figure2-11.DigitalOutput/Input

AnalogInput

TheArduinoMega2560has16analoginputpinsthatcanreadinarangeofvaluesinsteadofjustdigitalvaluesof0or1.Theanaloginputpinusesa10bitanalogtodigitalconvertertotransformvoltageinputintherangeof0voltsto5voltsintoanumberintherangebetween0to1023.SeeFigure2-12.

Page 38: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

Figure2-12.AnalogInput

Power

TheArduinoMega2560hasoutputsfor3.3voltsand5volts.OnesectionthatprovidespowerislocatedonthesideoftheArduino.YoucanalsoprovideyourownpowersourcebyconnectingthepositiveterminalofthepowersourcetotheVinpinandthegroundofthepowersourcetotheArduino’sground.MakesurethevoltagebeingsuppliediswithintheArduinoboard’svoltagerange.SeeFigure2-13.

Page 39: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

Figure2-13.3.3voltand5voltPoweroutputsandVinvoltageinputAnotherplaceontheArduinoMega2560thatprovidespowerisonthesideoftheboardnearthedigitaloutputpin22andpin23thatprovide5voltoutputs.SeeFigure2-14.

Figure2-14.5voltpower

Ground

ThegroundconnectionsontheArduinoMega2560areshowncircledinFigure2-15.Wewillexplainmoreabouttheimportanceofgroundconnectionslaterinthisbook.

Page 40: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

Figure2-15.ArduinoMega2560GroundConnections

Page 41: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

ArduinoDevelopmentSystemRequirements

DevelopingprojectsfortheArduinocanbedoneontheWindows,Mac,andLinuxoperatingsystems.ThesoftwareneededtodevelopprogramsthatrunontheArduinocanbedownloadedfromthemainwebsiteat:

http://www.arduino.cc/en/Main/Software

ThefollowingisasummaryofthedifferenttypesofArduinoIDEdistributionsthatareavailablefordownload.Youwillonlyneedtodownloadandinstalloneofthesefiles.Thefileyouchoosewilldependontheoperatingsystemyourcomputerisusing.

Windows

•WindowsInstaller–Thisisa.exefilethatmustberuntoinstalltheArduinoIntegratedDevelopmentEnvironment.

•WindowsZIPfilefornonadmininstall–ThisisazipfilethatmustbeuncompressedinordertoinstalltheArduinoIntegratedDevelopmentEnvironment.7-zipisafreefilecompressionanduncompressionprogramavailableathttp://www.7-zip.org

Mac

•MacOSX10.7Lionornewer–ThisisazipfilethatmustbeuncompressedandinstalledforusersoftheMacoperatingsystem

Linux

•Linux32bits–InstallationfilefortheLinux32bitoperatingsystem.•Linux64bits–InstallationfilefortheLinux64bitoperatingsystem.

TheeasiestandcheapestwaytostartArduinodevelopmentisprobablythroughusingtheWindowsversiononanolderoperatingsystemsuchasWindowsXP.Infact,theexamplesinthisbookwerecreatedbyusingtheWindowsversionoftheArduinoIDErunningonWindowsXP.ThereareinfactmanysellersonEbaywhereyoucanpurchaseausedWindowsXPcomputerforaround$50-$100.SoifyouarestartingfromscratchandarelookingforainexpensivedevelopmentsystemfortheArduinothenconsiderbuyingausedWindowsXPbasedcomputer.TheonlycautionisthatsupportfortheWindowsXPhasendedintheUnitedStatesandsomeotherpartsoftheworld.InChinaWindowsXPmaystillbesupportedwithsoftwareupdatessuchassecuritypatches.

Page 42: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

ArduinoSoftwareIDE

AsofthiswritingthelatestArduinoIDEisversion1.6.3.ThisistheprogramthatisusedtodeveloptheprogramcodethatrunsonandcontrolstheArduino.Forexample,inorderforyoutohavetheArduinocontrolthelightingstateofanL.E.D.(LightEmittingDiode)youwillneedtowriteacomputerprograminC/C++usingtheArduinoIDE.Then,youwillneedtocompilethisprogramintoaformthattheArduinoisabletoexecuteandthentransferthefinalcompiledprogramusingtheArduinoIDE.FromtheretheprogramautomaticallyexecutesandcontrolstheL.E.D.thatisconnectedtotheArduino.

NewversionsoftheIDEarecompileddailyorhourlyandareavailablefordownload.OlderversionsoftheIDEarealsoavailablefordownloadingat:http://www.arduino.cc/en/Main/OldSoftwareReleases

InthissectionwewillgooverthekeyfeaturesoftheArduinoSoftwareIDE.TheIDEyouareusingmaybeslightlydifferentthentheversiondiscussedinthissectionbutthegeneralfunctionswecoverhereshouldstillbethesame.Wewon’tgoindepthintoeverydetailoftheIDEsincethisbookismeantasaquickstartguideandnotareferencemanual.WewillcoverthecriticalfeaturesoftheArduinoIDEthatyouwillneedtogetstartedonthemaincameraprojectinthisbook.SeeFigure2-16.

Figure2-16.TheArduino

Page 43: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

IDEThe“verify”buttoncheckstoseeiftheprogramyouhaveenteredintotheArduinoIDEisvalidandwithouterrors.Theseprogramsarecalled“sketches”.SeeFigure2-17.

Figure2-17.Theverifybutton

The“upload”buttonfirstverifiesthattheprogramintheIDEisavalidC/C++programwithnoerrors,compilestheprogramintoaformtheArduinocanexecute,andthenfinallytransferstheprogramviatheUSBcablethatisconnectedtoyourcomputertoyourArduinoboard.SeeFigure

Figure2-18.Theuploadbutton

The“New”buttoncreatesanewblankfileorsketchinsidetheArduinoIDEwheretheusercancreatehisorherownC/C++programforverification,compilation,andtransferringtotheArduino.SeeFigure2-19.

Figure2-19.Thenewfilebutton

The“open”filebuttonisusedtoopenandloadintheArduinoC/C++programsourcecodefromafileorloadinvarioussamplesourcecodesfromexampleArduinoprojectsthatareincludedwiththeIDE.SeeFigure2-20.

Page 44: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

Figure2-20.TheopenfilebuttonThe“save”buttonsavesthesketchyouarecurrentlyworkingontodisk.Afilesavedialogisbroughtupfirstandthenyouwillabletosavethefileonyourcomputer’sharddrive.SeeFigureFigure2-21.Savebutton

The“serialmonitor”buttonbringsuptheSerialMonitordebugprogramwheretheusercanexaminetheoutputofdebugstatementsfromtheArduinoprogram.TheSerialMonitorcanalsoacceptuserinputthatcanbeprocessedbytheArduinoprogram.WewilldiscusstheSerialMonitorandhowtouseitasadebuggerandinputconsolelaterinthisbook.SeeFigure2-22.

Figure2-22.SerialMonitor

TherearealsootherimportantfeaturesofthemainwindowoftheArduinoIDE.ThetitlebaroftheIDEwindowcontainstheArduinoIDEversionnumber.InFigure2-23theArduinoversionnumberis1.0.5r2.Thesketchnameisdisplayedinthesourcecodetabandis“Blink”whichisoneofthesamplesketchesthatcomewiththeArduinoIDE.ThesourcecodeareawhichisthelargewhiteareawithscrollbarsontherightsideandbottomiswhereyouenteryourC/C++sourcecodethatwillcontrolthebehavioroftheArduino.ThebottomblackareaintheIDEiswherewarninganderrorsaredisplayedfromthecodeverificationprocess.AtthebottomlefthandcorneroftheIDEisanumberthatrepresentsthelinenumberinthesourcecodewheretheuser’scursoriscurrentlylocated.InthelowerrighthandcorneroftheIDEisthecurrentlyselectedArduinomodelandCOMportthattheArduinoisattachedto.

Figure2-23.TheGeneralIDE

Page 45: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

HandsonExample:AsimpleArduino“HelloWorld”programwithanLED

InthishandsonexampleIshowyouhowtosetuptheArduinodevelopmentsystemonyourWindowsbasedPCorMac.IfirstdiscusswhereyoucangetanArduinoboardandUSBcable.ThenIdiscusstheinstallationoftheArduinoIDEandArduinohardwaredevicedrivers.Ithendiscusshowtoloadinthe“Blink”sketchexampleprogram.Next,Itellyouhowtoverifythattheprogramiswithoutsyntaxerrors,howtouploaditontotheArduino,andhowtotelliftheprogramisworking.Finally,IdiscusshowtheBlinkprogramcodeworksandshowyouhowtomodifyit.

GetanArduinoBoardandUSBCable

YoucanpurchaseanofficialArduinoMega2560boardfromadistributorlistedonhttp://www.arduino.cc/en/Main/Buyorhttp://www.Arduino.org.ThefirstwebsiteisstillgenerallyconsideredthemainwebsiteforArduino.However,thesecondwebsiteisrunbythepeopleactuallymakingArduinoboards.ThesplitamongthefoundersoftheArduinomentionedearliercanbeseenhereintermsofwhoisdesignatedasadistributorofan“official”Arduinoboard.

AsecondoptionistobuyanunofficialArduinoMega2560madebyasellernotlistedasan“official”distributorbyeitherarduino.ccorarduino.org.Theseboardsaregenerallyalotcheaperthanan“official”Arduinoboard.However,thequalitymayvarywidelybetweenmanufacturersorevenbetweenproductionrunsbetweenthesamemanufacturer.

IntermsoftheUSBcablethatisusedtoconnecttheArduinotoyourdevelopmentcomputertheofficialArduinoboardgenerallydoesnotcomewithacablebutmanyunofficialboardscomewithshortUSBcables.ArduinocompatibleUSBcablesofalongerlengthsuchas6footor10footcanbeboughtonAmazon.comorEbay.com.Ipurchasedthe“MediabridgeUSB2.0-AMaletoBMaleCable(10Feet)-High-SpeedwithGold-PlatedConnectors–Black”fromAmazon.comformy“unofficial”ArduinoMega2560anditsseemstoworkwell.MakesureyougettherightkindofUSBcablewiththerightconnectorsoneitherend.TherectangularendoftheUSBcablekindofUSBcablewiththerightconnectorsoneitherend.TherectangularendoftheUSBcable24.

Page 46: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

Figure2-24.ArduinoUSBCable

InstalltheArduinoIDE

TheArduinoIDEhasversionsthatcanrunontheWindows,Mac,andLinuxoperatingsystems.TheArduinoIDEcanbedownloadedfrom:http://www.arduino.cc/en/Main/SoftwareIrecommendinstallingtheWindowsexecutableversionifyouhaveawindowsbasedcomputer.Followthedirectionsinthepopwindows.

Note:TheArduinowebsitealsocontainslinkstoinstructionsforinstallingtheArduinoIDEforWindows,Mac,andLinuxonhttp://www.arduino.cc/en/Guide/HomePage.TheinstallationforLinuxdependsontheexactversionofLinuxbeingused.

InstalltheArduinoDrivers

ThenextstepistoconnectyourArduinotoyourcomputerusingtheUSBcable.IfyouareusingWindowsitwilltrytoautomaticallyinstallyournewArduinohardware.Followthedirectionsinthepopupwindowstoinstallthedrivers.DeclinetoconnecttoWindowsUpdatetosearchforthedriver.Select“Installthesoftwareautomatically”asrecommended.IfyouareusingXPignorethepopupwindowwarningaboutthedrivernotpassingwindowslogotestingtoverifyitscompatibilitywithXP.

Ifthisdoesnotworktheninsteadofselecting“Installthesoftwareautomatically”specifyaspecificdriverlocationwhichisthe“drivers/FTDI”directoryunderyourmainArduinoinstallationdirectory.

LoadingintheBlinkArduinoSketchExample

Page 47: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

Next,weneedtoloadtheBlinksketchexampleintotheArduinoIDE.Clickthe“open”buttontobringupthemenu.Under“01.Basics”selectthe“Blink”exampletoloadin.SeeFigure2-25.

Figure2-25.LoadingintheblinkexampleThecodethatisloadedintotheArduinoIDEshouldlooklikethecodeinListing2-1.Listing2-1.BlinkSketch/*BlinkTurnsonanLEDonforonesecond,thenoffforonesecond,repeatedly.Thisexamplecodeisinthepublicdomain.*///Pin13hasanLEDconnectedonmostArduinoboards.//giveitaname:intled=13;//thesetuproutinerunsoncewhenyoupressreset:voidsetup(){//initializethedigitalpinasanoutput.pinMode(led,OUTPUT);}//thelooproutinerunsoverandoveragainforever:voidloop(){digitalWrite(led,HIGH);//turntheLEDon(HIGHisthevoltagelevel)delay(1000);//waitforaseconddigitalWrite(led,LOW);//turntheLEDoffbymakingthevoltageLOWdelay(1000);//waitforasecond}

VerifyingtheBlinkArduinoSketchExample

VerifyingtheBlinkArduinoSketchExample

26.

Page 48: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

Figure2-26.Verifyingtheblinksketch

UploadingtheBlinkArudinoSketchExample

BeforeuploadingthesketchtoyourArduinomakesurethetypeofArduinounderthe“Tools>Board”menuitemiscorrect.Inourcasetheboardtypeshouldbesettobe“ArduinoMega2560orMegaADK”.SeeFigure2-27.

Figure2-27.SetArduinotypetoArduinoMega2560

Next,makesuretheserialportissetcorrectlytotheonethatisbeingusedbyyourArduino.GenerallyCom1,andCom2arereservedandtheserialportthattheArduinowillbeconnectedtoisCom3orhigher.SeeFigure2-28.

Figure2-28.Setthecomport

IfyouareusingaMacthentheSerialPortselectionshouldbesomethinglike“/dev/tty.usbmodem”insteadofaCOMXXvalue.

Page 49: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

Next,withtheArduinoconnectedpressthe“upload”buttontoverify,compile,andthentransfertheBlinkexampleprogramtotheArduino.Aftertheprogramhasfinisheduploadingyoushouldseeamessagethattheuploadhasbeencompletedinthewarnings/errorwindowatthebottomoftheIDEinsidetheblackwindow.SeeFigure2-29.

Figure2-29.UploadtoArduinoNote:TheUploadbuttondoesthejobofthe“verify”buttonbutalsouploadsthefinalcompiledprogramtotheArduino.

TheFinalResult

ThefinalresultwillbeablinkinglightontheArduinoboardneardigitalpin13.BydesigntheArduinoboardhasabuiltinL.E.D.connectedtopin13.SothisexampledidnotrequireyoutoconnectanactualseparateL.E.D.totheArduinoboard.SeeFigure2-30.

Figure2-30.BuiltinL.E.D.

PlayingAroundwiththeCode

Page 50: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

ThedefaultoftheprogramistoturnontheL.E.D.foronesecondandthenturnofftheL.E.D.foronesecond.Thecodethatcontrolsthetimingislocatedintheloop()function.ThedigitalWrite()functionsetsthevariableledwhichispin13toeitheronwhichisHIGHoroffwhichisLOW.Thedelay()functionsuspendstheexecutionoftheprogramfor1000millisecondsor1secondsothattheL.E.D.issetonfor1secondandofffor1second.SeeListing2-2.

Listing2-2.loop()Functionvoidloop(){digitalWrite(led,HIGH);//turntheLEDon(HIGHisthevoltagelevel)delay(1000);//waitforaseconddigitalWrite(led,LOW);//turntheLEDoffbymakingthevoltageLOWdelay(1000);//waitforasecond}

Playaroundwiththevaluesinthedelay()functionslengtheningorshorteningthetimetheL.E.D.staysonand/orlengtheningorshorteningthetimetheL.E.D.staysoff.Forexample,tohavetheL.E.D.brieflyflashshortenthefirstdelayvalueto100.ThiswouldshortenthetimethattheL.E.D.stayson.UploadthenewsketchtotheArduinobypressingthe“upload”button.Afterithasfinisheduploadingyouseeamessageindicatingthatintheblackwarnings/errormessagewindowatthebottomoftheIDE.LookattheL.E.D.ontheArduino.ThetimingoftheL.E.D.on/offpatternshouldhavechanged.

Page 51: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

Summary

InthischapterIintroducedtheArduinotothereader.IconcentratedmycoverageontheArduinoMega2560.IdiscussedtheMega2560’sbasicfeaturesandthencoveredkeyfunctionalcomponents.Next,informationaboutthesoftwareneededtodevelopprogramsfortheArduinocalledtheArduinoIDE(IntegratedDevelopmentEnvironment)waspresentedincludingthedifferentversionsoftheIDEavailablefordifferentplatforms.InformationaboutkeyfeaturesoftheIDEwasdiscussed.Finally,ahandsonexamplewaspresentedwhereItookthereaderthroughastepbystepguidetosettinguptheArduinowithadevelopmentcomputersystem.InthisexampleIalsodiscussedloadinginanexampleprogram,uploadingthisexampleprogramtotheArduino,andthenmodifyingtheprogramtoseehowthischangestheoutput.

Page 52: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

Chapter3

ArduinoProgrammingLanguageBasicsInthischapterIgooverthebasicsoftheArduinoLanguage.IcoverthebasicelementsoftheArduinolanguagethatyouwillneedinordertocreateprogramsthatcontroltheArduinoboard.Variouskeyelementssuchasdatatypes,constants,controlloops,etc.arecovered.

Page 53: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

C/C++LanguageforArduinoOverview

TheArduinousesCandC++initsprogramscalled“sketches”.Thissectionbrieflysummarieskeylanguageelements.ThisisnotmeantasareferenceguideandideallyyoushouldhavesomeexperiencewithaprogramminglanguagesimilartoCand/orC++.Manyexamples,fromthissectioncomedirectlyfromtheimagecaptureprogramthatiscoveredlaterinthisbook.

Comments

•//-Thisisasinglelinecommentthatisusedbytheprogrammertodocumentthecode.ThesecommentsarenotexecutedbytheArduino.•/**/-Theseencloseamultilinecommentthatisusedbytheprogrammertodocumentthecode.ThesecommentsarenotexecutedbytheArduino.

DataTypes

•void–Thisreturntypeisonlyapplicabletofunctionsandindicatesthatthefunctionwillnotreturnanyvaluetothefunctioncaller.Forexample,thesetup()functionthatispartofthestandardArduinocodeframeworkhasareturntypeofvoid.

voidsetup(){//InitializetheArduino,camera,andSDcardhere}

•boolean–Abooleanvariablecanholdeitherthevalueoftrueorfalseandis1byteinlength.Forexample,inthefollowingcodethevariableresultisdeclaredoftypebooleanandisinitializedtofalse.

booleanresult=false;

•char–Thecharvariabletypecanstorecharactervaluesandis1byteinlength.Thefollowingcodedeclaresthattempcharisoftypecharandisanarraywith50elements.

chartempchar[50];•unsignedchar–Theunsignedchardatatypeholds1byteofinformationintherangeof0through255.•byte–Thebytedatatypeisthesameastheunsignedchardatatype.Thefollowingcodedeclaresavariablecalleddataoftypebytethatisinitializedto0.bytedata=0;

•int–Theintdatatypeholdsa2bytenumberintherangeof-32,768to32,767.Thefollowingcodedeclaresavariableoftypeintegerthatholdstheerrorstatusafterwritingtothecamera.

intresult=OV7670WriteReg(COM7,COM7_VALUE_RESET);•unsignedint–Thisdatatypeis2bytesinlengthandholdsavaluefrom0to65,535.•word-Thisdatatypeisthesameastheunsignedinttype.

Page 54: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

•long–Thisdatatypeis4bytesinlengthandholdsavaluefrom2,147,483,648to2,147,483,647.•unsignedlong–Thisdatatypeis4bytesinlengthandholdsavaluebetween0to4,294,967,295.•Float–Thisisafloatingpointnumberthatis4bytesinlengthandholdsavaluebetween-3.4028235E+38to3.4028235E+38.•double-OnthecurrentArduinoimplementationthedoubleisthesameasfloatwithnogaininprecision.

•String–Thisisaclassobjectthatallowstheusertoeasilymanipulategroupsofcharacters.InthefollowingcodeanewvariablecalledCommandoftypeStringisdeclaredandinitializedtotheQQVGAresolution.

StringCommand=“QQVGA”;

•array–Anarrayisacontinuouscollectionofdatathatcanbeaccessedbyanindexnumber.Arraysare0basedsothatthefirstelementinthearrayhasanindexof0.Commontypesofarraysarecharacterarrays,andintegerarrays.ThefollowingcodedeclaresthevariableEntriesasanarrayoftypeStringthatcontains10elements.ThefunctionProcessRawCommandElement()isthencalledwithelementnumber2intheEntriesarraywhichisthethirdelementinthearray.Remember0isthefirstelementinthearray.

StringEntries[10];booleansuccess=ProcessRawCommandElement(Entries[2]);

Constants

•INPUT–ThisisanArduinopinconfigurationthatsetsthepinasaninputpinthatallowsyoutoeasilyreadinthevoltagevalueatthatpinwithrespecttogroundontheArduino.Forexample,thefollowingcodesetsthepinVSYNContheArduinoasanINPUTpinwhichallowsyoutoreadinthevoltagevalueofthepintodetermineifanewframeisbeingcapturedbythecamera.ThefunctionpinMode()isanArduinofunctionincludedinthebuiltinlibrary.

pinMode(VSYNC,INPUT);

•OUTPUT–ThisisanArduinopinconfigurationthatsetsthepinasanoutputpinthatallowsyoutodriveotherelectronicscomponentssuchasanL.E.D.ortoprovidedigitalinputtootherdevicesintermsofHIGHorLOWvoltages.InthefollowingcodethepinWENissettoOUTPUTusingthebuiltinpinMode()function.

pinMode(WEN,OUTPUT);

•HIGH(pindeclaredasINPUT)-IfapinontheArduinoisdeclaredasanINPUTthenwhenthedigitalRead()functioniscalledtoreadthevalueatthatpinthenaHIGHvaluewouldindicateavalueof3voltsormoreatthatpin.

•HIGH(pindeclaredasOUTPUT)–IfapinontheArduinoisdeclaredasanOUTPUTthenwhenthepinissettoHIGHwiththedigitalWrite()functionthenthepin’svalueis5volts.

Page 55: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

•LOW(pindeclaredasINPUT)-IfapinontheArduinoisdeclaredasanINPUTthenwhenthedigitalRead()functioniscalledtoreadthevalueatthatpinthenaLOWvaluewouldindicateavalueof2voltsorless.

•LOW(pindeclaredasOUTPUT)-IfapinontheArduinoisdeclaredasanOUTPUTthenwhenthedigitalWrite()functioniscalledtosetthepintoLOWthevoltagevalueatthatpinwouldbesetto0volts.

•true–trueisdefinedasanynonzeronumbersuchas1,-1,200,5,etc.•false–falseisdefinedas0.

TheDefineStatement

Thedefinestatementassignsanametoaconstantvalue.Duringthecompilationprocessthecompilerwillreplacetheconstantnamewiththeconstantvalue.#defineconstantNamevalue

IntheimagecaptureprogramthatisdiscussedlaterinthisbookIusethe#definestatementmanytimestoassignanumbertoapinlabelsuchastheArduinopinconnectedtothewriteresetpointerpinonthecamerawhichispin22.

#defineWRST22DefinestatementsarealsousedtoassignnumericalvaluestocameraregisterssuchasCLKRC.#defineCLKRC0x11

Thevaluesofthesecameraregistersarealsoassignedvaluesusingthe#definestatement.Thefollowingstatementassigns0x01asthevaluetosettheCLKRCregistertoputthecameraintoVGAresolution.

#defineCLKRC_VALUE_VGA0x01

TheIncludeStatement

The#includestatementbringsincodefromoutsidefilesand“includes”themintoyourArduinosketch.Generallyaheaderor.hfileisincludedwhichallowsaccesstothefunctionsandclassesinsidethatfile.

Forexample,inourimagecaptureprogramweincludetheWire.hfilewhichlet’sususetheWirelibrary.TheWirelibraryhasfunctionstoinitialize,toreaddatafromandtowritedatatoadeviceconnectedtotheI2Cinterface.WeneedtheWirelibrarytousetheov7670camerathatusestheI2Cbus.

#include<Wire.h>Also,weneedtoincludetheSDcardreaderlibraryinordertousetheSDcardreader/writer.#include<SD.h>

TheSemicolon

EachstatementinC/C++needstoendinasemicolon.Forexample,whendeclaringand

Page 56: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

initializingavariableyouwillneedasemicolon.constintchipSelect=48;Whenyouusealibrarythatyouincludedwiththe#includestatementyouwillneedasemicolonattheendwhenyoucallafunction.Wire.begin();

CurlyBraces

Thecurlybracessuchas{and}specifyblocksofcodeandmustmatchinpairs.Thatis,foreveryopeningbrace{theremustbeaclosingbrace}tomatch.Afunctionrequirescurlybracestodenotethebeginningandendofthefunction.voidFunction1(){//BodyofFunction}Programloopssuchastheforstatementmayalsoneedthecurlybracesfor(intI=0;I<9;I++){//Bodyofloop}Itisalsogoodpracticetousebracesincontrolstructuressuchastheifstatement.if(I<0){//BodyofIfstatement}

ArithmeticOperators

•=-Theequalssignistheassignmentoperatorusedtosetavariabletoavalue.Forexample,thefollowingsetsthevalueofthevariableDatatotheresultfromthefunctionCreatePhotoInfo():

StringData=CreatePhotoInfo();

+-Theplussignperformsaddition.Forexample,thefollowingaddstheStrings•Command,PhotoTakenCountandExttogethertogetafinalstringcalledFilename.

StringFilename=Command+PhotoTakenCount+Ext;

•--Theminussignperformssubtraction.Forexample,thefollowingcalculatesthetimeittakestocaptureaphotousingthecamerabymeasuringthedifferencebetweenthestartingtimebeforetheimageiscapturedandtheendingtimejustaftertheimageiscaptured.

ElapsedTime=TimeForCaptureEnd-TimeForCaptureStart;

•*-Theasterisksignperformsmultiplication.Forexample,thetotalbytesofanimageiscalculatedbymultiplyingthewidthoftheimagebytheheightoftheimagebythebytesperpixelintheimage.

intTotalBytes=ImageWidth*ImageHeight*BytesPerPixel;

Page 57: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

•/-Thebackslashsignperformsdivision.Forexample,thespeedinmilesperhourofanobjectiscalculatedbydividingthenumberofmilestheobjecthastraveledbythenumberofhoursthatittooktotravelthatdistance.

floatSpeed=NumberMiles/NumberHours;•%-Thepercentsignisthemodulooperatorthatreturnstheremainderfromadivisionbetweentwointegers.Forexample,intremainder=dividend%divisor;

ComparisonOperators

•==-Thedoubleequalisacomparisonoperatortotestiftheargumentontheleftsideofthedoubleequalsignisequaltotheargumentontherightside.Iftheargumentsareequalthenitevaluatestotrue.Otherwiseitevaluatestofalse.Forexample,iftheautomaticblacklevelcorrectionparameterissettooffthenthecodeblockisexecuted.

if(ABLCParam==“AblcOFF”){//Executecode}

•!=-Theexclamationpointfollowedbyanequalsignisthenotequaltooperatorthatevaluatestotrueiftheargumentontheleftisnotequaltotheargumentontherightside.Otherwise,itevaluatestofalse.Forexample,inthefollowingcodeifthecurrentcameraresolutionisnotsettoVGAthenthecodeblockisexecuted.

if(Resolution!=VGA){//IfcurrentresolutionisnotVGAthensetcameraforVGA

•<-Thelessthanoperatorevaluatestotrueiftheargumentontheleftislessthantheargumentontheright.Forexample,inthecodethatfollowstheforloopwillexecutethecodeblockwhiletheheightislessthantheheightofthephoto.Whentheheightcounterbecomesequalorgreaterthanthephoto’sheightthentheloopexits.

for(intheight=0;height<PHOTO_HEIGHT;height++){//Processeveryrowofthephoto}

•>-Thegreaterthanoperatorevaluatestotrueiftheargumentontheleftsideisgreaterthantheargumentontherightside.Forexample,inthefollowingcodeifthereareavailablecharacterstoreadinfromtheSerialMonitorthenexecutethecodeblock.Thatisthenumberofavailablecharacterstoreadinmustbegreaterthan0.

if(Serial.available()>0){//ProcessavailablecharactersfromSerialport}

•<=Thelessthansignfollowedbytheequalsignreturnstrueiftheargumentontheleft

Page 58: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

handsideislessthanorequaltotheargumentontherighthandside.Itreturnsfalseotherwise.

•>=Thegreaterthansignfollowedbytheequalsignreturnstrueiftheargumentontheleftisgreaterthanorequaltotheargumentontheright.Itreturnsfalseotherwise.

BooleanOperators

•&&-Thisisthe“and”booleanoperatorthatonlyreturnstrueifboththeargumentsontheleftandrightsideevaluatetotrue.Itreturnsfalseotherwise.Forexample,inthefollowingcodeonlyiftheuserselectsbothdenoiseandedgeenhancementwillthecodeblockbeexecuted.Otherwiseitwillnotbeexecuted.

if((DenoiseParam==“DenoiseYes”)&&(EdgeParam==“EdgeYes”)){//Setcameraforbothdenoiseandedgeenhancementofimages.

•||-Thisisthe“or”operatorandreturnstrueifeithertheleftargumentortherightargumentevaluatestotrue.Otherwise,itreturnsfalse.Forexample,inthefollowingcodeifeitherthecamera’scommandissettoQQVGAorQVGAthenthecodeblockisexecuted.Otherwiseitisnotexecuted.

if((Command==“QQVGA”)||(Command==“QVGA”)){//Code}

•!–Thenotoperatorreturnstheoppositebooleanvalue.Thenotvalueoftrueisfalsewhichis0andthenotvalueoffalseistruewhichisnonzero.InthefollowingcodeafileisopenedontheSDcardandapointertothefileisreturned.IfthepointertothefileisNULLwhichhasa0valuethennotNULLwouldbe1whichistrue.TheifstatementisexecutedwhentheargumentisevaluatedtotruewhichmeansthatthefilepointerisNULL.Thismeansthattheopenoperationhasfailedandanerrormessageneedstobedisplayed.

//OpenFileInfoFile=SD.open(Filename.c_str(),FILE_WRITE);//Testiffileactuallyopenif(!InfoFile){Serial.println(F(“\nCriticalERROR…CannotopenPhotoInfoFileforoutput…“));return;}

BitwiseOperators

•&-Thisisthebitwise“and”operatorbetweentwonumberswhereeachbitofeachnumberhasthe“and”operationperformedonittoproducetheresultinthefinalnumber.Theresultingbitis1onlyifbothbitsineachnumberis1.Otherwisetheresultingbitis0.

Page 59: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

•|-Thisisthebitwise“or”operatorbetweentwonumberswhereeachbitofeachnumberhasthe“or”operationperformedonittoproducetheresultinthefinalnumber.Theresultingbitis1ifthebitineithernumberis1.Otherwisetheresultingbitis0.

•^-Thisisthebitwise“xor”operatorbetweentwonumberswhereeachbitofeachnumberhasthe“xor”operationperformedonittoproducetheresultinthefinalnumber.Theresultingbitis1ifthebitsineachnumberaredifferentand0otherwise.•~-Thisisthebitwise“not”operatorwhereeachbitinthenumberfollowingthe“not”symbolisinverted.Theresultingbitis1iftheinitialbitwas0andthebitis0iftheinitialbitwas1.

•<<-Thisisthebitshiftleftoperatorwhereeachbitintheleftoperandisshiftedtotheleftbythenumberofpositionsindicatedbytherightoperand.Forexample,inthecodebelowa1isshiftedleftPinPositiontimesandthefinalvalueisassignedtothevariableByteValue.

ByteValue=1<<PinPosition;

•>>-Thisisthebitshiftrightoperatorwhereeachbitintheleftoperandisshiftedtotherightbythenumberofpositionsindicatedbytherightoperand.Forexample,inthecodebelowbitsinthenumber255areshiftedtotherightPinPositiontimesandthefinalvalueisassignedtothevariableByteValue.

ByteValue=255>>PinPosition;

CompoundOperators

•++-Thisistheincrementoperator.Theexactbehaviorofthisoperatoralsodependsifitisplacedbeforethevariablebeingincrementedorafterthevariablebeingincremented.InthefollowingcodethevariablePhotoTakenCountisincrementedby1.

PhotoTakenCount++;

Iftheincrementoperatorisplacedafterthevariablebeingincrementedthenthevariableisusedfirstintheexpressionitisinbeforebeingincremented.Forexample,inthecodebelowtheheightvariableisusedfirstintheforloopexpressionbeforeitisincremented.Sothefirstiterationoftheforloopbelowwoulduseheight=0.Theheightvariablewouldbeincrementedafterbeingusedintheexpression.

for(intheight=0;height<PHOTO_HEIGHT;height++){//Processrowofimage}

Iftheincrementoperatorisplacedbeforevariablebeingincrementedthenthevariableisincrementedfirstthenitisusedintheexpressionthatitisin.Forexample,inthecodebelowtheheightvariableisincrementedfirstbeforeitisusedintheforloop.Thismeansthatinthefirstiterationofthelooptheheightvariableis1insteadof0.

for(intheight=0;height<PHOTO_HEIGHT;++height){//Processrowofimage

Page 60: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

•—-Thedecrementoperatordecrementsavariableby1anditsexactbehaviordependsontheplacementoftheoperatoreitherbeforeorafterthevariablebeingdecremented.Iftheoperatorisplacedbeforethevariablethenthevariableisdecrementedbeforebeingusedinanexpression.Iftheoperatorisplacedafterthevariablethenthevariableisusedinanexpressionbeforeitisdecremented.Thisfollowsthesamepatternastheincrementoperatordiscussedpreviously.

•+=-Thecompoundadditionoperatoraddstherightoperandtotheleftoperand.Thisisactuallyashorthandversionofoperand1=operand1+operand2;Whichisthesameastheversionthatusesthecompoundadditionoperator.operand1+=operand2;

•-=-Thecompoundsubtractionoperatorsubtractstheoperandontherightfromtheoperandontheleft.Forexample,thecodeforacompoundsubtractionwouldbe:

operand1-=operand2;Thisisthesameasthefollowing:operand1=operand1-operand2;•*=-Thecompoundmultiplicationoperatormultipliestheoperandontherightbytheoperandontheleft.Thecodeforthisisasfollows.operand1*=operand2;Thisisalsoequivalentto:operand1=operand1*operand2;•/=-Thecompounddivisionoperatordividestheoperandontheleftbytheoperandontheright.Forexample,operand1/=operand2;Thisisequivalentto:operand1=operand1/operand2;•&=-Thecompoundbitwiseandoperatorisequivalentto:x=x&y;•!=-Thecompoundbitwiseoroperatorisequivalentto:x=x|y;

PointerAccessOperators

•*-TheDereferenceOperatorallowsyoutoaccessthecontentsthatapointerpointsto.Forexample,thecodethatfollowsdeclaresavariablecalledpdataasapointertoabyteandcreatesstorageforthedatausingthenewcommand.Thepointervariablecalledpdataisthendereferencedtoallowtheactualdatathatthepointerpointstobesetto1.

byte*pdata=newbyte;*pdata=1;

•&-TheAddressOperatorcreatesapointertoavariable.Forexample,thefollowingcodedeclaresavariablecalleddataoftypebyteandassignsthevalueof1toit.AfunctioncalledFunctionPointer()isdefinedthatacceptsasaparameterapointertoabyte.Inordertousethisfunctionwiththevariabledataweneedtocallthatfunctionwithapointertothevariabledata.

Page 61: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

bytedata=1;voidFunctionPointer(byte*data){//bodyoffunction}FunctionPointer(&data);

VariableScope

•Globalvariables–IntheArduinoprogrammingenvironmentglobalvariablesarevariablesthataredeclaredoutsideanyfunctionandbeforetheyareused.ForexampleinthefollowingcodebelowtakenfromtheimagecaptureprogramIwroteforthisbookthefollowingareglobalvariablesthataredeclaredatthebeginningoftheprogram.

//VGADefaultintPHOTO_WIDTH=640;intPHOTO_HEIGHT=480;intPHOTO_BYTES_PER_PIXEL=2;

•Localvariables–Localvariablesaredeclaredinsidefunctionsorcodeblocksandareonlyvalidinsidethatfunctionorcodeblock.Forexample,inthefollowingfunctionthevariablelocalnumberisonlyvisibleinsidetheFunction1()function.

voidFunction1()intlocalnumber=0;}

Conversion

•char(x)–Thisfunctionconvertsavaluexintoachardatatypeandthenreturnsit.byte(x)–Thisfunctionconvertsavaluexintoabytedatatypeandthenreturns•it.•int(x)–Thisfunctionconvertsavaluexintoaintegerdatatypeandthenreturnsit.•word(x)–Thisfunctionconvertsavaluexintoaworddatatypeandthenreturnsit.•word(highbyte,lowbyte)–Thisfunctioncombinestwobytes,thehighorderbyteandtheloworderbyteintoasinglewordandthenreturnsit.•long(x)–Thisfunctionconvertsavaluexintoalongandthenreturnsit.•float(x)–Thisfunctionconvertsavaluexintoafloatandthenreturnsit.

ControlStructures

•if(comparisonoperator)–Theifstatementisacontrolstatementthattestsiftheresultofthecomparisonoperatororargumentistrue.Ifitistruethenexecutethecodeblock.Forexample,inthefollowingcodetheifstatementteststoseeiftheYUVmatrixparameterissettoactivatetheYUVcolormatrix.IfitissetthentheSetCameraColorMatrixYUV()functioniscalled.

//SetColorMatrixforYUVif(YUVMatrixParam==“YUVMatrixOn”){SetCameraColorMatrixYUV();

Page 62: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

}

•if(comparisonoperator)else–Theifelsecontrolstatementissimilartotheifstatementexceptwiththeadditionoftheelsesectionwhichisexecutedifthepreviousifstatementevaluatestofalseandisnotexecuted.Forexample,inthefollowingcodeiftheframespersecondparameterissetfor30framespersecondthentheSetupCameraFor30FPS()functioniscalled.Otherwise,iftheframespersecondparameterissettonightmodethenthe

SetupCameraNightMode()functioniscalled.//SetFPSforCameraif(FPSParam==“ThirtyFPS”){SetupCameraFor30FPS();}elseif(FPSParam==“NightMode”){SetupCameraNightMode();}

•for(initialization;condition;increment)–Theforstatementisusedtoexecuteacodeblockusuallyinitializingacounterthenperformingactionsonagroupofobjectsindexedbythatincrementedvalue.Seethecodeexamplebelow.

for(inti=0;i<NumberElements;i++){//ProcessElementiHere}

•while(expression)–Thewhilestatementexecutesacodeblockrepeatedlyuntiltheexpressionevaluatestofalse.Inthefollowingcodethewhilecodeblockisexecutedaslongasdataisavailableforreadingfromthefile.

//readfromthefileuntilthere’snothingelseinit:while(TempFile.available()){Serial.write(TempFile.read());}

•break–Abreakstatementisusedtoexitfromaloopsuchasawhileorforloop.Inthefollowingcodethewhileloopcausesthecodeblocktobeexecutedforever.IfthereisdataavailablefromtheSerialMonitorthenitisprocessedandthenthewhileloopisexited.

while(1){if(Serial.available()>0)//Processthedatabreak;}}•return(value)–Thereturnstatementexitsafunction.Italsomayreturnavaluetothecallingfunction.

Page 63: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

return;returnfalse;

Page 64: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

Summary

InthischapterIcoveredthebasicsoftheArduinoprogramminglanguage.Icoveredabroadrangeofbasictopicssuchasdatatypes,constants,builtinfunctions,andcontrolloops.Inaddition,thischapterwasnotmeanttobeareferencemanualbutaquickstartguidetothebasicsoftheArduinoprogramminglanguage.PleaserefertotheofficialArduinolanguagereferenceformoreinformation.

Page 65: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

Chapter4

DigitalDesignReviewInthischapterIcoverbasicdigitaldesign.Istartbydiscussinghowdataisstoredinthecamera.Icoverthedifferenttypesofnumbersystemssuchasdecimal(base10),binary(base2),andhexadecimal(base16).Ithendiscusshowtoconvertnumbersbetweenthesesystems.Next,Igiveahandsonexampleofhowtosetthecamera’scolorbartestfeaturebysettingaregister.Booleanvariables,booleanlogic,andbooleanoperatorsarediscussed.Next,theclockpulsethatdrivesdigitalcircuitsiscovered.TheschematicsymbolsfordigitaloperatorssuchasAND,OR,andNOTarethendiscussed.Finally,adesignoverviewoftheentirecamerasystematachiplevelisgiven.Themaincamerachip,andtheFIFOframebuffermemorychiparediscussedindetail.

Page 66: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

HowDataisStoredintheov7670Camera

Dataisorganizedinadevicesuchasacomputerorcamerainbitsandbytes.Abitasinglememorycellthatcanholdavaluethatrepresentsa0or1.Eightcontinuousbitstogetherform1byteofmemory.Thebitsinabytearenumberedbit0tobit7withthebitattherightmostplacedesignatedasthe0bitandthebitattheleftmostplacedesignatedthe7thbit.SeeFigure4-1.

Figure4-1.1Byteor8bits

Theov7670hasmanydifferentcameraregistersthatare1byteor8bitslongbinarymemorycellswhereyoucanchangethevaluesinthesecellstosetcamerafeaturessuchasresolution,edgeenhancement,etc.Inthedocumentationdifferentnamesaregiventodifferentregistersbasedontheirpurposeintermsofcontrollingthecamera.However,eachoftheseregistersisidenticalinthattheyareall8bitsor1byteinlengthandeachmemorycellcanholdavalueofeither0or1.SeeFigure4-2.TheCLKRCregistercontrolsthecamera’sinternalclock.TheSCALING_XSCregistercontrolsthehorizontalscalefactorforthecamera’simage.TheHSTARTregistercontrolsthehorizontalstartpositionofthecamera’soutputframewhichmaybedifferentdependingonresolution.

Figure4-2.ov7670cameraregisters

Eachbitorgroupofbitsinaregistermaycontrolafunctionorfunctionsofthecamera.Forexample,fortheCLKRCregisterbit7isreservedandnotused,bit6controlstheuse

Page 67: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

oftheexternalclock,andbit5throughbit0controlstheinternalclockprescaler.SeeFigure4-3.

Figure4-3.TheCLKRCregister

Inordertofullyunderstandtheov7670datasheetandhowtoproperlysetthecameraregistersyouneedtounderstandhowvarioustypesofnumbersystemssuchasdecimal,binaryandhexadecimalrepresentationsoperate.

Page 68: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

DecimalNumbers(Base10Representation)

Whenwethinkofnumberswegenerallythinkofbase10numberswithdigitsfrom0through9.Whatthismeansisthatforexamplethenumber7952canberepresentedasthesumof7000+900+50+2.Wecanfurtherrepresenteachofthesecomponentsasanumbermultipliedbythebaseof10raisedtoapowerthatassociatedwiththecomponent’spositioninthenumber.Forexample,wecanrewrite7000as7*(10*10*10)or7*10^3.Theexponent3isalsothepositionof“7”inthenumber.Thepositioniszerobasedandtheexponentofthefirstcomponentis0.SeeFigure4-4.

Sothevalueofthenumber7952withabaseof10cancalculatedbythesumof:7*(10*10*10)=>7*10^3=>70009*(10*10)=>9*10^2=>9005*(10)=>5*10^1=>502*(1)=>2*10^0=>2

Ifyouaddallthenumbersyouget7000+900+50+2whichaddsupto7952inbase10whichisactuallywhatyoustartedwith.Thepointofthisexampleistolaythegroundworkforcalculatingthebase10valuesofnumbersthatusebase2(binary)andbase16(hexadecimal)representation.

Figure4-4.Base10decimalnumber

Page 69: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

BinaryNumbers(Base2Representation)

Base2numbersorbinarynumbershavedigitsconsistingof0and1.Thedecimal(base10)valueforabinarynumberiscalculatedbyamethodsimilartothatintheprevioussection.Forexample,tocalculatethedecimalvalueofthebinarynumber1111multiplyeachcomponentofthenumberbythebase2raisedtothepowerofthepositionofthatcomponentthensumallthecomponentstogether.Positionsarezerobasedsuchthatthefirstpositionis0.

1000=>(1*2^3)=>8100=>(1*2^2)=>410=>(1*2^1)=>21=>(1*2^0)=>1Theindividualcomponentsofthebinarynumberarethenaddedtogethertoget8+4+2+1=15inbase10decimal.SeeFigure4-5.

Figure4-5.Base2binarynumber

Page 70: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

HexadecimalNumbers(Base16Representation)

Base16numbersorhexnumbersconsistofdigits0through9andlettersAthroughF.Thehexdigits0through9arethesameasthedecimaldigitsof0though9.However,thehexdigitsofAthroughFcorrespondinvalueto10through15inbase10ordecimal.SeeFigure4-6.

ThehexnumberB65Fcanbeconvertedtodecimalusingthesamemethodasdiscussedpreviouslyforbinarynumbers.Eachcomponentofthehexnumberismultipliedby16tothepowerofthecomponent’spositioninthenumberandthenallthesecomponentsareaddedtogethertogetthefinalbase10value.Thefirstpositionbeingconsidered0.Thus,toconvertB65Ftoadecimalnumberwecandothefollowing:

B000=>B*16^3=>11*4096=>45056600=>6*16^2=>6*256=>153650=>5*16^1=>5*16=>80F=>F*16^0=>15*1=>15Soaddingallthesecomponents45056+1536+80+15=46,687(Base10).SeeFigure4-7foramoredetailedgraphicoftheabove.

Figure4-6.DecimalandHexDigits

Page 71: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

Figure4-7.Base16hexnumber

Page 72: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

ConvertingaBinaryNumber(Base2)toaHexNumber(Base16)

Inthissectionwewillgothroughanexampleofhowtoconvertabinarynumber(base2)toahexadecimalnumber(base16).Themethodofdoingthisissplittingupthebinarynumberinto4bitgroups,convertingthesegroupstohexnumbers,andthencombiningthethesehexnumberstoformthefinalhexadecimalnumberthatrepresentstheoriginalbinarynumber.

Firstwestartwiththebinarynumbersuchas11010101.SeeFigure4-8.

Figure4-8.Binarynumber11010101Next,weneedtobreakthebinarynumberinto4bitgroupssuchas1101and0101.Eachofthesegroupswillbeconvertedtoahexnumber.SeeFigure4-9.

Page 73: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

Figure4-9.Binarytohexconversion

Next,weconvertthe4bitgroupconsistingof1101intoasinglehexdigit.Todothiswetakethecomponentsofthebinarynumberandmultiplythemby2raisedtothepoweroftheirzerobasedpositionsandthenaddtheseresultstogetherandusethetableinFigure4-6toconvertthedecimalvalueintoahexvalue.Forthebinarynumber1101thecorrespondinghexdigitalisD.SeeFigure4-10.

Page 74: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

Figure4-10.Convertingthefirstgroupof4bitsofthebinarynumbertothefirstcomponentofthehexnumber

Thenweconverttheothergroupof4bitswhichis0101intoahexnumberwhichis5.Weusethesamemethodasforthefirstgroupofdigits.Thekeytorememberhereisthateachgroupof4bitsfromtheoriginalbinarynumberistreatedlikeaseparatenumbersothattheleftmostdigit’svalueis2^3followedby2^2,2^1,and2^0.Thesetranslateintothedecimalvalues8,4,2,1whichareindicatedonFigure4-11.

Page 75: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

Figure4-11.ConvertingthesecondcomponentofthebinarynumbertothesecondcomponentofthehexnumberThefinalstepistocombinethehexvaluesfromeachofthe4bitgroupsintoonesinglegroupofdigitswhichisD5.SeeFigure4-12forasummaryoftheconversionprocess.

Figure4-12.Summaryofconvertingabinarynumbertohex

Page 76: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

ConvertingaHexadecimalNumber(Base16)toaBinaryNumber(Base2)

Toconvertahexnumber(base16)intoabinarynumber(base2)youfirstneedtoconverteachhexdigitintoaseparategroupof4binarydigitsthatrepresentthathexdigit.Thefinalstepwouldbetocombineallthegroupsof4binarydigitsintoonebinarynumber.

Forexample,thehexnumberD5canbeconvertedtobinarybyfirstwritingeachofitscomponentsordigitsinbinaryandthencombiningthesetwo4bitbinarynumbersintoonefinallarger8bitbinarynumber.ThehexcomponentofDisconvertedtothe4bitbinarynumberof1101.Thehexcomponentof5isconvertedtothe4bitbinarynumberof0101.Thefinalbinary1101.Thehexcomponentof5isconvertedtothe4bitbinarynumberof0101.Thefinalbinary13.

Figure4-13.Convertingahexnumberintoabinarynumber

Page 77: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

HandsOnExample:SettingRegistersontheOV7670Camera

Inthishandsonexample,Idemonstratetheimportanceofwhatwasdiscussedpreviouslyinthischapterintermsofconvertingabinarynumbertoahexadecimalnumberandviceversa.IdiscusstheCOM17cameraregisterandshowyouwhatbinarynumbersareneededtocontrolcertainfeaturesofthecameraandhowthesebinarynumberscanbeconvertedtohexadecimalnumberstobeusedforsettingtheactualregister.Hexadecimalnumbersrequirelessdigitsthanthesamenumberexpressedinbinaryform.Thus,whenahumanhastoactuallyenteranumbertosetthevalueofacameraregisterintotheArduinoIDEahexadecimalnumberispreferredbecauseitreducesthechanceofdataentryerror.Inaddition,thecamera’sdatasheetexpressesdefaultregistervaluesinhexadecimalsoitwouldbegoodtoknowwhatcamerafunctionsareenabledbydefaultwhenthecameraispoweredupandtodothatyouneedtoknowhowtoconverthexnumbersintobinarynumbers.

TheCOM17CameraRegister

TheCOM17ov7670cameraregistercontrolsthecamera’automaticexposurecontrollerwindowsize,andtheDigitalSignalProcessor’scolorbartestenabledstatususedfortestingthecamera’soutput.Bit7andbit6controltheAECwindowsize.Thedefaultsettingis00whichisfinesowedonotneedtochangethesebits.Bit5andbit4arereservedsowecanignoretheseandleavethemattheirdefaultsettingsof00.Bit3isakeybitthatenablesthecolorbartestmodeoftheDigitalSignalProcessororDSP.Setthisbitto1toenablethecolortestand0todisableit.Bits2,1,and0arereservedsowecanleavetheseattheirdefaultvaluesof000.SeeFigure4-14.

Figure4-14.Com17Register

SettingtheDSPColorBarTestEnable

Thecolorbartestisaseriesofverticalcolorbarsconsistingofwhite,yellow,lightblue,green,purple,red,blue,andblackasseenfromlefttoright.Whenthecolorbartestisenablednormalcameraimagecapturingisdisabledandtheonlyoutputisthecolorbartestimage.Thistestisusefulindeterminingifthecameraissetupcorrectlyandproducingthecorrectcolorimage.SeeFigure4-15.

ImportantNote:Anextremelyimportantthingtonotehereisthatinordertogetthecorrectcolorsfromtheov7670camerayouwillneedtosetacameraregisterthatintheofficialdocumentationislistedasbeing“reserved”butactuallyisneededtocorrectlydisplaycolors.Forexample,redcolorswillappeargreeninthephotothatistakenbythecamera.Wewilldiscussthismoreindepthlaterinthebookandshowyouexactlyhowtodoitina“handsonexample”.

Page 78: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

Figure4-15.Thecolorbartest

InordertoenablethecolorbartestyouneedtosettheCOM17registertothehexvaluesof08.InordertodisablethecolorbartestyoucansettheCOM17registertothehexvalueof00.Rememberthateachhexnumberrepresents4binarybitsandthusyoucaneasilygetthehexvalueyouneedfromFigure4-14.

IntermsofimplementingthesevaluesintoArduinoC/C++sourcecodewecandeclaredefinesthatrepresentavaluefordisablingthecolorbartestwhilekeepingtheAECwindowsettingsettonormalsuchas:

#defineCOM17_VALUE_AEC_NORMAL_NO_COLOR_BAR0x00WecanalsodeclareadefinetorepresentthevalueforenablingthecolorbartestwhilekeepingtheAECwindowsettingsettonormalsuchas:#defineCOM17_VALUE_AEC_NORMAL_COLOR_BAR0x08//ActivateColorBarforDSP

The“0x”infrontofthenumberidentifiesthisnumberasahexadecimalnumbervalue.Wewillgointofurtherdetailonhowtoactuallysettheregistervalueincodeinalater“handsonexample”inthisbook.Here,wejustareshowingyouhowyouchangethevaluesinacamera’sregistersinordertochangeacertainpropertyinthiscaseitwasdisplayingthecolorbartest.

Page 79: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

BooleanVariables,LogicandTruthTables

Abooleanvariableisavariablethatcantakeononeoftwovaluessuchas0or1.ThedigitaloutputpinsoftheArduinocanoutputelectricalsignalsthatrepresentbooleanvariables.YoucanusethebuiltinArduinofunctiondigitalWrite()tooutputaHIGHorLOWvaluerepresentingabooleanvariable.

Forexample,tooutputaHIGHvaluewhichrepresents1ortruetothepinRRSTyouwouldwritecodesuchas:digitalWrite(RRST,HIGH);TooutputaLOWvaluewhichrepresents0orfalsetopinRRSTyouwouldwritecodesuchas:digitalWrite(RRST,LOW);

Booleanlogicappliestobooleanvariablesandcanbeusedindigitalcircuitstocontrolabooleanoutputbasedontwoormorebooleaninputs.ThebasicbooleanlogicoperationsareAND,OR,andNOT.InorderfortheoutputoftheANDoperatortobetrueor1alloftheinputsmustbetrueor1.SeeFigure4-16forthebooleantruthtableforANDwhichlistsallthepossibleinputsandoutputcombinationsfortheANDoperatorusingtwobooleaninputvariables.

Figure4-16.BooleanlogicAND

TheresultofanORbooleanoperationistrueifanyoftheinputsaretrueor1.SeeFigure4-17foratableofallthepossibleinput/outputcombinationsandresultsfortheORoperationontwobinaryinputs.

Figure4-17.BooleanlogicORTheresultofaNOTbooleanoperationonabooleaninputistheoppositeoftheinput.SeethetableinFigure4-18.

Figure4-18.BooleanlogicNOT

Now,let’sgiveyouabetterideaofhowbooleanvariablesrelatetotheArduino.Figure4-19givesyouagraphicrepresentationoftheelectricalsignalswhichareactuallyvoltagelevelsthatareoutputbytheArduinothatcorrespondtotheANDtruthtableinFigure4-

Page 80: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

16.

Figure4-19.BooleanlogicANDvoltageoutputforArduinoFigure4-20givestheelectricalsignalsthatcorrespondtothebooleantruthtablefortheORoperatorthatislistedinFigure4-17.

Figure4-20.BooleanlogicORvoltageoutputforArduino

Page 81: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

TheClockPulse

TheclockpulseisabinaryseriesofHIGHandLOWvoltagevaluesthatareoutputfromtheArduinoandusedtodrivethestateofthecameraorotherdigitaldevice.Thatisthepulsescausethecameraordevicetoperformspecificactionsaccordingtoitsdesign.Forexample,inordertoreadinthedatafromthecamera’smemoryyouneedtoreadtheimagedataonebyteatatimeuntilallthebytesareread.Inordertoreadthisyouneedtosendaclockpulsetothecamera’sRCLKinputthatwillbegeneratedfromtheArduino.SeeFigure4-21.

Figure4-21.RCLKclockpulseoutputfromArduinotocameraThewayIgenerateaclockpulsetodrivetheRCLKinputisby:1.CallingthedigitalWrite()functiontosetthedesiredoutputpinHIGH2.CallingthedelayMicroseconds()functiontowaitaspecifiednumbermicroseconds.AllthistimetheoutputpinthatisconnectedtotheRCLKinputonthecameraisHIGH.3.CallingthedigitalWrite()functionandsettingtheoutputpinconnectedtoRCLKtoLOW.4.CallingthedelayMicroseconds()functionandpausingprogramexecutionforaspecifiedtime.ThisgeneratestheLOWpartoftheclockpulse.SeeListing4-1fortheArduinocodeListing4-1.ThePulsePin()functionvoidPulsePin(intPinNumber,intDurationMicroSecs){digitalWrite(PinNumber,HIGH);//SetsthepinondelayMicroseconds(DurationMicroSecs);//PausesforDurationMicroSecsmicrosecondsdigitalWrite(PinNumber,LOW);//SetsthepinoffdelayMicroseconds(DurationMicroSecs);//PausesforDurationMicroSecsmicroseconds}RCLKisdefinedaspin26usinga#definestatement#defineRCLK26//OutputFIFObufferoutputclockPulsingtheactualRCLKpinisdonecallingthePulsePin()functionsuchas:PulsePin(RCLK,1);

Page 82: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

ReadingSchematics

Inordertounderstandtheschematicsfortheov7670cameraordigitaldevicesingeneralyoushouldknowthestandardsymbolsforlogicgatesthatimplementthebooleanlogicdiscussedpreviously.InthissectionwewilldiscusstheschematicsymbolsfortheAND,ORandNOTgates.InadditionwewilldiscusstheNAND,andNORgateswhichareacombinationoftheAND,andORgateswithaNOTgate.

AndGates

TheschematicsymbolforanANDgatethatimplementstheANDbooleanfunctionisshowninFigure4-22.

Figure4-22.Andgates

OrGates

TheschematicsymbolfortheORgatethatimplementstheORbooleanlogicisshowninFigure4-23.

Figure4-23.Orgates

Not(Inverter)Gates

TheschematicsymbolfortheNOTgatethatimplementstheNOTbooleanlogicisshowninFigure4-24.

Figure4-24.Not(inverter)gate

NANDGates

TheschematicsymbolfortheNANDgatethatperformsthebooleanANDfunctionfollowedbythebooleanNOTfunctionisshowninFigure4-25.TheTexasInstrumentsSN74LVC1G00NANDgateistheactualtypeofgateusedintheov7670cameraaccordingtothepubliclyavailableschematics.

Page 83: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

Figure4-25.NOTANDgate

NORGates

TheschematicsymbolfortheNORgatethatperformsthebooleanORfunctionfollowedbythebooleanNOTfunctionisshowninFigure4-26.

Figure4-26.NOTORgate

Page 84: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

DesignOverviewfortheOV7670CamerawithFIFOMemory

InthissectionIcoverthebasicoperationoftheov7670camerafromachiplevel.Istartwithdiscussingthepubliclyavailabledocumentationfortheov7670.IthendiscussthemaincamerachipandtheFIFOframebuffermemorychip.Ithendiscusshowthesechipsareconnectedusingtheschematicoftheov7670camerasystem.Then,Idiscusshowthemaincamerachipoutputsavideoframeusingtimingdiagrams.Finally,IdiscusshowtheFIFOcancapturethevideoimagedatafromthemaincamerachipandhowyoucanreadtheimagedatafromtheFIFO.

PubliclyAvailableDocumentationfortheov7670

Thissectiondescribesthepubliclyavailabledocumentationrelatingtotheov7670cameraincludingtheofficialdocumentationfromOmnivision,themakeroftheov7670camera.IrecommendthatyoudownloadthefollowingpdffileswhichcanbereadusingtheAdobeAcrobatReaderwhichisfreeandcanbedownloadedfromAdobe’swebsite.Youcanalsodoagooglesearchforthesedocuments.ThisbookisnotmeanttobeareferencemanualbutaquickstartguidethatisdesignedforyoutogetquicklystarteddevelopingcamerabasedapplicationsusingtheArduinoandov7670.However,theinformationyoulearninthisbookwillalsohelpyoudevelopcameraapplicationsforcamerasotherthantheov7670aswell.

•Omnivisionov7670/ov7171AdvancedInformationPreliminaryDatasheet(Version1.4August21,2006)http://www.electronicaestudio.com/docs/sht001.pdf•ov7670/ov7171ImplementationGuide(Version1.0September2,2005)https://github.com/dalmirdasilva/ArduinoCamera/blob/master/CameraAL422B/datasheet/OV7670%20Implementation%20Guide%20%28V1.0%29.pdf•ov7670SoftwareApplicationNotehttps://github.com/luckasfb/Development_Documents/blob/master/MTKMediatek-Alps-Documents/OV7670%20software%20application%20note.pdf•AverLogicAL422BDataSheets(RevisionV1.01)http://www.frc.ri.cmu.edu/projects/buzzard/mve/HWSpecs1/Documentation/AL422B_Data_Sheets.pdf•Omnivisionov7670FIFOcameraschematichttp://www.beyondlogic.org/pdf/OV7670_FIFO_SCH_V1.pdf

CameraPinInput/Outputs

Thecamerainputandoutputpinsontheov7670areshownbelowinFigure4-27.

Page 85: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

Figure4-27.Camerapininputsandoutputs•3.3v–Inputforthe3.3voutputpinontheAruduino•Ground–GroundconnectionforthecameratobeconnectedtogroundonArduino•SIOC–I2CinterfaceconnectiontotheArduino’sSCLclockline.•SIOD–I2CinterfaceconnectiontotheArduino’sSDAdataline.•VSYNC–Outputfromcamerathatmarksthestartorstopofanoutputofasingleimageframe.•HREF–Trueifarowofanimageisbeingoutputtothevideoport.•D7–D0–Videooutputport,1byteor8bitswide.Imagedataisreadfromthesepinsonebyteatatime.•RST–Inputthatcanbeusedtoresetthecamera.•PWDN–Inputthatcanbeusedtoputthecameraintopowerdownmode.•STR–CamerastrobeoutputthatcanbeusedtoturnonanL.E.D.lightwhilethecameratakesanimage.

•RCK–Inputforaclockpulsethatisusedtoreadindatafromthevideoportonebyteatatime.Oneclockcyclecorrespondingtoonebyte.•WR–Writeenableinputforenablingthewritingofdatatothecamera’sframebuffermemory.TrueifyouwantimagedatafromthecameratobewrittentotheFIFOframebuffermemory.Falseiftheimagedataisnottobewrittentothecamera’smemory.

•OE–Inputpinthatcontrolsthecamera’soutputenableforthevideoportthatisusedtodetermineifthedataonthepinsD7–D0arevalid.•WRST–Inputpinthatisusedtoresettheframebuffermemory’swritepointersothatimagedatawillbewrittenatthestartoftheimageorframe.

•RRST–Inputpinthatisusedtoresettheframebuffermemory’sreadpointersothatimagedataisreadandsenttothevideooutputportstartingatthebeginningoftheimage

Page 86: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

orframe.

MainCameraChipOverview

Thissectiondiscussesthemaincamerachipthatcaptures,processestheimage,andsendsitouttotheframebuffermemorywhereitcanthenbereadbytheArduino.SeeFigure4-28.

Figure4-28.Maincamerachip•AVDD–Analogpowersupply•SIO_C–SCCBserialinterfaceclockinput.(compatiblewithI2CandSCL)•DOVDD–DigitalpowersupplyforInput/Output•SIO_D–SCCBserialinterfacedatainputandoutput.(compatiblewithI2CandSDA)•VREF1–Referencevoltage.•VSYNC–Verticalsyncoutput.•VREF2–Referencevoltage.•HREF–HREFsignaloutput.•PCLK–Pixelclockoutput.•DVDD–Powersupplyforthedigitallogiccore•AGND–Analogground.•DOGND–Digitalground.•DO–D7–Videooutputportthatis8bitswideandusedtooutputimagedata.•PWDN–Powerdownenabledisablemode.0isnormalmode.1ispowerdownmode.•STROBE–L.E.D.orstrobecontroloutput•XCLK–Systemclockinput•#RESET–Clearsallregistersandresetsthemtotheirdefaultvalues.0istheresetmodeand1isthenormalmode.

FIFOFrameBufferFieldMemoryOverview

Thissectiondiscussesthecamera’sframebuffermemorychip.SeeFigure4-29.

Page 87: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

Figure4-29.AverLogicAL422BFIFOframebuffermemorychip•DI0-DI7–Datainput.DataisinputontherisingedgeofthecycleofWCKwhen/WEispulledlow(enabled).

•DO0–DO7–Dataoutput.DataoutputissynchronizedwiththeRCKclock.DataisobtainedattherisingedgeoftheRCKclockwhen/REispulledlow.TheaccesstimeisdefinedfromtherisingedgeoftheRCKcycle.•/WE–Writeenablethatisactivelow./WEcontrolstheenabling/disablingofthedatainput.When/WEispulledlow,inputdataisacquiredattherisingedgeoftheWCKcycle.When/WEispulledhigh,thememorydoesnotacceptdatainput.Thewriteaddresspointerisstoppedatthecurrentposition./WEsignalisfetchedattherisingedgeoftheWCKcycle.

•GND–Ground.•TST–Testpin.Fortestingpurposeonly.Itshouldbepulledlowfornormalapplications.•/WRST–Writeresetthatisactivelow.Thisresetsignalinitializesthewriteaddressto0,andisfetchedattherisingedgeoftheWCKinputcycle.

•WCK–Writeclock.Thewritedatainputissynchronizedwiththisclock.WritedataisinputattherisingedgeoftheWCKcyclewhen/WEispulledlow(enabled).Theinternalwriteaddresspointerisincrementedautomaticallywiththisclockinput.

•VDD–5voltsor3.3volts.

•/RE–Readenablethatisactivelow./REcontrolstheoperationofthedataoutput.When/REispulledlow,outputdataisprovidedattherisingedgeoftheRCKcycleandtheinternalreadaddressisincrementedautomatically./REsignalisfetchedattherisingedgeoftheRCKcycle.

•/OE–Outputenablethatisactivelow./OEcontrolstheenabling/disablingofthedataoutput.When/OEispulledlow,outputdataisprovidedattherisingedgeoftheRCKcycle.When/OEispulledhigh,dataoutputisdisabledandtheoutputpinsremainathighimpedancestatus./OEsignalisfetchedattherisingedgeofRCKcycle.

•/RRST–Readresetthatisactivelow.Thisresetsignalinitializesthereadaddressto0,andisfetchedattherisingedgeoftheRCKinputcycle.

•RCK–Readclock.Thereaddataoutputissynchronizedwiththisclock.ReaddataoutputattherisingedgeoftheRCKcyclewhen/OEispulledlow(enabled).Theinternalreadaddresspointerisincrementedwiththisclockinput.

•DEC–Decouplingcapinput.Decouplingcappin,shouldbeconnectedtoa1mFor2.2mFcapacitortogroundfor5Vapplication.For3.3Vapplication,theDECpincanbe

Page 88: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

simplyconnectedtothe3.3Vpowerwithregular0.1mFbypasscapacitor.

OverallCameraSchematic

Thissectioncoverstheoverallcameraschematicandshowshowthemainpartsofthecamerainteractwithoneanother.SeeFigure4-30.Importantthingstonoteare:•ThecameraclockgeneratorcreatesaclockpulsethatdrivestheXCLKinputofthemaincamerachip.•ThevideoportoutputofthemaincamerachippinsD0-D7areconnectedwiththevideoframebufferFIFOmemory’sinputdatapinswhichareDI0-DI7.

•ThePCLKonthemaincamerachipthatissyncedwiththeoutputofbytesthatrepresentthepixelsoftheimageisconnectedtotheFIFOmemory’sWCKthatissyncedwiththewritingofthispixeldatatothememory.

•TheHREFoutputpinonthemaincamerachipisconnectedtoaNANDgatewithauserinputwriteenablesignalthatwillactivatewritingdatatotheFIFOmemorywhenthewriteenablesignalisHIGHandtheHREFisHIGH.ThisresultsinaHIGHvaluefromtheANDoperationandaLOWvaluefromtheNOToperationwhichactivatesthe/WEinputtotheFIFOmemorywhichisactiveLOW.SeeFigure4-31foracloserviewoftheNANDgate.

Figure4-30.OverallCameraSchematic

Page 89: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

Figure4-31.KeytowritingimagedatatoMemory

BasicOperation

Themaincamerachipoutputsasinglevideoframeimagethroughthe8-bitvideoportby:1.PulsingVSYNChightoindicatethestartofanewvideoframeforoutput.

2.TheHREFgoeshighwhenavalidrowofpixelsfromthevideoframeisputontheoutputvideoportpinsofD0-D7.Thiscontinuesforeachrowfromrow0tothelastrowfortheimagesizewhichisrow479foraVGAscreenresolution(640by480).Inaddition,whentheHREFishighthePCLKsyncswiththeoutputofthebytesforeachrowintheimage.SeeFigure4-33.

3.VSYNCpulseshighagaintoindicatetheendofthevideoframeoutput.SeeFigure4-32forthetimingdiagram.

Figure4-32.MaincamerachipVGAimageoutputsimplifiedtimingdiagram

Page 90: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

Figure4-33.Thepixelclock

TheimageoutputfromthemaincamerachipisthenfedintotheFIFOvideoframebuffermemory.FromthereitisreadbytheArduino.ThegeneraloperationoftheframebufferisgiveninthefunctionalblockdiagraminFigure4-34.

Figure4-34.FifomemoryoperationInordertocaptureavideoframebeingoutputbythemaincamerachipyouneedto:1.WaitforVSynctopulsetoindicatethestartoftheimage2.ResetWritePointerto0whichisthebeginningoftheframe3.SetFIFOWriteEnabletoactive(high)sothatimagecanbewrittentoram4.WaitforVSynctopulseagaintoindicatetheendoftheframecapture5.SetFIFOWriteEnabletononactive(low)sothatnomoreimagescanbewrittentotheramInordertoreadthevideoframethatwascapturedintotheFIFOmemoryyouneedto:1.SettheFIFOreadbufferpointertothestartofframe2.Foreverybyteofdataintheimage,pulsethereadclockRCLKtobringinanewbyteofdataontothevideooutputportandthenreaditintotheArduino.OnceyouhavethebyteofimagedataintheArduino’smemoryyoucanprocessthisdatabywritingittoaSDcard.

Page 91: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

Summary

InthischapterIdiscussedthebasicdigitaldesigninformationthatyouwillneedtounderstandhowtodevelopcameraapplications.Istartedwithadiscussionofhowdataisstoredinacamera.Next,Icovereddecimalnumbers,binarynumbers,andhexadecimalnumbers.Ithencoveredconversionsbetweenthesenumbertypes.AhandsonexamplefollowedwhereIexplainedhowtosetthecolortestbarmodeofthecamerabysettingacameraregister.Booleanvariables,booleanoperations,andbooleantruthtableswerecovered.TheclockpulsewasdiscussedandthentheschematicsymbolsforbooleanoperationssuchasANDandORwerecovered.Finallythedesignoftheov7670camerawasexplainedatachiplevel.

Page 92: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

Chapter5

Page 93: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without
Page 94: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

TakingPhotoswiththeOmnivisionov7670Camera–Part1InthischapterIcoverSDcardstoragefortheArduino,theArduino’sI2Cinterface,theOmnivisionov7670FIFOCameraImageCaptureSoftware,andtheffmpegimageconversionprogram.IstartwithahardwarediscussionofSDcardstorageontheArduinoincludingadiscussionofSDcardreaderinput/outputpinsandanoverviewoftheSDcarditself.IdiscussthesoftwareaspectsoftheSDcardreaderandcoverreadingfiles,writingfiles,anddeletingfilestoandfromaSDcard.NextIcoverI2CdevicesandshowyouhowtoconnecttheI2Cinterface,initialize,readfrom,andwritetoanI2Cdevicesuchastheov7670camera.ThenIcovertheimagecapturesoftwarethatwillbeusedtocaptureanimagefromthecameraandthentosaveittoaSDcard.Finally,IdiscussffmpegwhichisthefreeimageconvertersoftwarethatwillbeusedtoconverttheimagefilesproducedbythecameraintoPNGfilesthatcanbeviewedbyapaintprogramorwindowsexplorer.

Page 95: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

OverviewofSDCardStoragefortheArduino

InthissectionIdiscusstheSDcardandhowtouseitwiththeArduino.IfirstcovertheSDcardreader’soutputandinputpinsandhowtheyshouldbeconnectedtotheArduinoMega2560.IthenshowyouwhattheactualSDcardlookslikeandhowitshouldfitintotheSDcardreader.IthenshowyouhavetoprogramtheArduinosothatyoucanwritefiles,readfiles,anddeletefilesontheSDcard.

SDCardReaderInputandOutputPins

TheSDcardreaderinputandoutputpinsareshowninFigure5-1.TheinputandoutputpinlayoutsarefromaSDcardreaderIpurchasedfromAmazon.com.Theexactlistingwas“SDCardReaderModuleSlotSocketForArduinoARMMCU(2pcs)byExciting$5.50”andyouget2SDcardreadersforthatprice.ThisSDcardreaderisforanormalfullsizeSDcard.

Theinput/outputspinsoftheSDcardreaderare:•GND–Groundconnection.•3.3–3.3voltinput•5V–5voltinput

•SDCS–SDcard’sChipSelectPin.Thisisthepinthatthemastercanusetoenableanddisablespecificdevices.Whenadevice’sChipSelect(alsocalledtheSlaveSelect)pinislow,itcommunicateswiththemaster.Whenit’shigh,itignoresthemaster.ThisallowsyoutohavemultipledevicessharingthesameMISO,MOSI,andCLKlines.

•MOSI–MasterOutSlaveIn.Themasterlineforsendingdatatotheperipherals.•SCK–SerialClock.Theclockpulseswhichsynchronizedatatransmissiongeneratedbythemaster.•MISO–MasterInSlaveOut.Theslavelineforsendingdatatothemaster.

Page 96: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

Figure5-1.SDcardreaderinput/outputpinsIntermsoftheconnectingtheSDcardtotheArduinoMega,thisisdoneby:•ConnectingPin50ontheArduinotothe(MISO)pinontheSDcard•ConnectingPin51ontheArduinotothe(MOSI)pinontheSDcard•ConnectingPin52ontheArduinotothe(SCK)pinontheSDcard.

•ConnectingPinX(UserDefined)ontheArduinotothe(SDCS)pinontheSDcardorconnectingPin53ontheArduino(HardwareSSorSlaveSelect)tothe(SDCS)pinontheSDcard.

•ConnectingtheGNDpinonthecardreadertotheGNDpinontheArduino.

•Connectingthe3.3Vpinonthecardreadertothe3.3voutputontheArduino.ImportantNote:Therearetwopinsforeachinput/outputitemfortheSDcard.IrecommendusingthepinclosesttothepinlabelsinceIhaveseencommentsthatonsomecardsthepinthatisfarthestfromthepinlabeldoesnotwork.SeeFigure5-2toseehowIsetupmySDcard.

Page 97: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

Figure5-2.SDcardreaderconnections

TheSDcard

TheSDcarditselfgoesintothemetalholderfaceupandorientedasshowninFigure5-3.Youwillneedtopushthecardinuntilyouhearaclick.Thisindicatesthatthecardisfullyinandisreadyforuse.Toremovethecardpressdownuntilyouhearanotherclickandthenremovethecard.

Figure5-3.SDcardreaderwithcard

IpurchasedmySDcardfromAmazon.comandaccordingtothelistingitwasa“SanDisk8GBClass4SDHCMemoryCard”.Thiswillprovideplentyofmemoryfortaking

Page 98: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

pictureswiththecamera.SeeFigure5-4foranimageoftheSanDiskSDcard.

Figure5-4.SDHC8gbcardfromSandisk

UsingtheSDCardwithArduino

TheArduinocomeswithabuiltinlibraryoffunctionsthatallowaccesstotheSDcard.TherearefunctionsthatallowtheusertowritedatatotheSDcard,readdatafromtheSDcard,checkifafileontheSDcardexists,anddeleteafilefromtheSDcard.

InitializingtheSDCard

InordertousetheSDlibraryfunctionsyouneedtoincludetheSDlibraryheaderinyoursourcecodesuchas:#include<SD.h>Thehardwareslaveselectpinispin53ontheArduinoMegaconstintHardwareSSPin=53;//ForArduinoMega

ThehardwareslaveselectpinalsomustbesettobeofanoutputtypeinorderfortheSDcardlibrarytowork.WecallthebuiltinpinMode()functiontosetthehardwareslaveselectpintobeofanoutputtype.Thisisneededevenifitisnotused.Forexample,theactualchipselectpinisotherthan53.

pinMode(HardwareSSPin,OUTPUT);//changethisto53onamegaNext,wedefineachipselectpinaspin48.Wecouldhaveeasilydefinedthechipselectpinasanotherdigitalpinifwewished.constintchipSelect=48;

Then,weneedtoinitializetheSDcardandSDcardlibrarybycallingtheSD.begin()

Page 99: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

function.Herewehavetheoptionofchangingthedefaultchipselectpinof53(ontheMega)whichiscalledthehardwareSSpintoapinspecifiedinthenumbertosentthebegin()function.

Forexample,wecaninitializetheSDcardwiththechipselectpinbeingsetto48bythefollowingcode.Iftheinitializationsucceedsthenatruevalueisreturnedotherwiseafalsevalueisreturned.if(!SD.begin(chipSelect))

{//SDcardinitializationfailed.return;}else{//SDcardinitializationsuccessful}

WritingFilestotheSDCard

YoucanalsowritefilestotheSDcardusingthebuiltinSDcardlibrary.InthehandsonexamplepresentedlaterinthischaptercameradataisreadinonebyteatatimeintotheArduino’smemoryandimmediatelywrittentotheSDcard.

InordertowriteafiletoaSDcardyouneedto:1.DeclareavariableoftypeFilethatrepresentsthefilethatyouwillwriteto.

2.CalltheSD.open()functionwiththeparametersforthefilenameandtheparameter“FILE_WRITE”tocreateafileforreadingandwritingstartingattheendofthefile.SetthereturnvalueofthefunctiontothevariablethatyoudeclaredasaFileinStep1.

3.IfthereturnvaluefromtheSD.open()functionisnullor0thentherewasanerroropeningthefile.OtherwisetheFileobjectisvalid.

4.OnceyouhaveavalidFileobjectyoucanwritetextdatatothefilebycallingtheprint()functionontheobject.Youcanwritebinarydatatothefilebycallingtheobject’swrite()function.

5.Finally,inordertosavethedatatotheSDcardyouneedtocalltheclose()functionontheFileobject.SeeListing5-1foranexampleofwritingafiletoaSDcard.Listing5-1.WritingafiletoaSDcardFileTempFile;byteData;TempFile=SD.open(“testfile.txt”,FILE_WRITE);if(TempFile){TempFile.print(“Datatobewritten”));TempFile.write(Data);//closethefile:TempFile.close();}

Page 100: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

else{//Erroropeningfile}

ReadingFilesfromtheSDCard

YoucanreadfilesthatyouhavesavedfromtheSDcard.ToreaddatafromafilethathasbeensavedtoaSDcardandprintittothescreenfromtheSerialMonitoryoumust:1.DeclareavariableoftypeFilethatrepresentsthefiletobereadin.2.CallSD.open()withthefilenamethatistoreadin.SetthereturnvalueofthefunctiontotheFilevariablecreatedinStep1.3.IftheFilevariableisnullor0thentheopeningofthefilefailed.

4.IftheFilevariableisvalidthenyoucanreadinthecontents.TheFileobject’savailable()functioncanbecalledtodetermineifthereareanymorebytestoreadfromthefile.Usetheread()functiontoactuallyreadinthebytesandprintthemtoscreen.Youcanputtheread()functionintoawhileloopandthetestpartoftheloopcantesttoseeiftherearemorebytesavailableforreading.

5.Afterreadingallthebytesfromthefileandprocessingthemcalltheclose()functiontoclosethefile.SeeListing5-2foranexampleofhowtoreadinafilefromaSDcardandprintthecontentstothescreenusingtheSerialMonitor.Listing5-2.ReadingfilesfromtheSDcard.FileTempFile;//ReadsinfileandprintsittoscreenviaSerialTempFile=SD.open(“testfile.txt”);if(TempFile){//readfromthefileuntilthere’snothingelseinit:while(TempFile.available()){Serial.write(TempFile.read());}//closethefile:TempFile.close();}else{//ErroropeningfileSerial.print(“Erroropening“);}

RemoveexistingFilesfromtheSDCard

WhenwritingfilestotheSDcardyoumayneedtosaveoveranexistingfile.However,theopen()commandonlyallowsyoutoopenafileforwritingstartingattheendofthefile.Thereisnooptiontoopenafileforwritingandstartatthebeginningofthefile.So

Page 101: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

weneedtotestfortheexistenceofthefilewewanttowriteandremoveitifitexists.

Inordertowriteoveranexistingfileweneedto:1.ChecktoseeifthatfilealreadyexistsusingtheSD.exists()functionwiththeinputparameterofthefilenamewewanttowrite.2.IftheSD.exists()functionreturnstruethenyouneedtocalltheSD.remove()functionwiththefilenameasaparametertoremovethefilefromtheSDcard.3.NowyouareabletowritethenewfileusingthecodeinListing5-1.SeeListing5-3foranexampleofhowtotestfortheexistenceofafileandthenremoveitifitdoesexist.Listing5-3.RemovingexistingfilesfromtheSDcard//Checkiffilealreadyexistsandremoveitifitdoesif(SD.exists(“testfile.txt”)){SD.remove(“testfile.txt”);}

Page 102: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

OverviewofArduino’sI2CInterface

ThissectioncoverstheArudino’sI2Cinterface.Ifirstcovertheinput/outputpinsfortheI2ContheArduinoandtheov7670camera.Then,Ishowyouhowtoinitialize,writeto,andreadfromaI2CdeviceusingtheArduino.

I2CInput/OutputInterfacePins

TheI2CinterfaceconsistsoftwopinstheSDApinwhichhandlesdataandtheSCLpinwhichprovidestheclock.OntheArduinoMega,SDAisdigitalpin20andSCLis21.SeeFigure5-5wheretheSDAandSCLpinsarecircled.

Figure5-5.ArduinoMega2560withSDAandSCLpinscircledOntheov7670cameratheSIOCishookedtotheArduino’sSCLpin.TheSIODisconnectedtotheArduino’sSDApin.SeeFigure5-6forthelocationofthesepinsonthe

camera. Figure5-6.ov7670camerawithSIOCandSIODpinscircled

UsinganI2CdevicewithArduino

Page 103: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

ArduinohasbuiltinsupportfordeviceswithanI2Cbusorcompatiblebussuchastheov7670camera.InthissectionIwillshowyouhowtoinitialize,writedatato,andreaddatafromanI2Cdevice.

InitializinganI2CDevice

InordertouseanI2CdeviceyouneedtofirstinitializetheI2Cbus.YoudothisbyfirstincludingtheWirelibraryintoyoursourcecode.Suchas:#include<Wire.h>ThenyouneedtocalltheWire.begin()functioninthesetup()functiontoinitializetheArduino’sWirelibrarysuchas:voidsetup(){Wire.begin();}

ReadingDatafromaI2CDevice

YoucanreaddatafromanI2Cdeviceby:1.CallingtheWire.beginTransmission()functionwiththeaddressoftheI2Cdevice.

2.CallingtheWire.write()functionwiththeregisteraddresstoreadfrom.3.CallingtheWire.endTransmission()functiontosendtheregisteraddresstotheI2Cdevice(inthiscasethecamera)andtoendthetransmissionwhichreleasescontroloftheI2Cbus.

4.CallingtheWire.requestFrom()functiontorequestoneormorebytesfromtheI2Cdevice.5.WaitingforthebytetobecomeavailablebycontinuallycallingWire.available()untilabytebecomesavailable.6.WhenabytebecomeavailablethenreadinthebytebycallingWire.read().SeeListing5-4forafunctionthatreadsandreturnsasinglebytefromanI2CdevicewithinputaddressRegisterAddress.Listing5-4.TheReadRegisterValue()functionbyteReadRegisterValue(intRegisterAddress){bytedata=0;Wire.beginTransmission(OV7670_I2C_ADDRESS);Wire.write(RegisterAddress);Wire.endTransmission();Wire.requestFrom(OV7670_I2C_ADDRESS,1);while(Wire.available()<1);data=Wire.read();returndata;}

WritingDatatoaI2CDevice

YoucanwritedatatoanI2Cdeviceby:

Page 104: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

1.CallingtheWire.beginTransmission()functionwiththeaddressoftheI2Cdevice.2.CallingtheWire.write()functionwiththestartingaddressoftheregisterorregisterstowriteto.

3.CallingtheWire.write(pData,size)functionwiththearrayofdatainbytesthatistobewrittenandthenumberofbytesthataretobewritten.4.CallingtheWire.endTransmission()functionwhichendsthetransmissionandsendsthebytestotheI2Cdevice.OncecompletedastopmessageissentandtheI2Cbusisreleased.

Listing5-5showshowthisisdoneinthehandsonexamplepresentedlaterinthischapter.Listing5-5.TheOV7670Write()functionintOV7670Write(intstart,constbyte*pData,intsize){intn,error;Wire.beginTransmission(OV7670_I2C_ADDRESS);n=Wire.write(start);//writethestartaddressif(n!=1){return(I2C_ERROR_WRITING_START_ADDRESS);}n=Wire.write(pData,size);//writedatabytesif(n!=size){return(I2C_ERROR_WRITING_DATA);}error=Wire.endTransmission(true);//releasetheI2C-busif(error!=0){return(error);}return0;//return:noerror}

Page 105: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

HandsonExample:TestingtheI2CInterfacewiththeOV7670Camera

InthishandsonexamplewearegoingtorunanI2CscannerwhichdetectsifthereareanyI2CdevicesconnectedtotheArduino.IfthereareI2Cdevicesconnectedthenitwillprintoutthedevice’saddress.Thisisagoodwaytochecktoseeifyourov7670cameracanbedetectedbytheArduino.

FirstyouwillneedtodownloadtheI2CScannerprogramat:http://playground.arduino.cc/Main/I2cScannerwhichisconsideredthemainofficialsitefortheArduino.TheI2CscannerprogramcontinuallyscanstheI2Cbusfordevicesby:1.CallingtheWire.beginTransmission()functionwithanaddressintherangeof1through127.2.CallingtheWire.endTransmission()functionandtestingthereturnerrorcode.3.Ifthereturnerrorcodeis0whichmeanstherewasnoerrorthenavalidI2Cdevicehasbeendetected.4.IfavalidI2Cdevicehasbeendetectedthenprintoutthedevice’saddresstothescreenusingtheSerialMonitor.SeeListing5-6forthecompleteI2Cscannercode.Listing5-6.I2Cdevicescanner#include<Wire.h>voidsetup(){Wire.begin();Serial.begin(9600);Serial.println(“\nI2CScanner”);}voidloop(){byteerror,address;intnDevices;Serial.println(“Scanning…”);nDevices=0;for(address=1;address<127;address++){//Thei2c_scannerusesthereturnvalueof//theWrite.endTransmisstiontoseeif//adevicedidacknowledgetotheaddress.Wire.beginTransmission(address);error=Wire.endTransmission();if(error==0){Serial.print(“I2Cdevicefoundataddress0x”);if(address<16)Serial.print(“0”);Serial.print(address,HEX);

Page 106: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

Serial.println(”!”);nDevices++;}elseif(error==4){Serial.print(“Unknowerrorataddress0x”);if(address<16)Serial.print(“0”);Serial.println(address,HEX);}}if(nDevices==0)Serial.println(“NoI2Cdevicesfound\n”);elseSerial.println(“done\n”);delay(5000);//wait5secondsfornextscan}

UsingtheScannerProgram

1.ConnecttheArduinoMega2560’sSDAdigitalpin20totheSIODpinonthecamera.2.ConnecttheArduinoMega2560’sSCLdigitalpin21totheSIOCpinonthecamera.3.Connectthe3.3voltpinontheArduinotothe3.3voltpinonthecamera.4.ConnecttheGNDpinontheArduinototheGNDpinonthecamera.5.UploadtheI2CScannercodetoyourArduino.6.HittheSerialMonitorbuttonandwaitforthetesttorun.

7.TheprogramshouldeventuallydetectthecamerathatisattachedtotheI2Cbusandreportthattheaddressofthecamerais0x21.Youwillneedtousethisaddresstoreadandwritedatausingthecamera.

Page 107: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

OverviewoftheOmnivisionov7670FIFOCameraImageCaptureSoftware

InthissectionIdiscussindetailthesoftwarethatIcreatedtocaptureimagesfromthecamera.IfirstdiscussinitializingtheprogramandIthencoverthemainprogramloop.TheinitializationinvolvesinitializingthecameraandSDcard.ThemainprogramloopconsistsofprocessingvarioususerinputsfromtheSerialMonitorandperformingcertainactionsbasedontheseuserinputs.

InitializingtheProgram

ThefirstthingthatisruninanArduinoprogramistheuserdefinedcodelocatedinthesetup()function.Inthissetup()functionthefollowingactionsaretaken:1.TheserialmonitorisinitializedsothatyouwillbeabletogivethecameraandSDcardcommands.2.Theov7670cameraisinitializedandsetupforuseintakingphotos.3.TheSDcardisinitialized.TheSerialMonitorisinitializedby:1.CallingtheSerial.begin()functionwith9600astherateofcommunication.Also,makesureyouhavetheSerialMonitorsetto9600aswellwhichalsoshouldbethedefault.2.PrintingoutatextmessagetotheSerialMonitorindicatingthattheprogramhasstarted.SeeListing5-7.Listing5-7.InitializingtheSerialMonitor//InitializeSerialSerial.begin(9600);Serial.println(F(“ArduinoSERIAL_MONITOR_CONTROLLEDCAMERA…Usingov7670Camera”));Serial.println();

CameraInitialization

Thecameraisinitializedby:1.CallingtheWire.begin()functionwhichinitializesthelibrarythathandlesinputandoutputusingthecamera’sI2Cinterface2.TheResetCameraRegisters()functioniscalledwhichresetsallthecamera’sregisterstotheirdefaultvalue.3.TheReadRegisters()functioniscalledwhichreadsandprintsoutsomekeycameraregistersusefulfordebuggingandcheckingifthecameraisworking.4.TheSetupCamera()camerafunctioncallstheInitializeOV7670Camera()functiontopreparethecamerafortakingphotos.SeeListing5-8.Listing5-8.Initializingthecamera//SetuptheOV7670CameraforuseintakingstillphotosWire.begin();Serial.println(F(“–––––––––—CameraRegisters–––––––––-“));

Page 108: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

ResetCameraRegisters();ReadRegisters();Serial.println(F(“–––––––––––––––––––––––––”));SetupCamera();Serial.println(F(“FINISHEDINITIALIZINGCAMERA…”));Serial.println();Serial.println();TheResetCameraRegisters()functionsetsallthecameraregistersby:

1.CallingtheReadRegisterValue()function.ThisissometimesneededinordertoreliablywriteavaluetoaregisterbasedonexperimentsIhavedone.Thisismostlikelyabugintheov7670.SeeListing5-4foramoredetailedexplanationofthisfunction.

2.CallingtheOV7670WriteReg(COM7,COM7_VALUE_RESET)functionwithCOM7astheregisterthatyouwanttowritetoandtheCOM7_VALUE_RESETvalueasthevaluetowriteasthesecondparameter.

3.CallingtheParseI2CResult()functionwhichconvertstheresultofthepreviousI2Coperationintoaneasilyreadabletextstringthatisprintedout.4.Callingdelay(500)whichdelaystheprogramexecutionfor500millisecondsinordertoallowtimeforallthecameraregisterstoreset.SeeListing5-9.Listing5-9.TheResetCameraRegisters()functionvoidResetCameraRegisters(){//ResetCameraRegisters//Readingneededtopreventerrorbytedata=ReadRegisterValue(COM7);intresult=OV7670WriteReg(COM7,COM7_VALUE_RESET);Stringsresult=ParseI2CResult(result);Serial.println(“RESETTINGALLREGISTERSBYSETTINGCOM7REGISTERto0x80:”+sresult);//Delayatleast500msdelay(500);}

TheOV7670WriteReg(intreg,bytedata)writesdatatoaregisterregbycallingtheOV7670Write()functionandreturnstheerrorstateoftheoperation.SeeListing5-5foramoredetailedexplanationofOV7670Write()function.SeeListing5-10forthecodefortheOV7670WriteReg()function.

Listing5-10.OV7670WriteReg()functionintOV7670WriteReg(intreg,bytedata){interror;error=OV7670Write(reg,&data,1);return(error);}TheParseI2Cresult()functionconvertstheintegerresultfromanI2Cread/writeoperationintoaneasilyreadabletextstringwhichisreturnedtothecaller.SeeListing5-11.

Page 109: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

Listing5-11.ParseI2Cresult()functionStringParseI2CResult(intresult){Stringsresult=””;switch(result){case0:sresult=“I2COperationOK…”;break;caseI2C_ERROR_WRITING_START_ADDRESS:sresult=“I2C_ERROR_WRITING_START_ADDRESS”;break;caseI2C_ERROR_WRITING_DATA:sresult=“I2C_ERROR_WRITING_DATA”;break;caseDATA_TOO_LONG:sresult=“DATA_TOO_LONG”;break;caseNACK_ON_TRANSMIT_OF_ADDRESS:sresult=“NACK_ON_TRANSMIT_OF_ADDRESS”;break;caseNACK_ON_TRANSMIT_OF_DATA:sresult=“NACK_ON_TRANSMIT_OF_DATA”;break;caseOTHER_ERROR:sresult=“OTHER_ERROR”;break;default:sresult=“I2CERRORTYPENOTFOUND…”;break;}returnsresult;}TheReadRegisters()functionreadsinsomeofthekeyregistersandprintsthemouttothescreen.SeeListing5-12.Listing5-12.TheReadRegisters()functionvoidReadRegisters(){bytedata=0;data=ReadRegisterValue(CLKRC);Serial.print(F(“CLKRC=“));data=ReadRegisterValue(COM7);Serial.print(F(“COM7=“));Serial.println(data,HEX);data=ReadRegisterValue(COM3);Serial.print(F(“COM3=“));Serial.println(data,HEX);data=ReadRegisterValue(COM14);

Page 110: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

Serial.print(F(“COM14=“));Serial.println(data,HEX);data=ReadRegisterValue(SCALING_XSC);Serial.print(F(“SCALING_XSC=“));Serial.println(data,HEX);data=ReadRegisterValue(SCALING_YSC);Serial.print(F(“SCALING_YSC=“));Serial.println(data,HEX);data=ReadRegisterValue(SCALING_DCWCTR);Serial.print(F(“SCALING_DCWCTR=“));Serial.println(data,HEX);data=ReadRegisterValue(SCALING_PCLK_DIV);Serial.print(F(“SCALING_PCLK_DIV=“));Serial.println(data,HEX);data=ReadRegisterValue(SCALING_PCLK_DELAY);Serial.print(F(“SCALING_PCLK_DELAY=“));Serial.println(data,HEX);//defaultvalueDdata=ReadRegisterValue(TSLB);Serial.print(F(“TSLB(YUVOrder-HigherBit,Bit[3])=“));Serial.println(data,HEX);//defaultvalue88data=ReadRegisterValue(COM13);Serial.print(F(“COM13(YUVOrder-LowerBit,Bit[1])=“));Serial.println(data,HEX);data=ReadRegisterValue(COM17);Serial.print(F(“COM17(DSPColorBarSelection)=“));Serial.println(data,HEX);data=ReadRegisterValue(COM4);Serial.print(F(“COM4(workswithCOM17)=“));Serial.println(data,HEX);data=ReadRegisterValue(COM15);Serial.print(F(“COM15(COLORFORMATSELECTION)=“));Serial.println(data,HEX);data=ReadRegisterValue(COM11);Serial.print(F(“COM11(NightMode)=“));data=ReadRegisterValue(COM8);Serial.print(F(“COM8(ColorControl,AWB)=“));Serial.println(data,HEX);data=ReadRegisterValue(HAECC7);Serial.print(F(“HAECC7(AECAlgorithmSelection)=“));Serial.println(data,HEX);data=ReadRegisterValue(GFIX);Serial.print(F(“GFIX=“));Serial.println(data,HEX);//WindowOutputdata=ReadRegisterValue(HSTART);Serial.print(F(“HSTART=“));

Page 111: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

Serial.println(data,HEX);data=ReadRegisterValue(HSTOP);Serial.print(F(“HSTOP=“));Serial.println(data,HEX);data=ReadRegisterValue(HREF);Serial.print(F(“HREF=“));Serial.println(data,HEX);data=ReadRegisterValue(VSTRT);Serial.print(F(“VSTRT=“));data=ReadRegisterValue(VSTOP);Serial.print(F(“VSTOP=“));Serial.println(data,HEX);data=ReadRegisterValue(VREF);Serial.print(F(“VREF=“));Serial.println(data,HEX);}TheInitializeOV7670Camera()setsupthecamerasothatitcanbecontrolledbytheArduino.Thefunctiondoesthefollowing:1.SetstheWRSTpinontheArduinofordigitaloutput.2.SetstheRRSTpinontheArduinofordigitaloutput.3.SetstheWENpinontheArduinothatisconnectedtotheWRpinonthecamerafordigitaloutput.4.SetstheVSYNCpinontheArduinofordigitalinput.Inputfromthispinisusedfordeterminingwhenanimageshouldbecaptured.5.SetstheRCLKpinontheArduinofordigitaloutput.6.SetstheD0-D7pinsontheArduinofordigitalinput.Thesearethepinsthatwillreadintheimagedataonebyteatatime.7.Callsthedelay()functiontomadesurethecamerahashadenoughtimetofullypowerup.8.CallsthePulseLowEnabledPin(WRST,DurationMicroSecs)functionwhichsendsalowpulsethatresetsthewritebufferpointerontheFIFO.9.CallsthedigitalWrite(RRST,LOW)functiontowriteaLOWvaluetoresetthereadFIFOpointer.10.CallsthePulsePin(RCLK,DurationMicroSecs)functionthatpulsestheRCLKpinsothatthecamerawillrecognizethattheRRSTvalueisLOWandresetstheFIFOreadpointer.

11.CallsthedigitalWrite(RRST,HIGH)functiontorestoretheRRSTvalueofHIGHorfalsesincethispinislowenabled(lowistrue,highisfalse).ThusthereadpointerwillnotresetwhichRCLKispulsed.

SeeListing5-13.Listing5-13.TheInitializeOV7670Camera()functionvoidInitializeOV7670Camera(){Serial.println(F(“InitializingOV7670Camera…”));//SetWRSTto0andRRSTto0,0.1msafterpoweron.

Page 112: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

intDurationMicroSecs=1;//SetmodeforpinswitherinputoroutputpinMode(WRST,OUTPUT);pinMode(RRST,OUTPUT);pinMode(WEN,OUTPUT);pinMode(VSYNC,INPUT);pinMode(RCLK,OUTPUT);//FIFORamoutputpinspinMode(DO7,INPUT);pinMode(DO6,INPUT);pinMode(DO5,INPUT);pinMode(DO4,INPUT);pinMode(DO3,INPUT);pinMode(DO2,INPUT);pinMode(DO1,INPUT);pinMode(DO0,INPUT);//Delay1msdelay(1);PulseLowEnabledPin(WRST,DurationMicroSecs);//NeedtoclockthefifomanuallytogetittoresetdigitalWrite(RRST,LOW);PulsePin(RCLK,DurationMicroSecs);PulsePin(RCLK,DurationMicroSecs);digitalWrite(RRST,HIGH);}

ThePulseLowEnabledPin()functiontakesapinnumberanddurationinmicrosecondsasinputandoutputsapulseofLOWandHIGHvaluesontheinputpinnumberofthespecifiedduration.TheideaistobringthelowenabledpinLOWortrueforashortperiodoftimetoactivateitandthenturnitoffbybringingitbacktoHIGHorfalse.

Note:RememberthatalowenabledpinisoneinwhichaLOWinputactivatesthepinandaHIGHinputdeactivatesthepin.Thatis,thepinisactivewhenLOW.ThePulseLowEnabledPin()functionspecificallydoesthefollowing:1.CallsthedigitalWrite(PinNumber,LOW)functionandwritesaLOWvaluetothepinnumberPinNumber.2.CallsthedelayMicroseconds(DurationMicroSecs)functionandhaltstheexecutionoftheprogramforDurationMicroSecsmicroseconds.3.CallsthedigitalWrite(PinNumber,HIGH)functionandwritesaHIGHvaluetothepinnumberPinNumber.4.CallsthedelayMicroseconds(DurationMicroSecs)functionandhaltstheexecutionoftheprogramforDurationMicroSecsmicroseconds.SeeListing5-14.Listing5-14.ThePulseLowEnabledPin()functionvoidPulseLowEnabledPin(intPinNumber,intDurationMicroSecs){//ForLowEnabledPins,0=onand1=off

Page 113: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

digitalWrite(PinNumber,LOW);//SetsthepinondelayMicroseconds(DurationMicroSecs);//PausesforDurationMicroSecsmicrosecondsdigitalWrite(PinNumber,HIGH);//SetsthepinoffdelayMicroseconds(DurationMicroSecs);//PausesforDurationMicroSecsmicroseconds}ThePulsePin()functioncreatesapulsebysettingapinHIGHforaperiodoftimewhichactivatesthepinandthensettingthepinbacktoaLOWvaluewhichdeactivatesthepin.Note:ThePulsePin()functionassumesapinwhereaHIGHvalueactivatesthepinandaLOWvaluedeactivatesthepin.Thatis,thepinisactivewhenHIGH.SpecificallythePulsePin()functiondoesthefollowing:1.CallsthedigitalWrite(PinNumber,HIGH)functionthatsetsapintoaHIGHvalue.2.CallsthedelayMicroseconds(DurationMicroSecs)functionthathaltstheexecutionoftheprogramforDurationMicroSecsmicroseconds.3.CallsthedigitalWrite(PinNumber,LOW)functionthatsetsapintoaLOWvalue.4.CallsthedelayMicroseconds(DurationMicroSecs)functionthathaltsexecutionoftheprogramforDurationMicroSecsmicroseconds.SeeListing5-15.Listing5-15.ThePulsePin()functionvoidPulsePin(intPinNumber,intDurationMicroSecs){digitalWrite(PinNumber,HIGH);//SetsthepinondelayMicroseconds(DurationMicroSecs);//PausesforDurationMicroSecsmicrosecondsdigitalWrite(PinNumber,LOW);//SetsthepinoffdelayMicroseconds(DurationMicroSecs);//PausesforDurationMicroSecsmicroseconds}

SDCardInitialization

Wearedonenowinitializingthecamera.ThenextthingweneedtoinitializeistheSDcard.InordertoinitializetheSDcardweneedto:

1.CallthepinMode(HardwareSSPin,OUTPUT)functionsettingpin53whichisthehardwareslaveselectpintoOUTPUT.ThismustbedoneeventhoughwearenotusingitbecausetheSDlibraryrequiresit.

2.CalltheSD.begin(chipSelect)functionwiththechipSelectpinthatcanbeusedtoenableordisabletheSDcardreader.3.IfthereturnvalueisfalsethentheSDcardwasnotsuccessfullyinitialized.Otherwise,thecardhasbeensuccessfullyinitializedforuse.SeeListing5-16.Listing5-16.InitializingtheSDcard//InitializeSDCardSerial.print(F(“\nInitializingSDcard…”));pinMode(HardwareSSPin,OUTPUT);//changethisto53onamegaif(!SD.begin(chipSelect)){Serial.println(F(“Initializationfailed…/nThingstocheck:”));

Page 114: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

Serial.println(F(“-Isacardisinserted?”));Serial.println(F(“-Isyourwiringcorrect?”));Serial.println(F(“-DidyouchangethechipSelectpintomatchyourshieldormodule?”));return;}else{Serial.println(F(“Wiringiscorrectandacardispresent…”));}

MainCommandLoop

Afterthesetup()functioniscalledtheloop()functioniscalledrepeatedlyuntiltheArduinoisresetortheArduinoispoweredoff.Theloop()functiondoesthefollowing:1.ReadsinuserinputfromtheSerialMonitor.2.ExecutevariouscameraorSDcardfunctionsbasedontheuserinput

ReadingintheUserInput

TheBUFFERLENGTHvariablerepresentsthelengthofthebufferthatholdsthecharacterstobereadin.TheIncomingBytecharacterarrayactuallyholdstheuserinputdata.TheRawCommandLineholdstheStringvalueoftheuserinputdata.Theuserinputloopisawhileloopthatdoesthefollowing:1.CallstheSerial.available()functionandifthereisuserinputtobereadinwhichmeansthereturnvalue>0thenreadintheuserinput.

2.Readsintheuser’sinputbycallingtheSerial.readBytesUntil(‘\n’,IncomingByte,BUFFERLENGTH)function.Thefunctionreadsintheuserinputuntilanewlinecharacterisfound,BUFFERLENGTHnumberofcharactershavebeenreadin,orthefunctiontimesout.ThefunctionreturnstheuserinputcharactersintheIncomingBytecharacterarray.

3.AddseachcharacterintheIncomingBytearraytotheRawCommandLinevariable.4.Breaksprogramexecutionoutoftheinfinitewhileloopsothattheuserinputcanbeprocessed.SeeListing5-17.Listing5-17.Waitingforausercommand.//SerialInputconstintBUFFERLENGTH=255;charIncomingByte[BUFFERLENGTH];//forincomingserialdataStringRawCommandLine=””;//WaitforCommandSerial.println(F(“ReadytoAcceptnewCommand=>“));while(1){if(Serial.available()>0){intNumberCharsRead=Serial.readBytesUntil(‘\n’,IncomingByte,BUFFERLENGTH);

Page 115: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

for(inti=0;i<NumberCharsRead;i++){RawCommandLine+=IncomingByte[i];}break;}}

ProcessingUserInput

Next,theuserinputisprocessed.Processingtheuserinputdoesthefollowing:1.CallstheDisplayHelpMenu()functionif“h”or“help”istheuserinput.2.CallstheDisplayHelpCommandsParams()functionif“helpcamera”istheuserinput.3.CallstheDisplayCurrentCommand()functionif“d”istheuserinput.4.Commandsthecameratotakeaphotowiththecurrentcameracommandandparametersif“t”istheuserinput.5.CallstheReadPrintFile(“TEST.TXT”)functionwith“test.txt”asafilenameif“testread”istheuserinput.6.WritesatestfiletotheSDcardif“testwrite”istheuserinput.7.Changesthecameracommandand/orparametersifacameracommandorparameteristheuserinput.8.ResetstheRawCommandLinewhichholdstheuserinputtoempty.SeeListing5-18.Listing5-18.ProcessingUserInput//PrintoutthecommandfromAndroidSerial.print(F(“RawCommandfromSerialMonitor:“));Serial.println(RawCommandLine);if((RawCommandLine==“h”)||(RawCommandLine==“help”)){DisplayHelpMenu();}elseif(RawCommandLine==“helpcamera”)DisplayHelpCommandsParams();}elseif(RawCommandLine==“d”){DisplayCurrentCommand();}elseif(RawCommandLine==“t”){//TakePhotoSerial.println(F(“\nGoingtotakephotowithcurrentcommand:”));DisplayCurrentCommand();//TakePhoto

Page 116: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

ExecuteCommand(Command);Serial.println(F(“PhotoTakenandSavedtoArduinoSDCARD…”));StringTestfile=CreatePhotoFilename();Serial.print(F(“ImageOutputFilename:”));Serial.println(Testfile);PhotoTakenCount++;}elseif(RawCommandLine==“testread”){ReadPrintFile(“TEST.TXT”);}elseif(RawCommandLine==“testwrite”){CheckRemoveFile(“TEST.TXT”);WriteFileTest(“TEST.TXT”);}else{Serial.println(F(“Changingcommandorparametersaccordingtoyourinput:”));//ParseCommandLineandSetCommandLineElements//ParseRawCommandintoCommandandParametersParseRawCommand(RawCommandLine);//DisplaynewchangedcameracommandwithparametersDisplayCurrentCommand();}//ResetCommandLineRawCommandLine=””;Serial.println();Serial.println();TheMainHelpMenu

TheDisplayHelpMenu()functiondisplaysthemainhelpmenufortheprogram.ThetextisprintingtothescreenusingtheSerial.print()orSerial.println()functions.AlsotheF()indicatesthatthetextisstoredinsidetheArduino’sflashmemory.

SeeListing5-19.Listing5-19.DisplayHelpMenu()voidDisplayHelpMenu()Serial.println(F(“……………..HelpMenu………………”));Serial.println(F(“d-DisplayCurrentCameraCommand”));Serial.println(F(“t-TakePhotographusingcurrentCommandandParameters”));Serial.println(F(“testread-TestsreadingfilesfromtheSDCardbyreadingandprintigthecontentsoftest.txt”));Serial.println(F(“testwrite-TestswritingfilestoSDCard”));Serial.println(F(“helpcamera-DisplaysCamera’sCommandsandParameters”));Serial.println();Serial.println();

Page 117: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

}CameraHelpMenu

TheDisplayHelpCommandsParams()functiondisplaysthehelpmenuforthecamerashowingthesetofcommandsthatcanchangethecamera’sresolutionaswellasparametersfortheframespersecondsettings,autowhitebalancesettings,automaticexposuresettings,YUVMatrixsettings,denoisesettings,edgeenhancementsetttings,andautomaticblacklevelcalibrationsettings.

SeeListing5-20.Listing5-20.CameraHelpMenuvoidDisplayHelpCommandsParams(){Serial.println(F(“…….HelpMenuCameraCommands/Params……….”));Serial.println(F(“ResolutionChangeCommands:VGA,VGAP,QVGA,QQVGA”));Serial.println(F(“FPSParameters:ThirtyFPS,NightMode”));Serial.println(F(“AWBParameters:SAWB,AAWB”));Serial.println(F(“AECParameters:AveAEC,HistAEC”));Serial.println(F(“YUVMatrixParameters:YUVMatrixOn,YUVMatrixOff”));Serial.println(F(“DenoiseParameters:DenoiseYes,DenoiseNo”));Serial.println(F(“EdgeEnchancement:EdgeYes,EdgeNo”));Serial.println(F(“AutomaticBlackLevelCalibration:AblcON,AblcOFF”));Serial.println();Serial.println();}DisplayingtheCurrentCameraCommand

TheDisplayCurrentCommand()functiondisplaysthecurrentsettingsforthecameracommandandcameraparameters.ThevariablesthatholdthecameracommandandcameraparametersareStringvariablesandareshowninListing5-21withtheirdefaultvalues.

Listing5-21.CameracommandandparametervariablesStringCommand=“QQVGA”;StringFPSParam=“ThirtyFPS”;StringAWBParam=“SAWB”;StringAECParam=“HistAEC”;StringYUVMatrixParam=“YUVMatrixOn”;StringDenoiseParam=“DenoiseNo”;StringEdgeParam=“EdgeNo”;StringABLCParam=“AblcON”;

TheactualDisplayCurrentCommand()functionisshowninListing5-22.ThefunctionconsistsofSerial.print()andSerial.println()statementsthatprintsoutthecameracommandandthenthevaluesofthecameraparameters.

Listing5-22.TheDisplayCurrentCommand()functionvoidDisplayCurrentCommand(){

Page 118: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

//PrintoutCommandandParametersSerial.println(F(“CurrentCommand:”));Serial.print(F(“Command:“));Serial.println(Command);Serial.print(F(“FPSParam:“));Serial.println(FPSParam);Serial.print(F(“AWBParam:“));Serial.println(AWBParam);Serial.print(F(“AECParam:“));Serial.println(AECParam);Serial.print(F(“YUVMatrixParam:“));Serial.println(YUVMatrixParam);Serial.print(F(“DenoiseParam:“));Serial.println(DenoiseParam);Serial.print(F(“EdgeParam:“));Serial.println(EdgeParam);Serial.print(F(“ABLCParam:“));Serial.println(ABLCParam);Serial.println();}TakingaPhotoIftheuserinputis“t”thenaphotoistakenwiththecameraandsavedtotheSDcard.Inordertotakeaphotowiththecamerathefollowingstepsaretaken:1.TheDisplayCurrentCommand()functioniscalledtodisplaythecurrentcameracommandandcameraparametersintheSerialMonitor.2.TheExecuteCommand(Command)functioniscalledwiththecameracommandasaparameterinordertotaketheactualphoto.

3.TheCreatePhotoFilename()functioniscalledtoretrievethefilenamethattheimagewassavedunderandthenprintsthistothescreen.4.IncreasesthePhotoTakenCountvariablethatkeepstrackofthenumberofphotostaken.

SeeListing5-23.Listing5-23.Takingaphotoif(RawCommandLine==“t”){//TakePhotoSerial.println(F(“\nGoingtotakephotowithcurrentcommand:”));DisplayCurrentCommand();//TakePhotoExecuteCommand(Command);Serial.println(F(“PhotoTakenandSavedtoArduinoSDCARD…”));StringTestfile=CreatePhotoFilename();Serial.print(F(“ImageOutputFilename:”));Serial.println(Testfile);PhotoTakenCount++;}

TheExecuteCommand()functionusestheResolutionvariabletochecktoseeifthe

Page 119: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

camera’scurrentresolutionsettingsneedtobechanged.Ifitdoesthenafunctioniscalledtosetupthecameraaccordingtothenewresolution.

ThecurrentresolutionofthecameraisheldintheResolutionvariablethatisofResolutionTypeandbydefaultissettoNone.Theenumeratedtypesare:•VGA-VGAresolutionandRawBayerformat•VGAP-VGAresolutionandRawBayerformatbuttheimageisalsoprocessedthroughtheDigitalSignalProcessor•QVGA-QVGAresolutionandYUVimageformat•QQVGA-QQVGAresolutionandYUVimageformat

•None-whichmeansthatthecamerahasnotbeensettoanyspecificresolutionyetSeeListing5-24.

Listing5-24.TheResolutionvariableenumResolutionType{VGA,VGAP,QVGA,QQVGA,None};ResolutionTypeResolution=None;TheExecuteCommand()functionsetsthecameratothecorrectresolutionandparameters,thentakesthephotoandthensavesittoanSDCard.TheExecuteCommand()functiondoesthefollowing:

1.IfthecommandisVGAthenthecameratakesaVGAphoto.IfthecurrentresolutionisnotVGAorifparametershavechangedthenthecameraregistersarereset,thecurrentresolutionissettoVGA,theSetupOV7670ForVGARawRGB()functioniscalledtoactuallysetuptheVGAmode,andtheReadRegisters()functioniscalledtoreadkeyregistersandprintthemouttoscreen.

2.IfthecommandisVGAPthenthecameratakesaprocessedVGAphoto.IfthecurrentresolutionisnotVGAPorifparametershavechangedthenthecameraregistersarereset,thecurrentresolutionissettoVGAP,theSetupOV7670ForVGAProcessedBayerRGB()functioniscalledtoactuallysetuptheprocessedVGAmode,andtheReadRegisters()functioniscalledtoreadkeyregistersandprintthemouttoscreen.

3.IfthecommandisQVGAthenthecameratakesaQVGAphoto.IfthecurrentresolutionisnotQVGAorifparametershavechangedthenthecurrentresolutionissettoQVGA,theSetupOV7670ForQVGAYUV()functioniscalledtoactuallysetuptheQVGAmode,andtheReadRegisters()functioniscalledtoreadkeyregistersandprintthemouttoscreen.

4.IfthecommandisQQVGAthenthecameratakesaQQVGAphoto.IfthecurrentresolutionisnotQQVGAorifparametershavechangedthenthecurrentresolutionissettoQQVGA,theSetupOV7670ForQQVGAYUV()functioniscalledtoactuallysetupthe

Page 120: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

QQVGAmode,andtheReadRegisters()functioniscalledtoreadkeyregistersandprintthemouttoscreen.

5.Thedelay(100)functioniscalledtohalttheprogramexecutionfor100millisecondstoallowtimeforthecamera’sregisterstobecompletelyupdatedafterbeingset.6.TheTakePhoto()functioniscalledthatactuallyisresponsiblefortakingthephotoandsavingittoanSDcard.SeeListing5-25.Listing5-25TheExecuteCommand()functionvoidExecuteCommand(StringCommand){//SetupCameraforVGA,QVGA,orQQVGAModesif(Command==“VGA”){Serial.println(F(“TakingaVGAPhoto…”));if(Resolution!=VGA){//IfcurrentresolutionisnotQQVGAthensetcameraforQQVGAResetCameraRegisters();Resolution=VGA;SetupOV7670ForVGARawRGB();Serial.println(F(“–––––––––—CameraRegisters–––––––––-“));ReadRegisters();Serial.println(F(“–––––––––––––––––––––––––”));}}elseif(Command==“VGAP”){Serial.println(F(“TakingaVGAPPhoto…”));if(Resolution!=VGAP){//IfcurrentresolutionisnotVGAPthensetcameraforVGAPResetCameraRegisters();Resolution=VGAP;SetupOV7670ForVGAProcessedBayerRGB();Serial.println(F(“–––––––––—CameraRegisters–––––––––-“));ReadRegisters();Serial.println(F(“–––––––––––––––––––––––––”));}}elseif(Command==“QVGA”){Serial.println(F(“TakingaQVGAPhoto…”));if(Resolution!=QVGA){//IfcurrentresolutionisnotQQVGAthensetcameraforQQVGAResolution=QVGA;

Page 121: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

SetupOV7670ForQVGAYUV();Serial.println(F(“–––––––––—CameraRegisters–––––––––-“));ReadRegisters();Serial.println(F(“–––––––––––––––––––––––––”));}}elseif(Command==“QQVGA”){Serial.println(F(“TakingaQQVGAPhoto…”));if(Resolution!=QQVGA){//IfcurrentresolutionisnotQQVGAthensetcameraforQQVGAResolution=QQVGA;SetupOV7670ForQQVGAYUV();Serial.println(F(“–––––––––—CameraRegisters–––––––––-“));ReadRegisters();Serial.println(F(“–––––––––––––––––––––––––”));}}else{Serial.print(F(“Thecommand“));Serial.print(Command);Serial.println(F(”isnotrecognized…”));}//Delayforregisterstosettledelay(100);//TakePhotoTakePhoto();}TheSetupOV7670ForVGARawRGB()functionsetstheov7670camerafortheoutputofarawRGBBayerimageinVGAresolution.TheSetupOV7670ForVGARawRGB()functionspecificallydoesthefollowing:1.SetsthePHOTO_WIDTHvariablethatrepresentsthewidthoftheoutputimageto640.Thisvariableislaterusedtoreadintheimagedatafromthecamera’smemory.2.SetsthePHOTO_HEIGHTvariablethatrepresentstheheightoftheoutputimageto480.Thisvariableislaterusedtoreadintheimagedatafromthecamera’smemory.3.SetsthePHOTO_BYTES_PER_PIXELthatrepresentsthebytesperpixeloftheoutputimageto1.Thisvariableislaterusedtoreadintheimagedatafromthecamera’smemory.4.Thewidth,height,andbytesperpixeloftheoutputimagearethenprintedtothescreenontheSerialMonitor.

5.TheVGAscreenresolutionmodeisthenactivatedbysettingvaluesforthecameraregistersbycallingtheOV7670WriteReg()functionforeachregisterneededwiththeassociatednewvalueandthenParseI2CResult(result)iscalledwiththeresultofthewriteoperation.Thisreturnsatexterrorstatusmessagethatisthenprintedout.Theregistersthatneedtobesetare:

Page 122: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

1.CLKRC2.COM73.COM34.COM145.SCALING_XSC6.SCALING_YSC7.SCALING_DCWCTR8.SCALING_PCLK_DIV9.SCALING_PCLK_DELAY10.COM17

6.CallstheSetCameraFPSMode()functiontodetermineifthecameraframeratewillbe30framespersecondoraNightModewheretheframeratevarieswiththeamountoflightavailable.

7.CallstheSetCameraAEC()functionthatsetsthetypeofautomaticexposurecontrolthatiseitheraveragebasedorhistogrambased.

8.CallstheOV7670WriteReg(0xB0,0x8c)functionandsetsaregisterthatislistedintheofficialdocumentationasunusedor“reserved”whichis0xB0tothevalueof0x8C.Thisisdonetocorrectthecolorsthatshouldberedbutappearasgreenwithoutthisregisteradjustment.

9.CallstheSetCameraSaturationControl()functionthatsetsthesaturationcontrolforthecamera.10.CallstheSetupCameraArrayControl()functionthatsetsthecamera’sarraycontrolregisters.11.CallstheSetupCameraADCControl()functionthatsetsthecamera’sanalogtodigitalconverterrelatedregisters.12.CallstheSetupCameraABLC()functionthatsetstheautomaticblacklevelcorrection.13.CallstheOV7670WriteReg()functionandsetsthewindowoutputregisterswhicharethefollowingtovaluesfortheVGAscreenresolution.1.HSTART2.HSTOP3.HREF4.VSTRT5.VSTOP6.VREFSeeListing5-26.Listing5-26.TheSetupOV7670ForVGARawRGB()functionvoidSetupOV7670ForVGARawRGB(){intresult=0;Stringsresult=””;Serial.println(F(“–––––––––SettingCameraforVGA(RawRGB)–––––––––”));PHOTO_WIDTH=640;PHOTO_HEIGHT=480;PHOTO_BYTES_PER_PIXEL=1;Serial.print(F(“PhotoWidth=“));

Page 123: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

Serial.println(PHOTO_WIDTH);Serial.print(F(“PhotoHeight=“));Serial.println(PHOTO_HEIGHT);Serial.print(F(“BytesPerPixel=“));Serial.println(PHOTO_BYTES_PER_PIXEL);//BasicRegistersresult=OV7670WriteReg(CLKRC,CLKRC_VALUE_VGA);sresult=ParseI2CResult(result);Serial.print(F(“CLKRC:“));Serial.println(sresult);result=OV7670WriteReg(COM7,COM7_VALUE_VGA);//result=OV7670WriteReg(COM7,COM7_VALUE_VGA_COLOR_BAR);sresult=ParseI2CResult(result);Serial.print(F(“COM7:“));Serial.println(sresult);result=OV7670WriteReg(COM3,COM3_VALUE_VGA);sresult=ParseI2CResult(result);Serial.print(F(“COM3:“));Serial.println(sresult);result=OV7670WriteReg(COM14,COM14_VALUE_VGA);sresult=ParseI2CResult(result);Serial.print(F(“COM14:“));Serial.println(sresult);result=OV7670WriteReg(SCALING_XSC,SCALING_XSC_VALUE_VGA);sresult=ParseI2CResult(result);Serial.print(F(“SCALING_XSC:“));Serial.println(sresult);result=OV7670WriteReg(SCALING_YSC,SCALING_YSC_VALUE_VGA);sresult=ParseI2CResult(result);Serial.print(F(“SCALING_YSC:“));Serial.println(sresult);result=OV7670WriteReg(SCALING_DCWCTR,SCALING_DCWCTR_VALUE_VGA);sresult=ParseI2CResult(result);Serial.print(F(“SCALING_DCWCTR:“));Serial.println(sresult);result=OV7670WriteReg(SCALING_PCLK_DIV,SCALING_PCLK_DIV_VALUE_VGA);sresult=ParseI2CResult(result);Serial.print(F(“SCALING_PCLK_DIV:“));Serial.println(sresult);result=OV7670WriteReg(SCALING_PCLK_DELAY,SCALING_PCLK_DELAY_VALUE_VGA);sresult=ParseI2CResult(result);Serial.print(F(“SCALING_PCLK_DELAY:“));Serial.println(sresult);//COM17-DSPColorBarEnable/Disable

Page 124: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

//COM17_VALUE0x08//ActivateColorBarforDSP//result=OV7670WriteReg(COM17,COM17_VALUE_AEC_NORMAL_COLOR_BAR);result=OV7670WriteReg(COM17,COM17_VALUE_AEC_NORMAL_NO_COLOR_BAR);sresult=ParseI2CResult(result);Serial.print(F(“COM17:“));Serial.println(sresult);//SetAdditionalParameters//SetCameraFramespersecondSetCameraFPSMode();//SetCameraAutomaticExposureControlSetCameraAEC();//NeededColorCorrection,greentoredresult=OV7670WriteReg(0xB0,0x8c);Serial.print(F(“SettingB0UNDOCUMENTEDregisterto0x84:=“));Serial.println(sresult);//SetCameraSaturationSetCameraSaturationControl();//SetupCameraArrayControlSetupCameraArrayControl();//SetADCControlSetupCameraADCControl();//SetAutomaticBlackLevelCalibrationSetupCameraABLC();Serial.println(F(“………..SettingCameraWindowOutputParameters……..”));//ChangeWindowOutputparametersaftercustomscalingresult=OV7670WriteReg(HSTART,HSTART_VALUE_VGA);sresult=ParseI2CResult(result);Serial.print(F(“HSTART:“));Serial.println(sresult);result=OV7670WriteReg(HSTOP,HSTOP_VALUE_VGA);sresult=ParseI2CResult(result);Serial.print(F(“HSTOP:“));Serial.println(sresult);result=OV7670WriteReg(HREF,HREF_VALUE_VGA);Serial.print(F(“HREF:“));Serial.println(sresult);result=OV7670WriteReg(VSTRT,VSTRT_VALUE_VGA);sresult=ParseI2CResult(result);Serial.print(F(“VSTRT:“));Serial.println(sresult);result=OV7670WriteReg(VSTOP,VSTOP_VALUE_VGA);sresult=ParseI2CResult(result);Serial.print(F(“VSTOP:“));Serial.println(sresult);result=OV7670WriteReg(VREF,VREF_VALUE_VGA);

Page 125: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

sresult=ParseI2CResult(result);Serial.print(F(“VREF:“));Serial.println(sresult);}TheSetCameraFPSMode()functionsetsthenumberofFPS(framespersecondthatthecameracaptures)forthecameraby:1.CallingtheSetupCameraFor30FPS()functioniftheFPSParamvariableissetto“ThirtyFPS”.2.CallingtheSetupCameraNightMode()functioniftheFPSParamvariableissetto“NightMode”.SeeListing5-27.Listing5-27.TheSetCameraFPSMode()functionvoidSetCameraFPSMode(){//SetFPSforCameraif(FPSParam==“ThirtyFPS”){SetupCameraFor30FPS();}elseif(FPSParam==“NightMode”){SetupCameraNightMode();}}TheSetupCameraFor30FPS()functionsetsthecameratocaptureimagescontinuouslyattherateof30framespersecond.Theregistersthataresetare:1.CLKRC2.DBLV3.EXHCH4.EXHCL5.DM_LNL6.DM_LNH7.COM11SeeListing5-28.Listing5-28.SetupCameraFor30FPSvoidSetupCameraFor30FPS(){intresult=0;Stringsresult=””;Serial.println(F(“………..SettingCamerato30FPS……..”));result=OV7670WriteReg(CLKRC,CLKRC_VALUE_30FPS);Serial.print(F(“CLKRC:“));Serial.println(sresult);result=OV7670WriteReg(DBLV,DBLV_VALUE_30FPS);sresult=ParseI2CResult(result);

Page 126: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

Serial.print(F(“DBLV:“));Serial.println(sresult);result=OV7670WriteReg(EXHCH,EXHCH_VALUE_30FPS);sresult=ParseI2CResult(result);Serial.print(F(“EXHCH:“));Serial.println(sresult);result=OV7670WriteReg(EXHCL,EXHCL_VALUE_30FPS);sresult=ParseI2CResult(result);Serial.print(F(“EXHCL:“));Serial.println(sresult);result=OV7670WriteReg(DM_LNL,DM_LNL_VALUE_30FPS);sresult=ParseI2CResult(result);Serial.print(F(“DM_LNL:“));Serial.println(sresult);result=OV7670WriteReg(DM_LNH,DM_LNH_VALUE_30FPS);sresult=ParseI2CResult(result);Serial.print(F(“DM_LNH:“));Serial.println(sresult);result=OV7670WriteReg(COM11,COM11_VALUE_30FPS);sresult=ParseI2CResult(result);Serial.print(F(“COM11:“));Serial.println(sresult);}TheSetupCameraNightMode()functionsetsthecameratonightmodewheretheframespeedisadjustedautomaticallytomatchtheamountoflightintheenvironment.Thecameraregisterssetare:1.CLKRC2.COM11SeeListing5-29.Listing5-29.TheSetupCameraNightMode()functionvoidSetupCameraNightMode(){intresult=0;Stringsresult=””;Serial.println(F(“………TurningNIGHTMODEON……..”));result=OV7670WriteReg(CLKRC,CLKRC_VALUE_NIGHTMODE_AUTO);sresult=ParseI2CResult(result);Serial.print(F(“CLKRC:“));Serial.println(sresult);result=OV7670WriteReg(COM11,COM11_VALUE_NIGHTMODE_AUTO);sresult=ParseI2CResult(result);Serial.print(F(“COM11:“));Serial.println(sresult);TheSetCameraAEC()functionsetstheautomaticexposurecontrolmethodtoeithertheaveragemethodorthehistogrammethodbasedonthevalueoftheAECParam.Thefunctioncallseither:

Page 127: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

1.SetupCameraAverageBasedAECAGC()iftheaveragemethodisselectedbytheuseror2.SetCameraHistogramBasedAECAGC()ifthehistogrammethodisselectedbytheuser.SeeListing5-30.Listing5-30.TheSetCameraAEC()functionvoidSetCameraAEC(){//ProcessAECif(AECParam==“AveAEC”){//SetCamera’sAverageAEC/AGCParametersSetupCameraAverageBasedAECAGC();}elseif(AECParam==“HistAEC”){//SetCameraAECalgorithimtoHistogramSetCameraHistogramBasedAECAGC();}}TheSetupCameraAverageBasedAECAGC()functionsetstheautomaticexposurecontrolfortheaveragemethod.Thecameraregistersaffectedare:1.AEW2.AEB3.VPT4.HAECC7Alltheseregistersaresetandtheresultisreturnedandprintedout.SeeListing5-31.Listing5-31.TheSetupCameraAverageBasedAECAGC()functionvoidSetupCameraAverageBasedAECAGC(){intresult=0;Stringsresult=””;Serial.println(F(“––––—SettingCameraAverageBasedAEC/AGCRegisters–––––”));result=OV7670WriteReg(AEW,AEW_VALUE);sresult=ParseI2CResult(result);Serial.print(F(“AEW:“));Serial.println(sresult);result=OV7670WriteReg(AEB,AEB_VALUE);sresult=ParseI2CResult(result);Serial.print(F(“AEB:“));Serial.println(sresult);result=OV7670WriteReg(VPT,VPT_VALUE);sresult=ParseI2CResult(result);Serial.print(F(“VPT:“));Serial.println(sresult);result=OV7670WriteReg(HAECC7,HAECC7_VALUE_AVERAGE_AEC_ON);

Page 128: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

sresult=ParseI2CResult(result);Serial.print(F(“HAECC7:“));Serial.println(sresult);TheSetCameraHistogramBasedAECAGC()functionsetstheautomaticexposurecontroltothehistogrammethod.Theregistersaffectedare:1.AEW2.AEB3.HAECC14.HAECC25.HAECC36.HAECC47.HAECC58.HAECC69.HAECC7Alltheseregistersaresetandtheresultisreturnedandprintout.SeeListing5-32.Listing5-32.TheSetCameraHistogramBasedAECAGC()functionvoidSetCameraHistogramBasedAECAGC(){intresult=0;Stringsresult=””;Serial.println(F(“––––—SettingCameraHistogramBasedAEC/AGCRegisters–––––”));result=OV7670WriteReg(AEW,AEW_VALUE);sresult=ParseI2CResult(result);Serial.print(F(“AEW:“));Serial.println(sresult);result=OV7670WriteReg(AEB,AEB_VALUE);sresult=ParseI2CResult(result);Serial.print(F(“AEB:“));Serial.println(sresult);result=OV7670WriteReg(HAECC1,HAECC1_VALUE);sresult=ParseI2CResult(result);Serial.print(F(“HAECC1:“));Serial.println(sresult);result=OV7670WriteReg(HAECC2,HAECC2_VALUE);sresult=ParseI2CResult(result);Serial.print(F(“HAECC2:“));Serial.println(sresult);result=OV7670WriteReg(HAECC3,HAECC3_VALUE);sresult=ParseI2CResult(result);Serial.print(F(“HAECC3:“));Serial.println(sresult);result=OV7670WriteReg(HAECC4,HAECC4_VALUE);sresult=ParseI2CResult(result);Serial.print(F(“HAECC4:“));Serial.println(sresult);result=OV7670WriteReg(HAECC5,HAECC5_VALUE);

Page 129: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

sresult=ParseI2CResult(result);Serial.print(F(“HAECC5:“));Serial.println(sresult);result=OV7670WriteReg(HAECC6,HAECC6_VALUE);sresult=ParseI2CResult(result);Serial.print(F(“HAECC6:“));Serial.println(sresult);result=OV7670WriteReg(HAECC7,HAECC7_VALUE_HISTOGRAM_AEC_ON);sresult=ParseI2CResult(result);Serial.print(F(“HAECC7:“));Serial.println(sresult);}TheSetCameraSaturationControl()functioncontrolsthelevelofsaturationintheimagebysettingthesaturationcontrolregisterSATCTR.SeeListing5-33.Listing5-33.TheSetCameraSaturationControl()functionvoidSetCameraSaturationControl(){intresult=0;Stringsresult=””;Serial.println(F(“………..SettingCameraSaturationLevel……..”));result=OV7670WriteReg(SATCTR,SATCTR_VALUE);sresult=ParseI2CResult(result);Serial.print(F(“SATCTR:“));Serial.println(sresult);}TheSetupCameraArrayControl()functionsetsthecameraarrayregisters:1.CHLFand2.ARBLMSeeListing5-34.Listing5-34.TheSetupCameraArrayControl()functionvoidSetupCameraArrayControl()intresult=0;Stringsresult=””;Serial.println(F(“………..SettingCameraArrayControl……..”));result=OV7670WriteReg(CHLF,CHLF_VALUE);sresult=ParseI2CResult(result);Serial.print(F(“CHLF:“));Serial.println(sresult);result=OV7670WriteReg(ARBLM,ARBLM_VALUE);sresult=ParseI2CResult(result);Serial.print(F(“ARBLM:“));Serial.println(sresult);}TheSetupCameraADCControl()functionsetsupthecamera’sanalogtodigitalconversioncontrolsrelatingtotheconversionoftheimagefromanalogtodigital.TheSetupCameraADCControl()functionaffectscameraregisters:1.ADCCTR12.ADCCTR2

Page 130: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

3.ADC4.ACOM5.OFON

TheregistersarewrittentousingtheOV7670WriteReg()function,thereturnerrorstatusisprocessedusingtheParseI2CResult()functionandtheresultsareprintedouttothescreen.SeeListing5-35.

Listing5-35.TheSetupCameraADCControl()functionvoidSetupCameraADCControl()intresult=0;Stringsresult=””;Serial.println(F(“………..SettingCameraADCControl……..”));result=OV7670WriteReg(ADCCTR1,ADCCTR1_VALUE);sresult=ParseI2CResult(result);Serial.print(F(“ADCCTR1:“));Serial.println(sresult);result=OV7670WriteReg(ADCCTR2,ADCCTR2_VALUE);sresult=ParseI2CResult(result);Serial.print(F(“ADCCTR2:“));Serial.println(sresult);result=OV7670WriteReg(ADC,ADC_VALUE);sresult=ParseI2CResult(result);Serial.print(F(“ADC:“));Serial.println(sresult);result=OV7670WriteReg(ACOM,ACOM_VALUE);sresult=ParseI2CResult(result);Serial.print(F(“ACOM:“));Serial.println(sresult);result=OV7670WriteReg(OFON,OFON_VALUE);sresult=ParseI2CResult(result);Serial.print(F(“OFON:“));Serial.println(sresult);}TheSetupCameraABLC()functionsetstheautomaticblacklevelcalibrationbasedonthevalueofABLCParam.Thecameraregistersaffectedare:1.ABLC12.THL_ST

TheregistersarewrittentousingtheOV7670WriteReg()function,theerrorstatusissentto

TheregistersarewrittentousingtheOV7670WriteReg()function,theerrorstatusissentto36.

Listing5-36.TheSetupCameraABLC()functionvoidSetupCameraABLC(){intresult=0;Stringsresult=””;

Page 131: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

//IfABLCisoffthenreturnotherwise//turnonABLC.if(ABLCParam==“AblcOFF”){return;}Serial.println(F(“……..SettingCameraABLC…….”));result=OV7670WriteReg(ABLC1,ABLC1_VALUE);sresult=ParseI2CResult(result);Serial.print(F(“ABLC1:“));Serial.println(sresult);result=OV7670WriteReg(THL_ST,THL_ST_VALUE);sresult=ParseI2CResult(result);Serial.print(F(“THL_ST:“));Serial.println(sresult);}TheSetupOV7670ForVGAProcessedBayerRGB()functionsetsthecameraforVGAresolutionandthecamera’soutputtoaprocessedBayerRGBimage.TheSetupOV7670ForVGAProcessedBayerRGB()functiondoesthefollowing:1.TheSetupOV7670ForVGARawRGB()functioniscalledtosetupthecameraforVGAresolution.2.TheregisterCOM7issetwiththevalueforactivatingprocessedBayerRGBasanoutputimage.3.TheregisterTSLBissetwiththevalueneededtocorrectincorrectlydisplayedcolors.4.Theregister0xB0issetwith0x8cinordertocorrectincorrectlydisplayedcolors.5.TheSetupCameraAWB()functioniscalledtosettheautomaticwhitebalanceaccordingtotheuser’sparameters.6.TheSetupCameraDenoiseEdgeEnhancement()functioniscalledtosetthedenoiseandedgeenhancementaccordingtotheuser’sparameters.SeeListing5-37.Listing5-37.TheSetupOV7670ForVGAProcessedBayerRGB()functionvoidSetupOV7670ForVGAProcessedBayerRGB(){intresult=0;Stringsresult=””;//CallBaseforVGARawBayerRGBModeSetupOV7670ForVGARawRGB();Serial.println(F(“––––-SettingCameraforVGA(ProcessedBayerRGB)–––––-“));//Setkeyregisterforselectingprocessedbayerrgboutputresult=OV7670WriteReg(COM7,COM7_VALUE_VGA_PROCESSED_BAYER);//result=OV7670WriteReg(COM7,COM7_VALUE_VGA_COLOR_BAR);sresult=ParseI2CResult(result);Serial.print(F(“COM7:“));Serial.println(sresult);result=OV7670WriteReg(TSLB,0x04);sresult=ParseI2CResult(result);Serial.print(F(“InitializingTSLBregisterresult=“));

Page 132: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

Serial.println(sresult);//NeededColorCorrection,greentoredresult=OV7670WriteReg(0xB0,0x8c);sresult=ParseI2CResult(result);Serial.print(F(“SettingB0UNDOCUMENTEDregisterto0x84:=“));Serial.println(sresult);//SetCameraAutomaticWhiteBalanceSetupCameraAWB();//DenoiseandEdgeEnhancementSetupCameraDenoiseEdgeEnhancement();}TheSetupCameraAWB()functionsetsthetypeofautomaticwhitebalancetoeithersimpleoradvanceddependingontheAWBParamvariable.TheSetupCameraAWB()functiondoesthefollowing:

1.IftheAWBParamis“SAWB”thentheSetupCameraSimpleAutomaticWhiteBalance()functioniscalledfollowedbytheSetupCameraGain()function.2.IftheAWBParamis“AAWB”thentheSetupCameraAdvancedAutomaticWhiteBalance()functioniscalledfollowedbytheSetupCameraAdvancedAutoWhiteBalanceConfig()andthentheSetupCameraGain()functioniscalled.

SeeListing5-38.Listing5-38.TheSetupCameraAWB()functionvoidSetupCameraAWB(){//SetAWBModeif(AWBParam==“SAWB”){//SetSimpleAutomaticWhiteBalanceSetupCameraSimpleAutomaticWhiteBalance();//OK//SetGainConfigSetupCameraGain();}elseif(AWBParam==“AAWB”){//SetAdvancedAutomaticWhiteBalanceSetupCameraAdvancedAutomaticWhiteBalance();//ok//SetCameraAutomaticWhiteBalanceConfigurationSetupCameraAdvancedAutoWhiteBalanceConfig();//ok//SetGainConfigSetupCameraGain();}}TheSetupCameraSimpleAutomaticWhiteBalance()functionsetstheautomaticwhitebalancetypetosimpleby:

Page 133: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

1.SettingtheCOM8registerusingtheOV7670WriteReg()functionandthenprintingouttheresultofthewriteoperationafteritisconvertedintotextusingtheParseI2Cresult()function.

2.SettingtheAWBCTR0registerusingtheOV7670WriteReg()functionandthenprintingouttheresultofthewriteoperationafteritisconvertedintotextusingtheParseI2Cresult()function.

SeeListing5-39.Listing5-39.TheSetupCameraSimpleAutomaticWhiteBalance()functionvoidSetupCameraSimpleAutomaticWhiteBalance(){intresult=0;Stringsresult=””;Serial.println(F(“………..SettingCameratoSimpleAWB……..”));//COM8result=OV7670WriteReg(COM8,COM8_VALUE_AWB_ON);sresult=ParseI2CResult(result);Serial.print(F(“COM8(0x13):“));Serial.println(sresult);//AWBCTR0result=OV7670WriteReg(AWBCTR0,AWBCTR0_VALUE_NORMAL);sresult=ParseI2CResult(result);Serial.print(F(“AWBCTR0ControlRegister0(0x6F):“));Serial.println(sresult);}TheSetupCameraGain()functionsetsthegainforthecameraby:

1.SettingtheCOM9registerusingtheOV7670WriteReg()functionandprintingoutthesuccessorfailurestatusofthewriteoperation.2.SettingtheBLUEregisterusingtheOV7670WriteReg()functionandprintingoutthesuccessorfailurestatusofthewriteoperation.

3.SettingtheREDregisterusingtheOV7670WriteReg()functionandprintingoutthesuccessorfailurestatusofthewriteoperation.4.SettingtheGGAINregisterusingtheOV7670WriteReg()functionandprintingoutthesuccessorfailurestatusofthewriteoperation.5.SettingtheCOM16registerusingtheOV7670WriteReg()functionandprintingoutthesuccessorfailurestatusofthewriteoperation.SeeListing5-40.Listing5-40.TheSetupCameraGain()functionvoidSetupCameraGain(){intresult=0;Stringsresult=””;Serial.println(F(“………..SettingCameraGain……..”));//SetMaximumGainresult=OV7670WriteReg(COM9,COM9_VALUE_4XGAIN);

Page 134: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

sresult=ParseI2CResult(result);Serial.print(F(“COM9:“));Serial.println(sresult);//SetBlueGainresult=OV7670WriteReg(BLUE,BLUE_VALUE);sresult=ParseI2CResult(result);Serial.print(F(“BLUEGAIN:“));Serial.println(sresult);//SetRedGainresult=OV7670WriteReg(RED,RED_VALUE);sresult=ParseI2CResult(result);Serial.print(F(“REDGAIN:“));Serial.println(sresult);//SetGreenGainresult=OV7670WriteReg(GGAIN,GGAIN_VALUE);sresult=ParseI2CResult(result);Serial.print(F(“GREENGAIN:“));Serial.println(sresult);//EnableAWBGainresult=OV7670WriteReg(COM16,COM16_VALUE);sresult=ParseI2CResult(result);Serial.print(F(“COM16(ENABLEGAIN):“));Serial.println(sresult);}TheSetupCameraAdvancedAutomaticWhiteBalance()functionsetstheautomaticwhitebalancesettingtotypeAdvancedby:1.SettingtheCOM8registerusingtheOV7670WriteReg()functionandprintingoutthesuccessorfailurestatusofthewriteoperation.2.SettingtheAWBCTR0registerusingtheOV7670WriteReg()functionandprintingoutthesuccessorfailurestatusofthewriteoperation.SeeListing5-41.Listing5-41.TheSetupCameraAdvancedAutomaticWhiteBalance()functionvoidSetupCameraAdvancedAutomaticWhiteBalance(){intresult=0;Stringsresult=””;Serial.println(F(“………..SettingCameratoAdvancedAWB……..”));//AGC,AWB,andAECEnableresult=OV7670WriteReg(0x13,0xE7);sresult=ParseI2CResult(result);Serial.print(F(“COM8(0x13):“));Serial.println(sresult);//AWBCTR0result=OV7670WriteReg(0x6f,0x9E);sresult=ParseI2CResult(result);Serial.print(F(“AWBControlRegister0(0x6F):“));Serial.println(sresult);

Page 135: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

}

TheSetupCameraAdvancedAutoWhiteBalanceConfig()functionsetssomemoreregistersthatarerequiredfortheadvancedautomaticwhitebalancebysettingthefollowingregistersanddisplayingthesuccessorfailurestatusofeachwriteoperation:

1.AWBC12.AWBC23.AWBC34.AWBC45.AWBC56.AWBC67.AWBC78.AWBC89.AWBC910.AWBC1011.AWBC1112.AWBC1213.AWBCTR314.AWBCTR215.AWBCTR1SeeListing5-42.Listing5-42.TheSetupCameraAdvancedAutoWhiteBalanceConfig()functionvoidSetupCameraAdvancedAutoWhiteBalanceConfig(){intresult=0;Stringsresult=””;Serial.println(F(“………..SettingCameraAdvancedAutoWhiteBalanceConfigs……..”));result=OV7670WriteReg(AWBC1,AWBC1_VALUE);sresult=ParseI2CResult(result);Serial.print(F(“AWBC1:“));Serial.println(sresult);result=OV7670WriteReg(AWBC2,AWBC2_VALUE);sresult=ParseI2CResult(result);Serial.print(F(“AWBC2:“));Serial.println(sresult);result=OV7670WriteReg(AWBC3,AWBC3_VALUE);sresult=ParseI2CResult(result);Serial.print(F(“AWBC3:“));Serial.println(sresult);result=OV7670WriteReg(AWBC4,AWBC4_VALUE);sresult=ParseI2CResult(result);Serial.print(F(“AWBC4:“));Serial.println(sresult);result=OV7670WriteReg(AWBC5,AWBC5_VALUE);sresult=ParseI2CResult(result);Serial.print(F(“AWBC5:“));Serial.println(sresult);

Page 136: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

result=OV7670WriteReg(AWBC6,AWBC6_VALUE);sresult=ParseI2CResult(result);Serial.print(F(“AWBC6:“));Serial.println(sresult);result=OV7670WriteReg(AWBC7,AWBC7_VALUE);sresult=ParseI2CResult(result);Serial.print(F(“AWBC7:“));Serial.println(sresult);result=OV7670WriteReg(AWBC8,AWBC8_VALUE);sresult=ParseI2CResult(result);Serial.print(F(“AWBC8:“));Serial.println(sresult);result=OV7670WriteReg(AWBC9,AWBC9_VALUE);sresult=ParseI2CResult(result);Serial.print(F(“AWBC9:“));Serial.println(sresult);result=OV7670WriteReg(AWBC10,AWBC10_VALUE);sresult=ParseI2CResult(result);Serial.print(F(“AWBC10:“));Serial.println(sresult);result=OV7670WriteReg(AWBC11,AWBC11_VALUE);sresult=ParseI2CResult(result);Serial.print(F(“AWBC11:“));Serial.println(sresult);result=OV7670WriteReg(AWBC12,AWBC12_VALUE);sresult=ParseI2CResult(result);Serial.print(F(“AWBC12:“));Serial.println(sresult);result=OV7670WriteReg(AWBCTR3,AWBCTR3_VALUE);sresult=ParseI2CResult(result);Serial.print(F(“AWBCTR3:“));Serial.println(sresult);result=OV7670WriteReg(AWBCTR2,AWBCTR2_VALUE);sresult=ParseI2CResult(result);Serial.print(F(“AWBCTR2:“));Serial.println(sresult);result=OV7670WriteReg(AWBCTR1,AWBCTR1_VALUE);sresult=ParseI2CResult(result);Serial.print(F(“AWBCTR1:“));Serial.println(sresult);

TheSetupCameraDenoiseEdgeEnhancement()functionperformsdenoisingandedgeenhancementonanimagedependingonthevaluesoftheDenoiseParamandEdgeParamvariables.

TheSetupCameraDenoiseEdgeEnhancement()functiondoesthefollowing:

1.IftheDenoiseParamis“DenoiseYes”andtheEdgeParamis“EdgeYes”thenboththe

Page 137: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

denoiseandedgeenhancementimageoptionshavebeenselectedbytheuser.TheSetupCameraDenoise()functioniscalledtosetthecameraregistersthatwilldenoisetheimage.TheSetupCameraEdgeEnhancement()functioniscalledtosettoturnontheedgeenhancementfunctionofthecamera.TheCOM16registerissetthroughtheOV7670WriteReg()functionwiththevaluethatwillturnboththedenoiseandedgeenhancementfeatureson.Specificallythevalueisinthe#defineCOM16_VALUE_DENOISE_ON__EDGE_ENHANCEMENT_ON__AWBGAIN_ON.

2.IftheDenoiseParamis“DenoiseYes”andtheEdgeParamis“EdgeNo”thentheuserhasselecteddenoisingbuthasturnedoffedgeenhancement.TheSetupCameraDenoise()functionisthencalledtoturnonthecamera’sdenoisingfunction.TheCOM16registerissetthroughtheOV7670WriteReg()function.ThevaluetobewrittentotheCOM16registerisfromthe#defineCOM16_VALUE_DENOISE_ON__EDGE_ENHANCEMENT_OFF__AWBGAIN_ON.

3.IftheDenoiseParamis“DenoiseNo”andtheEdgeParamis“EdgeYes”thentheuserhasselectedtoturndenoisingoffandtoturnonedgeenhancement.ThentheSetupCameraEdgeEnhancement()functioniscalledthatturnsontheedgeenhancement.TheCOM16registerissetwiththefunctionOV7670WriteReg()withthevaluethatspecifiedbythe#defineCOM16_VALUE_DENOISE_OFF__EDGE_ENHANCEMENT_ON__AWBGAIN_ON

ImportantNote:theCOM16containsthecontrolbitsforboththedenoiseandedgeenhanceoperations.Bit5controlstheedgeenhancementandbit4controlsthedenoiseoperation.

SeeListing5-42.Listing5-42.TheSetupCameraDenoiseEdgeEnhancement(0functionvoidSetupCameraDenoiseEdgeEnhancement(){intresult=0;Stringsresult=””;if((DenoiseParam==“DenoiseYes”)&&(EdgeParam==“EdgeYes”)){SetupCameraDenoise();SetupCameraEdgeEnhancement();result=OV7670WriteReg(COM16,COM16_VALUE_DENOISE_ON__EDGE_ENHANCEMENT_ON__AWBGAIN_ON);sresult=ParseI2CResult(result);Serial.print(F(“COM16:“));Serial.println(sresult);}elseif((DenoiseParam==“DenoiseYes”)&&(EdgeParam==“EdgeNo”)){SetupCameraDenoise();result=OV7670WriteReg(COM16,

Page 138: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

COM16_VALUE_DENOISE_ON__EDGE_ENHANCEMENT_OFF__AWBGAIN_ON);sresult=ParseI2CResult(result);Serial.print(F(“COM16:“));Serial.println(sresult);}elseif((DenoiseParam==“DenoiseNo”)&&(EdgeParam==“EdgeYes”)){SetupCameraEdgeEnhancement();result=OV7670WriteReg(COM16,COM16_VALUE_DENOISE_OFF__EDGE_ENHANCEMENT_ON__AWBGAIN_ON);sresult=ParseI2CResult(result);Serial.print(F(“COM16:“));Serial.println(sresult);}TheSetupCameraDenoise()functionsetsthecamera’sregisterssothatthedenoisefunctionisactivatedforimageprocessing.Thefunctionsetsthefollowingcameraregisters:1.DNSTH2.REG77SeeListing5-43.Listing5-43.TheSetupCameraDenoise()functionvoidSetupCameraDenoise(){intresult=0;Stringsresult=””;Serial.println(F(“………..SettingCameraDenoise……..”));result=OV7670WriteReg(DNSTH,DNSTH_VALUE);sresult=ParseI2CResult(result);Serial.print(F(“DNSTH:“));Serial.println(sresult);result=OV7670WriteReg(REG77,REG77_VALUE);sresult=ParseI2CResult(result);Serial.print(F(“REG77:“));Serial.println(sresult);}TheSetupCameraEdgeEnhancement()functionactivatesthecamera’simageedgeenhancementby:1.SettingtheEDGEcameraregister.2.SettingtheREG75cameraregister.3.SettingtheREG76cameraregister.SeeListing5-44.Listing5-44.TheSetupCameraEdgeEnhancement()functionvoidSetupCameraEdgeEnhancement(){intresult=0;

Page 139: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

Stringsresult=””;Serial.println(F(“………..SettingCameraEdgeEnhancement……..”));result=OV7670WriteReg(EDGE,EDGE_VALUE);sresult=ParseI2CResult(result);Serial.print(F(“EDGE:“));Serial.println(sresult);result=OV7670WriteReg(REG75,REG75_VALUE);sresult=ParseI2CResult(result);Serial.print(F(“REG75:“));Serial.println(sresult);result=OV7670WriteReg(REG76,REG76_VALUE);sresult=ParseI2CResult(result);Serial.print(F(“REG76:“));Serial.println(sresult);}TheSetupOV7670ForQVGAYUV()functionsetsupthecameratotakepicturesinQVGAresolutionandoutputtheimageinYUVformat.TheSetupOV7670ForQVGAYUV()doesthefollowing:

1.ThePHOTO_WIDTHvariablewhichrepresentsthewidthinpixelsofthecapturedcameraimageissetto320.Thisvariableisusedinreadinginthecapturedimagefromthecamera’sFIFOmemory.

2.ThePHOTO_HEIGHTvariablewhichrepresentstheheightinpixelsofthecapturedcameraimageissetto240.Thisvariableisusedinreadinginthecapturedimagefromthecamera’sFIFOmemory.

3.ThePHOTO_BYTES_PER_PIXELvariablewhichrepresentsthenumberofbytesperpixelofthecapturedimageissetto2.Thisvariableisusedinreadinginthecapturedimagefromthecamera’sFIFOmemory.

4.TheCLKRCcameraregisterisset.5.TheCOM7cameraregisterisset.6.TheCOM3cameraregisterisset.7.TheCOM14cameraregisterisset.8.TheSCALING_XSCcameraregisterisset.9.TheSCALING_YSCcameraregisterisset.10.TheSCALING_DCWCTRcameraregisterisset.11.TheSCALING_PCLK_DIVcameraregisterisset.12.TheSCALING_PCLK_DELAYcameraregisterisset.13.TheTSLBcameraregisterisset.14.TheCOM13cameraregisterisset.15.TheCOM17cameraregisterisset.16.TheSetCameraFPSMode()functionsetstheframespersecondforthecamerabasedonuserselections.17.TheSetCameraAEC()functionsetstheautomaticexposurecontroltypeofthecamerabasedonuserselections.18.TheSetupCameraAWB()functionsetstheautomaticwhitebalancecontrolsofthe

Page 140: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

camerabasedonuserselections.19.TheSetupCameraUndocumentedRegisters()functionsetstheundocumentedregistersthatareneededforthecameratooperatecorrectly.20.IftheYUVMatrixParamis“YUVMatrixOn”thentheSetCameraColorMatrixYUV()functionthatsetsthecolormatrixspecificallyforaYUVimageiscalled.21.TheSetCameraSaturationControl()functionsetsthecamera’ssaturationcontrol.22.TheSetupCameraDenoiseEdgeEnhancement()functionsetsthecamera’sdenoiseandedgeenhancementimageprocessingfunctions.

23.TheSetupCameraArrayControl()functionsetsthecamera’sarraycontrols.24.TheSetupCameraADCControl()functionsetsthecamera’sanalogtodigitalconversioncontrols.

25.TheSetupCameraABLC()functionsetsthecamera’sautomaticblacklevelcalibrationsettings.26.Thecamera’soutputwindowregistersaresettoQVGAvalues.Theregistersare:1.HSTART2.HSTOP3.HREF4.VSTRT5.VSTOP6.VREFSeeListing5-45.Listing5-45.TheSetupOV7670ForQVGAYUV()functionvoidSetupOV7670ForQVGAYUV(){intresult=0;Stringsresult=””;Serial.println(F(“–––––––––SettingCameraforQVGA(YUV)–––––––––”));PHOTO_WIDTH=320;PHOTO_HEIGHT=240;PHOTO_BYTES_PER_PIXEL=2;Serial.print(F(“PhotoWidth=“));Serial.println(PHOTO_WIDTH);Serial.print(F(“PhotoHeight=“));Serial.println(PHOTO_HEIGHT);Serial.print(F(“BytesPerPixel=“));Serial.println(PHOTO_BYTES_PER_PIXEL);//BasicRegistersresult=OV7670WriteReg(CLKRC,CLKRC_VALUE_QVGA);sresult=ParseI2CResult(result);Serial.print(F(“CLKRC:“));Serial.println(sresult);result=OV7670WriteReg(COM7,COM7_VALUE_QVGA);//result=OV7670WriteReg(COM7,COM7_VALUE_QVGA_COLOR_BAR);sresult=ParseI2CResult(result);Serial.print(F(“COM7:“));Serial.println(sresult);

Page 141: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

result=OV7670WriteReg(COM3,COM3_VALUE_QVGA);sresult=ParseI2CResult(result);Serial.print(F(“COM3:“));Serial.println(sresult);result=OV7670WriteReg(COM14,COM14_VALUE_QVGA);sresult=ParseI2CResult(result);Serial.print(F(“COM14:“));Serial.println(sresult);result=OV7670WriteReg(SCALING_XSC,SCALING_XSC_VALUE_QVGA);sresult=ParseI2CResult(result);Serial.print(F(“SCALING_XSC:“));Serial.println(sresult);result=OV7670WriteReg(SCALING_YSC,SCALING_YSC_VALUE_QVGA);sresult=ParseI2CResult(result);Serial.print(F(“SCALING_YSC:“));Serial.println(sresult);result=OV7670WriteReg(SCALING_DCWCTR,SCALING_DCWCTR_VALUE_QVGA);sresult=ParseI2CResult(result);Serial.print(F(“SCALING_DCWCTR:“));Serial.println(sresult);result=OV7670WriteReg(SCALING_PCLK_DIV,SCALING_PCLK_DIV_VALUE_QVGA);sresult=ParseI2CResult(result);Serial.print(F(“SCALING_PCLK_DIV:“));Serial.println(sresult);result=OV7670WriteReg(SCALING_PCLK_DELAY,SCALING_PCLK_DELAY_VALUE_QVGA);sresult=ParseI2CResult(result);Serial.print(F(“SCALING_PCLK_DELAY:“));Serial.println(sresult);//YUVordercontrolchangefromdefaultusewithCOM13result=OV7670WriteReg(TSLB,0x04);sresult=ParseI2CResult(result);Serial.print(F(“TSLB:“));Serial.println(sresult);//COM13result=OV7670WriteReg(COM13,0xC2);//fromYCbCrreferencespecssresult=ParseI2CResult(result);Serial.print(F(“COM13:“));Serial.println(sresult);//COM17-DSPColorBarEnable/Disable//COM17_VALUE0x08//ActivateColorBarforDSP//result=OV7670WriteReg(COM17,COM17_VALUE_AEC_NORMAL_COLOR_BAR);result=OV7670WriteReg(COM17,COM17_VALUE_AEC_NORMAL_NO_COLOR_BAR);

Page 142: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

sresult=ParseI2CResult(result);Serial.print(F(“COM17:“));Serial.println(sresult);//SetAdditionalParameters//SetCameraFramespersecondSetCameraFPSMode();//SetCameraAutomaticExposureControlSetCameraAEC();//SetCameraAutomaticWhiteBalanceSetupCameraAWB();//SetupUndocumentedRegisters-NeededMinimumSetupCameraUndocumentedRegisters();//SetColorMatrixforYUVif(YUVMatrixParam==“YUVMatrixOn”){SetCameraColorMatrixYUV();}//SetCameraSaturationSetCameraSaturationControl();//DenoiseandEdgeEnhancementSetupCameraDenoiseEdgeEnhancement();//SetupCameraArrayControlSetupCameraArrayControl();//SetADCControlSetupCameraADCControl();//SetAutomaticBlackLevelCalibrationSetupCameraABLC();Serial.println(F(“………..SettingCameraWindowOutputParameters……..”));//ChangeWindowOutputparametersaftercustomscalingresult=OV7670WriteReg(HSTART,HSTART_VALUE_QVGA);sresult=ParseI2CResult(result);Serial.print(F(“HSTART:“));Serial.println(sresult);result=OV7670WriteReg(HSTOP,HSTOP_VALUE_QVGA);sresult=ParseI2CResult(result);Serial.print(F(“HSTOP:“));Serial.println(sresult);result=OV7670WriteReg(HREF,HREF_VALUE_QVGA);sresult=ParseI2CResult(result);Serial.print(F(“HREF:“));Serial.println(sresult);result=OV7670WriteReg(VSTRT,VSTRT_VALUE_QVGA);sresult=ParseI2CResult(result);Serial.print(F(“VSTRT:“));Serial.println(sresult);result=OV7670WriteReg(VSTOP,VSTOP_VALUE_QVGA);sresult=ParseI2CResult(result);Serial.print(F(“VSTOP:“));

Page 143: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

Serial.println(sresult);result=OV7670WriteReg(VREF,VREF_VALUE_QVGA);sresult=ParseI2CResult(result);Serial.print(F(“VREF:“));Serial.println(sresult);}

TheSetupCameraUndocumentedRegisters()functionsetstheregister0xB0withthevalue0x84.Thisisanundocumentedregisterthatwaslistedas“reserved”inthemaindocumentation.However,the“OV7670SoftwareApplicationNote”documentspecifiedthisvalueunderthe“ReferenceSettings”sectionunder“YcbCr”.SeeListing5-46.

Listing5-46.TheSetupCameraUndocumentedRegisters()functionvoidSetupCameraUndocumentedRegisters(){intresult=0;Stringsresult=””;Serial.println(F(“………..SettingCameraUndocumentedRegisters……..”));result=OV7670WriteReg(0xB0,0x84);sresult=ParseI2CResult(result);Serial.print(F(“SettingB0UNDOCUMENTEDregisterto0x84:=“));Serial.println(sresult);}TheSetCameraColorMatrixYUV()functionsetsthecolormatrixfortheYUVoutputimagebysettingcameraregisters:1.MTX1thoughMTX62.CONTRAS3.MTXSSeeListing5-47.Listing5-47.TheSetCameraColorMatrixYUV()functionvoidSetCameraColorMatrixYUV(){intresult=0;Stringsresult=””;Serial.println(F(“………..SettingCameraColorMatrixforYUV……..”));result=OV7670WriteReg(MTX1,MTX1_VALUE);sresult=ParseI2CResult(result);Serial.print(F(“MTX1:“));Serial.println(sresult);result=OV7670WriteReg(MTX2,MTX2_VALUE);sresult=ParseI2CResult(result);Serial.print(F(“MTX2:“));Serial.println(sresult);result=OV7670WriteReg(MTX3,MTX3_VALUE);sresult=ParseI2CResult(result);Serial.print(F(“MTX3:“));Serial.println(sresult);result=OV7670WriteReg(MTX4,MTX4_VALUE);sresult=ParseI2CResult(result);

Page 144: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

Serial.print(F(“MTX4:“));Serial.println(sresult);result=OV7670WriteReg(MTX5,MTX5_VALUE);sresult=ParseI2CResult(result);Serial.print(F(“MTX5:“));Serial.println(sresult);result=OV7670WriteReg(MTX6,MTX6_VALUE);sresult=ParseI2CResult(result);Serial.print(F(“MTX6:“));Serial.println(sresult);result=OV7670WriteReg(CONTRAS,CONTRAS_VALUE);sresult=ParseI2CResult(result);Serial.print(F(“CONTRAS:“));Serial.println(sresult);result=OV7670WriteReg(MTXS,MTXS_VALUE);sresult=ParseI2CResult(result);Serial.print(F(“MTXS:“));Serial.println(sresult);}

TheSetupOV7670ForQQVGAYUV()functionsetsthecameratotakephotosinQQVGAresolutionintheYUVformat.MorespecificallytheYUVimageisinyuyvorderwith2bytesperpixelintheimage.

TheSetupOV7670ForQQVGAYUV()functiondoesthefollowing:1.SetsthePHOTO_WIDTHvariablewhichrepresentsthecapturedphoto’swidthto160.Thisvariableisusedtoreadintheimagefromthecamera’sframebufferFIFOmemory.2.SetsthePHOTO_HEIGHTvariablewhichrepresentsthecapturedphoto’sheightto120.Thisvariableisusedtoreadintheimagefromthecamera’sframebufferFIFOmemory.

3.SetthePHOTO_BYTES_PER_PIXELvariablewhichrepresentsthecapturedphoto’sbytesperpixelto2.Thisvariableisusedtoreadintheimagefromthecamera’sframebufferFIFOmemory.

4.Setsthecamera’sCLKRCregister.5.Setsthecamera’sCOM7register.6.Setsthecamera’sCOM3register.7.Setsthecamera’sCOM14register.8.Setsthecamera’sSCALING_XSCregister.9.Setsthecamera’sSCALING_YSCregister.10.Setsthecamera’sSCALING_DCWCTRregister.11.Setsthecamera’sSCALING_PCLK_DIVregister.12.Setsthecamera’sSCALING_PCLK_DELAYregister.13.Setsthecamera’sTSLBregister.14.Setsthecamera’sCOM13register.15.Setsthecamera’sCOM17register.16.TheSetCameraFPSMode()functioniscalledandsetstheframespersecondmodeofthecamera.

Page 145: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

17.TheSetCameraAEC()functioniscalledandsetstheautomaticexposurecontrolsforthecamera.18.TheSetupCameraAWB()functioniscalledandsetsthecamera’sautomaticwhitebalancecontrolsforthecamera.

19.TheSetupCameraUndocumentedRegisters()functioniscalledandsetsthecamera’sundocumentedregistersthatareneededtoproduceacorrectcolorphotooutput.20.iftheYUVMatrixParamvariableis“YUVMatrixOn”thentheSetCameraColorMatrixYUV()functioniscalledtosetthecamera’scolormatrixforYUVoutput.21.TheSetCameraSaturationControl()functioniscalledtosetthesaturationcontrolforthecamera.22.TheSetupCameraDenoiseEdgeEnhancement()functioniscalledtosetthedenoiseandedgeenhancementsettingsbasedonuserselections.23.TheSetupCameraArrayControl()functioniscalledtosetthecamera’sarraycontrol.24.TheSetupCameraADCControl()functioniscalledtosetthecamera’sanalogtodigitalconversioncontrols.25.TheSetupCameraABLC()functioniscalledtosettheautomaticblacklevelcalibrationofthecamera.26.TheoutputwindowdimensionsaresettoQQVGAbymodifyingregisters:1.HSTART2.HSTOP3.HREF4.VSTRT5.VSTOP6.VREFSeeListing5-48.Listing5-48.TheSetupOV7670ForQQVGAYUV()functionvoidSetupOV7670ForQQVGAYUV(){intresult=0;Stringsresult=””;Serial.println(F(“–––––––––SettingCameraforQQVGAYUV–––––––––”));PHOTO_WIDTH=160;PHOTO_HEIGHT=120;PHOTO_BYTES_PER_PIXEL=2;Serial.print(F(“PhotoWidth=“));Serial.println(PHOTO_WIDTH);Serial.print(F(“PhotoHeight=“));Serial.println(PHOTO_HEIGHT);Serial.print(F(“BytesPerPixel=“));Serial.println(PHOTO_BYTES_PER_PIXEL);Serial.println(F(“………..SettingBasicQQVGAParameters……..”));result=OV7670WriteReg(CLKRC,CLKRC_VALUE_QQVGA);sresult=ParseI2CResult(result);Serial.print(F(“CLKRC:“));Serial.println(sresult);

Page 146: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

result=OV7670WriteReg(COM7,COM7_VALUE_QQVGA);//result=OV7670WriteReg(COM7,COM7_VALUE_QQVGA_COLOR_BAR);sresult=ParseI2CResult(result);Serial.print(F(“COM7:“));Serial.println(sresult);result=OV7670WriteReg(COM3,COM3_VALUE_QQVGA);sresult=ParseI2CResult(result);Serial.print(F(“COM3:“));Serial.println(sresult);result=OV7670WriteReg(COM14,COM14_VALUE_QQVGA);sresult=ParseI2CResult(result);Serial.print(F(“COM14:“));Serial.println(sresult);result=OV7670WriteReg(SCALING_XSC,SCALING_XSC_VALUE_QQVGA);sresult=ParseI2CResult(result);Serial.print(F(“SCALING_XSC:“));Serial.println(sresult);result=OV7670WriteReg(SCALING_YSC,SCALING_YSC_VALUE_QQVGA);sresult=ParseI2CResult(result);Serial.print(F(“SCALING_YSC:“));Serial.println(sresult);result=OV7670WriteReg(SCALING_DCWCTR,SCALING_DCWCTR_VALUE_QQVGA);sresult=ParseI2CResult(result);Serial.print(F(“SCALING_DCWCTR:“));Serial.println(sresult);result=OV7670WriteReg(SCALING_PCLK_DIV,SCALING_PCLK_DIV_VALUE_QQVGA);sresult=ParseI2CResult(result);Serial.print(F(“SCALING_PCLK_DIV:“));Serial.println(sresult);result=OV7670WriteReg(SCALING_PCLK_DELAY,SCALING_PCLK_DELAY_VALUE_QQVGA);sresult=ParseI2CResult(result);Serial.print(F(“SCALING_PCLK_DELAY:“));Serial.println(sresult);//YUVordercontrolchangefromdefaultusewithCOM13result=OV7670WriteReg(TSLB,TSLB_VALUE_YUYV_AUTO_OUTPUT_WINDOW_DISABLED);//Workssresult=ParseI2CResult(result);Serial.print(F(“TSLB:“));Serial.println(sresult);//COM13result=OV7670WriteReg(COM13,0xC8);//GammaEnabled,UVAutoAdjOnsresult=ParseI2CResult(result);Serial.print(F(“COM13:“));Serial.println(sresult);

Page 147: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

//COM17-DSPColorBarEnable/Disable//result=OV7670WriteReg(COM17,COM17_VALUE_AEC_NORMAL_COLOR_BAR);result=OV7670WriteReg(COM17,COM17_VALUE_AEC_NORMAL_NO_COLOR_BAR);sresult=ParseI2CResult(result);Serial.print(F(“COM17:“));Serial.println(sresult);//SetAdditionalParameters//SetCameraFramespersecondSetCameraFPSMode();//SetCameraAutomaticExposureControlSetCameraAEC();//SetCameraAutomaticWhiteBalanceSetupCameraAWB();//SetupUndocumentedRegisters-NeededMinimumSetupCameraUndocumentedRegisters();//SetColorMatrixforYUVif(YUVMatrixParam==“YUVMatrixOn”){SetCameraColorMatrixYUV();}//SetCameraSaturationSetCameraSaturationControl();//DenoiseandEdgeEnhancementSetupCameraDenoiseEdgeEnhancement();//SetArrayControlSetupCameraArrayControl();//SetADCControlSetupCameraADCControl();//SetAutomaticBlackLevelCalibrationSetupCameraABLC();Serial.println(F(“………..SettingCameraWindowOutputParameters……..”));//ChangeWindowOutputparametersaftercustomscalingresult=OV7670WriteReg(HSTART,HSTART_VALUE_QQVGA);sresult=ParseI2CResult(result);Serial.print(F(“HSTART:“));Serial.println(sresult);result=OV7670WriteReg(HSTOP,HSTOP_VALUE_QQVGA);sresult=ParseI2CResult(result);Serial.print(F(“HSTOP:“));Serial.println(sresult);result=OV7670WriteReg(HREF,HREF_VALUE_QQVGA);sresult=ParseI2CResult(result);Serial.print(F(“HREF:“));Serial.println(sresult);result=OV7670WriteReg(VSTRT,VSTRT_VALUE_QQVGA);

Page 148: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

sresult=ParseI2CResult(result);Serial.print(F(“VSTRT:“));Serial.println(sresult);result=OV7670WriteReg(VSTOP,VSTOP_VALUE_QQVGA);sresult=ParseI2CResult(result);Serial.print(F(“VSTOP:“));Serial.println(sresult);result=OV7670WriteReg(VREF,VREF_VALUE_QQVGA);sresult=ParseI2CResult(result);Serial.print(F(“VREF:“));Serial.println(sresult);}TheTakePhoto()functiontakesthephotowiththecameraandthensavesittotheSDcard.TheTakePhoto()functiondoesthefollowing:1.Recordsthestarttimeinmillisecondsbycallingthemillis()functionwhichreturnsthenumberofmillisecondssincethecurrentprogramhasbeenstarted.2.TheCaptureOV7670Frame()functioniscalledtotakeaphotowiththeov7670camerawhichissavedinthecamera’sFIFOframebuffermemory.3.TheReadTransmitCapturedFrame()functioniscalledtosavetheimageinthecamera’smemorytoanSDcard.4.TheEndTimevariablerecordstheendtimebycallingthemillis()function.5.TheElapsedTimevariableissettothetimeittakesforaphototobecapturedtothecamera’smemoryandwrittentotheSDcard.SeeListing5-49.Listing5-49.TheTakePhoto()functionvoidTakePhoto(){unsignedlongStartTime=0;unsignedlongEndTime=0;unsignedlongElapsedTime=0;StartTime=millis();CaptureOV7670Frame();ReadTransmitCapturedFrame();EndTime=millis();ElapsedTime=(EndTime-StartTime)/1000;//ConverttosecondsSerial.print(F(“ElapsedTimeforTakingandSendingPhoto(secs)=“));Serial.println(ElapsedTime);}TheCaptureOV7670Frame()functioncapturesanimagefromtheov7670cameraandsavesittothecamera’sFIFOframebuffermemory.TheCaptureOV7670FrameI()functiondoesthefollowing:

1.WaitsfortheVSyncinputfromthecameratopulsetoindicatethestartoftheimagebycallingthepulseIn(VSYNC,HIGH)function.ThepulseIn()functionmakestheArduinowaitforthepinVSYNCtopulsefromLOWtoHIGHandthentoLOWagainbeforereturningandcontinuingprogramexecution.

Page 149: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

2.ResetstheFIFOmemoryframebuffer’swritepointerto0thatrepresentsthebeginningoftheframe.ThePulseLowEnabledPin(WRST,6)functionresetsthewritepointerbysendingaLOWpulsetopinWRSTfor6microseconds.

3.SetstheFIFOwriteenabletoactive(high)sothatimagecanbewrittentoram.ThisisdonebycallingthedigitalWrite(WEN,HIGH)functionthatsetstheoutputpinWENtoHIGH.4.WaitsforVSynctopulseagaintoindicatetheendoftheframecapture.ThepulseIn(VSYNC,HIGH)functioniscalledandwaitsforapositivepulseontheVSYNCpin.

5.SetstheFIFOwriteenabletononactive(low)sothatnomoreimagescanbewrittentothecamera’smemory.ThedigitalWrite(WEN,LOW)functioniscalledtowriteaLOWvaluetopinWENwhichisconnectedtothecamera’swriteenablepinWR.

6.Printsouttheelapsedtimefromthestartoftheimagecapturetotheendoftheimagecapture.7.Programexecutionishaltedfor2millisecondssothatnewdatacanappearonoutputpins.Thedelay()functionisusedtodothis.SeeListing5-50.Listing5-50.TheCaptureOV7670Frame()functionvoidCaptureOV7670Frame(){unsignedlongDurationStart=0;unsignedlongDurationStop=0;unsignedlongTimeForCaptureStart=0;unsignedlongTimeForCaptureEnd=0;unsignedlongElapsedTime=0;//CaptureoneframeintoFIFOmemory//0.Initialization.Serial.println();Serial.println(F(“StartingCaptureofPhoto…”));TimeForCaptureStart=millis();//1.WaitforVSynctopulsetoindicatethestartoftheimageDurationStart=pulseIn(VSYNC,HIGH);//2.ResetWritePointerto0.WhichisthebeginningofframePulseLowEnabledPin(WRST,6);//3microseconds+3microsecondsforerrorfactoronArduino//3.SetFIFOWriteEnabletoactive(high)sothatimagecanbewrittentoramdigitalWrite(WEN,HIGH);//4.WaitforVSynctopulseagaintoindicatetheendoftheframecaptureDurationStop=pulseIn(VSYNC,HIGH);//5.SetFIFOWriteEnabletononactive(low)sothatnomoreimagescanbewrittentotheramdigitalWrite(WEN,LOW);//6.PrintoutStatsTimeForCaptureEnd=millis();ElapsedTime=TimeForCaptureEnd-TimeForCaptureStart;Serial.print(F(“TimeforFrameCapture(milliseconds)=“));

Page 150: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

Serial.println(ElapsedTime);Serial.print(F(“VSyncbeginningduration(microseconds)=“));Serial.println(DurationStart);Serial.print(F(“VSyncendduration(microseconds)=“));Serial.println(DurationStop);//7.WAITsothatnewdatacanappearonoutputpinsReadnewdata.delay(2);}TheReadTransmitCapturedFrame()functionreadsintheimagefromthecamera’smemoryandsavestheimagetoanSDcard.TheReadTransmitCapturedFrame()functiondoesthefollowing:1.TheCreatePhotoFilename()functioniscalledtocreatethenameofthephototosaveontheSDcardbasedoncertainparameterssuchasresolution,andphotonumber.2.CallstheCheckRemoveFile(Filename)functiontocheckifthefilealreadyexistsandremovesitifitdoes.3.TheSD.open(Filename.c_str(),FILE_WRITE)functionopensafileontheSDcardforwritingandreturnstheopenedfileifsuccessful.4.Ifthereturnedfileisnullthenexitthefunction.

5.Setsthereadbufferpointertothestartofthecamera’simageframe.ThisdonebycallingthedigitalWrite(RRST,LOW)functiontoresetthereadpointerbysettingthelowactiveRRSTpintoLOW.Thereadclockispulsedinordertoexecutethereadpointerreset.ThereadclockispulsedusingthePulsePin(RCLK,1)functionwheretheRCLKpinispulsedfor1microsecond.Thisisdonethreetimes.TheRRSTpinisthendeactivatedbysettingthepintoHIGH.ThisisdonebycallingthedigitalWrite(RRST,HIGH)function.

6.PulsesthereadclockRCLKtobringinanewbyteofdatabycallingthePulsePin(RCLK,1)function.

7.Convertstheinputpinvaluesfromthecamera’svideoporttobytevaluesforpins0-7oftheincomingpixel’sbyte.TheConvertPinValueToByteValue(digitalRead(DO7),7)functionisusedtodothiswiththefirstparameterbeingthevalueofaninputbitandthesecondparameteristhepositionofthisbit.

8.CombinestheindividualpiecesofdatafromeachpinintocompositedataintheformofasinglebytecalledPixelData.

9.Eachbytefromtheimageissavedusingthewrite(PixelData)commandthatiscalledfromthefileobjectthatwasreturnedfromStep3.Theparameteristhebytefromtheimagedatathatcameoutofthecamera’sFIFOmemoryfromStep6.

10.Steps6through9arerepeateduntilallthebytesfromtheimagearereadinandsavedtotheSDcard.11.TheimagefileontheSDcardisclosedbycallingtheclose()functionfromthefileobjectthatwasopenedinstep3.Forexample,ImageOutputFile.close().

12.Writesthephoto’sinfofilethatcontainstheexactcamerasettingsinatextfiletotheSDCardbycallingtheCreatePhotoInfoFile()function.SeeListing5-51.Listing5-51.TheReadTransmitCapturedFrame()functionvoidReadTransmitCapturedFrame()

Page 151: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

{bytePixelData=0;bytePinVal7=0;bytePinVal6=0;bytePinVal5=0;bytePinVal4=0;bytePinVal3=0;bytePinVal2=0;bytePinVal1=0;bytePinVal0=0;Serial.println(F(“StartingTransmissionofPhotoToSDCard…”));////////////////////CodeforSDCard///////////////////////////////////ImagefiletowritetoFileImageOutputFile;//CreatenameofPhotoTosavebasedoncertainparametersStringFilename=CreatePhotoFilename();//Checkiffilealreadyexistsandremoveitifitdoes.CheckRemoveFile(Filename);ImageOutputFile=SD.open(Filename.c_str(),FILE_WRITE);//Testiffileactuallyopenif(!ImageOutputFile){Serial.println(F(“\nCriticalERROR…CannotopenImageOuputFileforoutput…“));return;}//////////////////////////////////////////////////////////////////////////SetReadBufferPointertostartofframedigitalWrite(RRST,LOW);PulsePin(RCLK,1);PulsePin(RCLK,1);PulsePin(RCLK,1);digitalWrite(RRST,HIGH);unsignedlongByteCounter=0;for(intheight=0;height<PHOTO_HEIGHT;height++){for(intwidth=0;width<PHOTO_WIDTH;width++){for(intbytenumber=0;bytenumber<PHOTO_BYTES_PER_PIXEL;bytenumber++){//PulsethereadclockRCLKtobringinnewbyteofdata.PulsePin(RCLK,1);//ConvertPinvaluestobytevaluesforpins0-7ofincomingpixelbytePinVal7=ConvertPinValueToByteValue(digitalRead(DO7),7);PinVal6=ConvertPinValueToByteValue(digitalRead(DO6),6);PinVal5=ConvertPinValueToByteValue(digitalRead(DO5),5);PinVal4=ConvertPinValueToByteValue(digitalRead(DO4),4);PinVal3=ConvertPinValueToByteValue(digitalRead(DO3),3);

Page 152: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

PinVal2=ConvertPinValueToByteValue(digitalRead(DO2),2);PinVal1=ConvertPinValueToByteValue(digitalRead(DO1),1);PinVal0=ConvertPinValueToByteValue(digitalRead(DO0),0);//CombineindividualdatafromeachpinintocompositedataintheformofasinglebytePixelData=PinVal7|PinVal6|PinVal5|PinVal4|PinVal3|PinVal2|PinVal1|PinVal0;/////////////////////////////SDCard////////////////////////////////ByteCounter=ByteCounter+ImageOutputFile.write(PixelData);///////////////////////////////////////////////////////////////////////}}}//CloseSDCardFileImageOutputFile.close();Serial.print(F(“TotalBytesSavedtoSDCard=“));Serial.println(ByteCounter);//WritePhoto’sInfoFiletoSDCard.Serial.println(F(“WritingPhoto’sInfofile(.txtfile)toSDCard…”));CreatePhotoInfoFile();}TheCreatePhotoFilename()functioncreatesandreturnsastringthatcontainsthefilenameforthephotothatistosavedtotheSDcard.TheCreatePhotoFilename()functiondoesthefollowing:1.Ifthecameracommandis“QQVGA”orthecameracommandis“QVGA”thenthefileextensionis“.yuv”whichstandsforaYUVfile.2.Ifthecameracommandis“VGA”orthecommandis“VGAP”thenthefileextensionis“.raw”whichstandsforaBayerRAWfile3.Thefinalfilenameforthephotoisaconcatenationofthecameracommandandthenumberofphotostakenandtheextension.SeeListing5-52.Listing5-52TheCreatePhotoFilename()functionStringCreatePhotoFilename(){StringFilename=””;StringExt=””;//Createsfilenamethatthephotowillbesavedunder//Createfileextension//IfCommand=QQVGAorQVGAthenextensionis.yuvif((Command==“QQVGA”)||(Command==“QVGA”)){Ext=“.yuv”;}elseif((Command==“VGA”)||(Command==“VGAP”)){Ext=“.raw”;}

Page 153: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

//CreateFilenamefrom//Resolution+PhotoNumber+ExtensionFilename=Command+PhotoTakenCount+Ext;returnFilename;}TheCheckRemoveFile()functioncheckstoseeifafileexistsandthenremovesitifitdoes.TheCheckRemoveFile()functiondoesthefollowing:

1.IfthefileexistsontheSDcardthenremoveit.ThatisiftheSD.exists(tempchar)functionreturnstruethencalltheSD.remove(tempchar)functionwiththefilenameofthefiletoremovefromtheSDcard.

2.IfthefilestillexistsaftertryingtoremoveitthenthenewimagefilecannotbesavedtotheSDCard.AnerrormessageisprintedoutandthefunctionisexitedwithouttryingtosavethephotototheSDcard.

SeeListing5-53.Listing5-53.TheCheckRemoveFile()functionvoidCheckRemoveFile(StringFilename){//Checkiffilealreadyexistsandremoveitifitdoes.chartempchar[50];strcpy(tempchar,Filename.c_str());if(SD.exists(tempchar)){Serial.print(F(“Filename:“));Serial.print(tempchar);Serial.println(F(”AlreadyExists.RemovingIt…”));SD.remove(tempchar);}//IffilestillexiststhennewimagefilecannotbesavedtoSDCard.if(SD.exists(tempchar)){Serial.println(F(“Error..Imageoutputfilecannotbecreated…”));return;}}

TheConvertPinValueToByteValue()functionconvertspinHIGH/LOWvaluesonpinsatpositions0-7toacorrespondingbytevalue.IftheinputPinValueisHIGHthenthereturnvalueisabytewiththevalueofa1shiftedleftPinPositionnumberpositions.IfthePinValueisLOWthenazerovalueisreturned.SeeListing5-54.

Listing5-54.TheConvertPinValueToByteValue()functionbyteConvertPinValueToByteValue(intPinValue,intPinPosition){byteByteValue=0;if(PinValue==HIGH){ByteValue=1<<PinPosition;

Page 154: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

}returnByteValue;}TheCreatePhotoInfoFile()functioncreatesthephotoinformationfilebasedoncurrentcamerasettings.TheCreatePhotoInfoFile()functiondoesthefollowing:1.TheCreatePhotoInfoFilename()functioniscalledandreturnsastringwiththenameofthephoto’sinformationfilename.2.ChecksifthefilealreadyexistsandremovesitifitdoesbycallingtheCheckRemoveFile(Filename)functionwiththefilenameofthefiletocheckasaparameter.3.OpensawritablefilewiththefilenameoftheinfofilereturnedfromStep1.ThefunctionSD.open(Filename.c_str(),FILE_WRITE)isusedtodothis.4.Testiffilehasbeenopenedsuccessfully.Ifthefilehasnotbeenopenedsuccessfullythenexitthefunction.5.Createthestringthatrepresentsthecamerasettinginformationtobeincludedinthephoto’sinfofilebycallingCreatePhotoInfo()function.

6.WritethedatareturnedfromStep5totheinfofileopenedinStep3.TheInfoFile.println(Data)functionwiththecameradatabeingsentastheparameterisusedtodothis.7.ClosetheSDCardFileusingtheInfoFile.close()function

SeeListing5-55.Listing5-55.TheCreatePhotoInfoFile()functionvoidCreatePhotoInfoFile(){//Createsthephotoinformationfilebasedoncurrentsettings//.txtinformationFileforPhotoFileInfoFile;//CreatenameofPhotoTosavebasedoncertainparametersStringFilename=CreatePhotoInfoFilename();//Checkiffilealreadyexistsandremoveitifitdoes.CheckRemoveFile(Filename);//OpenFileInfoFile=SD.open(Filename.c_str(),FILE_WRITE);//Testiffileactuallyopenif(!InfoFile){Serial.println(F(“\nCriticalERROR…CannotopenPhotoInfoFileforoutput…“));return;}//WriteInfotofileStringData=CreatePhotoInfo();InfoFile.println(Data);//CloseSDCardFileInfoFile.close();}

Page 155: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

TheCreatePhotoInfoFilename()functioncreatesthefilenamethattheinformationaboutthephotowillbesavedunder.TheCreatePhotoInfoFilename()functiondoesthefollowing:1.SetsthefileextensionforanInfofileforaphototo“.txt”.2.Createthefinalfilenamefromthecombinationofthecameraresolution,photonumber,andExtension.SeeListing5-56.Listing5-56.TheCreatePhotoInfoFilename()functionStringCreatePhotoInfoFilename(){StringFilename=””;StringExt=””;//Createsfilenamethattheinformationaboutthephotowill//besavedunder.//CreatefileextensionExt=“.txt”;//CreateFilenamefrom//Resolution+PhotoNumber+ExtensionFilename=Command+PhotoTakenCount+Ext;returnFilename;}TheCreatePhotoInfo()functioncreatestheinformationwhichwillbesavedinaphoto’sinfofilethatconsistsofthecamera’scommandandthecamera’sparameters.SeeListing5-57.Listing5-57.TheCreatePhotoInfo()functionStringCreatePhotoInfo(){StringInfo=””;Info=Command+””+FPSParam+””+AWBParam+””+AECParam+””+YUVMatrixParam+””+DenoiseParam+””+EdgeParam+””+ABLCParam;returnInfo;}TestingtheSDCard:ReadingFromtheSDCardTheReadPrintFile()functionisusedtotestthereadingcapabilitiesoftheSDcard.TheReadPrintFile()functiondoesthefollowing:1.AfileisopenedontheSDcardbycallingtheSD.open(Filename.c_str())function.

2.Ifthefileobjectthatisreturnedisvalidthenreadandprintoutallthefilecontentstothescreen.Thisisdoneinawhileloopthatcontinuesloopinguntilthereisnomoreinformationtoread,thatistheTempFile.available()functionreturns0.ThefiledataiswrittentothescreenoftheSerialMonitorbycallingtheSerial.write(TempFile.read())functionwiththeinputparameterbeingfiledatathatisreadfromtheread()functionontheFileobject.

3.ThefileisthenclosedbycallingtheTempFile.close()functionontheFileobjectthatwasopenedinStep1.

Page 156: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

SeeListing5-58.Listing5-58.TheReadPrintFile()functionvoidReadPrintFile(StringFilename){FileTempFile;//ReadsinfileandprintsittoscreenviaSerialTempFile=SD.open(Filename.c_str());if(TempFile){Serial.print(Filename);Serial.println(“:”);//readfromthefileuntilthere’snothingelseinit:while(TempFile.available()){Serial.write(TempFile.read());}//closethefile:TempFile.close();}else{//ErroropeningfileSerial.print(“Erroropening“);Serial.println(Filename);}}TestingtheSDCard:WritingaFiletotheSDCardTheWriteFileTest()functionwritesatestfiletotheSDcard.Thefunctionopensafileforwriting,writessometextdatatothefile,andthenclosesthefile.SeeListing5-59.Listing5-59.TheWriteFileTest()functionvoidWriteFileTest(StringFilename){FileTempFile;TempFile=SD.open(Filename.c_str(),FILE_WRITE);if(TempFile){Serial.print(F(“Writingtotestfile…”));TempFile.print(F(“TESTCAMERASDCARDHOOKUPAtTime…“));TempFile.print(millis()/1000);TempFile.println(F(”Seconds”));TempFile.print(F(“PhotoInfoFilename:“));TempFile.println(CreatePhotoInfoFilename());TempFile.print(F(“PhotoInfo:”));TempFile.println(CreatePhotoInfo());//closethefile:TempFile.close();Serial.println(F(“WritingFileDone…”));}

Page 157: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

else{//ifthefiledidn’topen,printanerror:Serial.print(F(“Erroropening“));Serial.println(Filename);}}ChangingtheCamera’sCommandorParametersTheParseRawCommand()functionprocessestheuser’scameracommandsandparameterchanges.TheParseRawCommand()functiondoesthefollowing:1.CallstheParseCommand(RawCommandLine.c_str(),‘‘,Entries)functionthatbreaksuptheuser’sinputintoanarrayofstrings.

2.EachoftheelementsofthestringarrayfromStep1issenttotheProcessRawCommandElement(Entries[i])functiontobeprocessed.Iftheprocessingwassuccessfulthenamessageisprintedoutsayingthattheuserhassuccessfullychangedacameracommandorparameter.Otherwiseanerrormessageisprintedout.

3.TheResolutionissetto“None”whichresetsandreloadsthecamera’sregisterswhenaphotoistaken.4.Thecamera’sregistersareresetbycallingtheResetCameraRegisters()function.SeeListing5-60.Listing5-60.TheParseRawCommand()functionvoidParseRawCommand(StringRawCommandLine){StringEntries[10];booleansuccess=false;//ParseintocommandandparametersintNumberElements=ParseCommand(RawCommandLine.c_str(),‘‘,Entries);for(inti=0;i<NumberElements;i++){booleansuccess=ProcessRawCommandElement(Entries[i]);if(!success){Serial.print(F(“InvalidCommandorParameter:“));Serial.println(Entries[i]);}else{Serial.print(F(“Commandorparameter“));Serial.print(Entries[i]);Serial.println(F(”sucessfullyset…”));}}//Assumeparameterchangesinceuserissettingparametersoncommandlinemanually//Tellsthecameratore-initializeandsetupcameraaccordingtonewparametersResolution=None;//ResetandreloadregistersResetCameraRegisters();

Page 158: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

}TheParseCommand()functionsplitsanarrayofcharactersbasedonauserinputcharacterandstorestheresultinanarrayofstrings.TheParseCommand()functiondoesthefollowing:

1.ForeachcharacterinthecommandlinecomparethatcharactertothesplitcharacteriftheyareequalthenthismarkstheendofauserparametersosavethetempstringinthearrayofstringsResult.Ifthecharacterisnotthesplitcharacterthenaddthischaractertothetempstringvariable.

2.AddthetempstringvariabletothearrayofstringsResult.Thisaddsinthelastuserparameterthatdoesnothaveasplitcharacterafterittothearrayofstrings.3.ReturnthenumberofuserparametersintheResultarray.SeeListing5-61.Listing5-61TheParseCommand()functionintParseCommand(constchar*commandline,charsplitcharacter,String*Result){intResultIndex=0;intlength=strlen(commandline);Stringtemp=””;for(inti=0;i<length;i++){chartempchar=commandline[i];if(tempchar==splitcharacter){Result[ResultIndex]+=temp;ResultIndex++;temp=””;}else{temp+=tempchar;}}//PutinendpartofstringResult[ResultIndex]=temp;return(ResultIndex+1);}

TheProcessRawCommandElement()functiontestsuserinputtoseeifitisoneofthecamera’scommandsorcameraparameters.Ifsothenitsetstheappropriatecommandorparametertotheuser’sselection.

TheProcessRawCommandElement()functiondoesthefollowing:

1.ChangestheinputElementtoalllowercaseinordertohelptestforvalidcommandsandparameters.Forexample,theusercanenteracommandorparameterthatiscaseinsensitivesuchthatVGAisthesameasvgaandisthesameasvGa.

2.TheinputElementistestedtoseeifitisavalidcameracommand.Validcommandsare

Page 159: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

vga,vgap,qvga,andqqvga.IfthereisamatchthenthecommandissettotheappropriatecommandbasedontheElement.

3.IfitisnotacommandthentheinputElementistestedtoseeifitisoneofthevalidcameraparameters.IfitisthenitissettothecorrespondingparametervaluebasedontheElement’svalue.

4.IftheinputElementwasfounditbeeitheracommandorparameterthenatrueisreturnedotherwiseafalsevalueisreturned.SeeListing5-62.Listing5-62.TheProcessRawCommandElement()functionbooleanProcessRawCommandElement(StringElement){booleanresult=false;Element.toLowerCase();if((Element==“vga”)||(Element==“vgap”)||(Element==“qvga”)||(Element==“qqvga”)){Element.toUpperCase();Command=Element;result=true;}elseif(Element==“thirtyfps”){FPSParam=“ThirtyFPS”;result=true;}elseif(Element==“nightmode”){FPSParam=“NightMode”;result=true;}elseif(Element==“sawb”){AWBParam=“SAWB”;result=true;}elseif(Element==“aawb”){AWBParam=“AAWB”;result=true;}else

Page 160: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

if(Element==“aveaec”){AECParam=“AveAEC”;result=true;}elseif(Element==“histaec”){AECParam=“HistAEC”;result=true;}elseif(Element==“yuvmatrixon”){YUVMatrixParam=“YUVMatrixOn”;result=true;}elseif(Element==“yuvmatrixoff”){YUVMatrixParam=“YUVMatrixOff”;result=true;}elseif(Element==“denoiseyes”){DenoiseParam=“DenoiseYes”;result=true;}elseif(Element==“denoiseno”){DenoiseParam=“DenoiseNo”;result=true;}elseif(Element==“edgeyes”){EdgeParam=“EdgeYes”;result=true;}elseif(Element==“edgeno”){EdgeParam=“EdgeNo”;result=true;}

Page 161: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

elseif(Element==“ablcon”){ABLCParam=“AblcON”;result=true;}elseif(Element==“ablcoff”){ABLCParam=“AblcOFF”;result=true;}returnresult;}

Page 162: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

OverviewofFFMPEG

InordertoconverttheimagefilesthataresavedtotheSDcardtoaviewablepictureyouneedtouseanimageconverterprogramlikeffmpeg.Thissectiongivessomebackgroundofffmpegincludingtheofficialwebsite,theversionofffmpegtestedwiththisbook,andtheexactcommandsthatwillconverttheQQVGA,QVGA,andVGAimagesgeneratedfromthecaptureprogramintoPNG(PortableNetworkGraphics)imagefiles.ThePNGformatiswidelysupportedcomparedtotheYUVorBayerRawimageformats.

OfficialWebsite

Theofficialwebsitefortheffmpegprogramishttps://www.ffmpeg.org/Youshouldgothereanddownloadthelatestversionforyourcomputersystem.Itisfreeandavailableatnocharge.

FFMPEGVersionTestedwiththisBook

Accordingtothereadme.txtfileintheversionofffmpegIusedforthisbook,theffmpegversionistheWin32staticbuildbyKyleSchwarz.TheFFmpegversionis“2015-03-12git-3bedc99”

ThisistheversionIusedtotesttheoutputoftheov7670camerawithboththeYUVandtheBayerRAWpicturefiles.IfyouarehavingproblemsconvertingyourYUVorRAWimagefilestoaviewableformatthentrytousethisversionofffmpeg.Theyshouldhaveanarchivewitholderversionsoftheprogramavailable.

FFMPEGCONVERSION

Thissectiondescribestheffmpegcommandlineoptionsthatarerequiredtoconverttheimagesintoaneasilyviewableformat.TheimagesfromthecamerathatarerecordedinYUVandRawBayerformatareconvertedtoPNGfiles.PNGstandsforportablenetworkgraphicsfilewhichisacommonimagefiletypethatcanbeviewedinwindowsexplorerorthoughapaintprogramlikePaintShopPro.

ForeachofthefollowingcommandsreplaceINPUTFILE.YUVorINPUTFILE.RAWwiththeactualfilenameoftheYUVfileorBayerRAWfileyouwanttocovert.ChangetheOUTPUTFILE.PNGfilenametothefilenameyouwanttosavethenewimageas.

QQVGA

ffmpeg-frawvideo-s160x120-pix_fmtyuyv422-iINPUTFILE.YUV-fimage2-vcodecpngOUTPUTFILE.PNG

QVGA

Page 163: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

ffmpeg-frawvideo-s320x240-pix_fmtyuyv422-iINPUTFILE.YUV-fimage2-vcodecpngOUTPUTFILE.PNG

VGA

ffmpeg-frawvideo-s640x480-pix_fmtbayer_bggr8-iINPUTFILE.RAW-fimage2-vcodecpngOUTPUTFILE.PNG

Page 164: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

Summary

InthischapterIhavecoveredthehardwareandsoftwareaspectsoftheSDcardreaderincludinginput/outputpinconnectionstotheArduinoaswellasdiscussingtheSDcarditself,andinitializing,reading,writing,anddeletingfilestoandfromtheSDcard.Next,IcoveredtheArduino’sI2Cinterfaceincludingtheactualinterface,readingandwritingtoanI2Cdevicesuchastheov7670camera.MyimagecaptureprogramthatworkswiththeSDcardreaderandov7670cameraisalsodiscussed.Finally,theffmpegprogramthatisusedtoconverttheYUVandBayerRAWphotoimagesintoPNGimagefilesiscovered.

Page 165: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

Chapter6

Page 166: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without
Page 167: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

TakingPhotoswiththeOmnivisionov7670Camera–Part2Thischapterisaquickstartguidetogettingyourov7670cameraoperational.IdiscusseverythingyouneedtoknowincludinghowtoconnecttheSDcardreaderandcameratoyourArduinoMega2560.Idiscusshowtooperatetheimagecapturesoftware.ItellyouhowtotransferyourimagestoyourcomputerandIshowyouhowtoconverttheseimagesintoeasilyviewablePNGimages.

Page 168: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

HandsonExample:Takingapicturewiththecamera,savingthepicturetotheSDcardstorage,andviewingtheimageonyourcomputer.

InthishandsonexampleIwillbeshowinghowtosetupthecameratotakepictures,transferthemtoyourcomputerandtoconvertthemtoanimageformatthatiseasilyviewable.IstartwithshowingyouhowtosetupandconnecttheSDcardreaderandcameratotheArduino.IthendiscusstheimagecaptureprogramIwrotetocaptureandsaveimagestoaSDcard.Then,Iwalkyoustepbysteponhowtousetheprogram.IcoverhowtotakeapictureineachofthecameracommandmodesthatareQQVGA,QVGA,VGAP,andVGA.Ialsodemonstratehowcameraparameterscanbechangedandshowhowtheyeffecttheoutputofacameraimage.IthendiscusshowtotransfertheimagedataontheSDcardtoyourcomputer.Finally,Ishowyouhowtoconvertimagesfromthecameratoeasilyviewableimagesonyourcomputer.

Creatinga3.3voltBreadboardNode

Thefirstthingyouneedtodoiscreatea3.3voltnodeonabreadboardthatwillprovidepowertothecameraandtotheSDcardreader.Todothisyouneedtoconnecttwomaletofemalejumperwiresand1wirewithmaleconnectionsonbothendsintoholesinthebreadboardthatareconnectedtogether.Thetwomaletofemalewireswillbeusedtoconnectthe3.3voltinputpinsontheSDcardreaderandcameratothe3.3voltnodeonthebreadboard.Thewirewiththemaleconnectionsonbothendswillbeusedtoconnectthe3.3voltnodeonthebreadboardtothe3.3voltoutputfromtheArduino.Somebreadboardshaveapowerlineandagroundlinewhereallthepinsinthecolumnareconnected.Theyalsohaverowsof5pinsthatareconnectedtogether.SeeFigure6-1.

Figure6-1.Breadboardwithpowerrailsandgroundline

Therearealsosmallerbreadboardsavailablethatjusthavetwocolumnsofrowsofnodes.

Page 169: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

Eachnodeconsistsof5pins.Iusedoneoftheseforthepowernodeforthehandsonexampleinthisbook.SeeFigure6-2.Thefigureshowsthe3.3voltpowernode.YoucanbuybothkindsofbreadboardsonAmazon.com.

Figure6-2.Breadboardwithonlytwocolumnsofconnectedpins

ConnectingtheSDCardReadertotheArduino

Next,youneedtoconnecttheSDcardreadertotheArduino.MakesurethepowerisofftotheArduinobeforeyouperformthefollowingsteps.YouwillneedtousethefemaletomalejumperwiresforconnectingtheSDcardtotheArduino.

Youwillneedto:•Connectthe3.3voltpinontheSDcardreadertothebreadboard’s3.3voltnode.•ConnecttheSDCSpintopin48ontheArduino.•ConnecttheMOSIpintopin51ontheArduino.•ConnecttheSCKpintopin52ontheArduino.•ConnecttheMISOpintopin50ontheArduino.•ConnecttheGNDpintoaGNDpinontheArduino.SeeFigure6-3.

Page 170: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

Figure6-3.ConnectingtheSDcardtotheArduinoMega2560

DefiningthePinsinCode

TheuserdefinablepinassignmentsforaSDcardisjusttheSDCSorchipselectpinwhichisdefinedinourimagecaptureprogramaspin48.Thismeansthatthewirefromthecamera’sSDCSpinisconnectedtotheArduino’spin48.

constintchipSelect=48;

ConnectingtheCameratotheArduino

Next,weneedtoconnecttheov7670cameratotheArduino.YouwillneedtousethefemaletomalejumperwiresforconnectingthecameratotheArduino.ToconnectthecameratotheArduinoyouneedto:•Connectthe3.3voltpinonthecameratothe3.3voltnodeonthebreadboard.

•ConnecttheGroundpinonthecameratooneoftheGroundpinsontheArduino•ConnecttheSIOCpinonthecameratotheSCLorpin21ontheArduino.

•ConnecttheSIODpinonthecameratotheSDAorpin20ontheArduino.•ConnecttheWRSTpinonthecameratopin22ontheArduino.•ConnecttheRRSTpinonthecameratopin23ontheArduino.•ConnecttheWRpinonthecameratopin24ontheArduino.•ConnecttheVSYNCpinonthecameratopin25ontheArduino.•ConnecttheRCLKpinonthecameratopin26ontheArduino.•ConnecttheOEpinonthecameratooneoftheGND(Ground)pinsontheArduino.•ConnecttheD7pinonthecameratopin28ontheArduino.

Page 171: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

•ConnecttheD6pinonthecameratopin29ontheArduino.•ConnecttheD5pinonthecameratopin30ontheArduino.•ConnecttheD4pinonthecameratopin31ontheArduino.•ConnecttheD3pinonthecameratopin32ontheArduino.•ConnecttheD2pinonthecameratopin33ontheArduino.•ConnecttheD1pinonthecameratopin34ontheArduino.•ConnecttheD0pinonthecameratopin35ontheArduino.SeeFigures6-4and6-5foravisualdescriptionoftheconnectionsrequired.

Figure6-4.ConnectingthecameratotheArduino

Figure6-5.ConnectingthecameratotheArduino

Page 172: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

DefiningthePinsinCode

TheuserdefinablepinsontheArduinosideforthecameraareinListing6-1.Forexample,theWRSTpinisdefinedontheArduinoaspin22andisconnectedtotheWRSTpinonthecamera.TheRRSTpinisdefinedontheArduinoaspin23andisconnectedtotheRRSTpinonthecamera.

Listing6-1.Userdefinablepinsinourimagecapturecode//Camerainput/outputpinconnectiontoArduino#defineWRST22//OutputWritePointerReset#defineRRST23//OutputReadPointerReset#defineWEN24//OutputWriteEnable#defineVSYNC25//InputVerticalSyncmarkingframecapture#defineRCLK26//OutputFIFObufferoutputclock//FIFORaminputpins#defineDO728#defineDO629#defineDO530#defineDO431#defineDO332#defineDO233#defineDO134#defineDO035

TheOmnivisionov7670FIFOCameraImageCaptureSoftware

Thissectiondiscussestheimagecapturesoftware.Theofficialwebsiteislistedfollowedbyalistingofthevarioussoftwarecommands.

OfficialWebSite

Currentlytheofficialwebsiteofthisbookislocatedat:http://www.psycho-sphere.comGotothewebsiteforupdatestotheimagecaptureprogramaswellascorrectionsandupdatestothisbook.Adirectlinktoazipfileoftheimagecaptureprogramis:http://www.psycho-sphere.com/BeginningArduinoov7670CameraDevelopment.zip

UserCameraControlCommands

•d-DisplayCurrentCameraCommandt-TakePhotographusingcurrentCommandandParameters•

CameraCommandandParameterSetCommands

•ResolutionChangeCommands:VGA,VGAP,QVGA,QQVGA•FPS(FramesPerSecond)Parameters:ThirtyFPS,NightMode

Page 173: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

•AWB(AutomaticWhiteBalance)Parameters:SAWB,AAWB•AEC(AutomaticExposureControl)Parameters:AveAEC,HistAEC•YUVColorMatrixParameters:YUVMatrixOn,YUVMatrixOff•DenoiseParameters:DenoiseYes,DenoiseNo•EdgeEnhancementParameters:EdgeYes,EdgeNo•ABLC(AutomaticBlackLevelCalibration)Parameters:AblcON,AblcOFF

SDCardTestCommands

•testread-TestsreadingfilesfromtheSDcardbyreadingandprintingthecontentsof“test.txt”thatwasgeneratedbythe“testwrite”command.Thetextoutputofthiscommandshouldbesomethingsimilarto:

TEST.TXT:TESTCAMERASDCARDHOOKUPAtTime…25SecondsPhotoInfoFilename:QQVGA0.txtPhotoInfo:QQVGAThirtyFPSSAWBHistAECYUVMatrixOnDenoiseNoEdgeNoAblcON•testwrite-TestswritingfilestotheSDcardunderthefilename“test.txt”.Thetextoutputfromthiscommandis“Writingtotestfile…WritingFileDone…”

HelpCommands

•help–Displayshelpmenu•helpcamera-DisplaysCamera’sCommandsandParameters

TakingPhotoswiththeCamera

Thepurposeofthissectionistodemonstratehowtotakephotoswiththeov7670camerausingmyimagecapturesoftware.TherecommendedsetupofthecameraisshowninFigure6-6withthecamerahangingovertheedgeofthetablesothatthereisnostrainplacedonthecamera’swires.

IMPORTANT:TakenoteofhowthecamerahangsoverthesideofthetablesothatthereisnostrainonthewiresgoingintotheArduinopinsfromthecamera.IhavenoticedthatwhenItrytotakepictureswhenImovethecameratoalevelpositionandthusputstrainonthewires,manytimesIgetanincorrectgarbledphoto.

Page 174: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

Figure6-6.Recommendedcamerasetup

ImageCaptureProgramInitialization

1.Firstyouwillneedtodownloadanduncompresstheimagecaptureprogramusingaprogramlike7-zip.Note:7zipisafreeprogramthatisavailableat:http://www.7-zip.org2.StarttheArduinoIDEandloadintheimagecaptureprogramyoujustdownloadedanduncompressed.

3.ConnectyourArduinoMega2560toyourcomputer.AlsomakesuretheSDcardispushedfirmlyintotheSDcardreader’sslotuntilthereisaclick.ItisalsoagoodideatocheckthattheSDcardreaderisworkingproperlybyusingthe“testread”and“testwrite”commands.Youshouldfirstuse“testwrite”tohavetheArduinowriteoutafilecalled“test.txt”totheSDcard.Then,usethe“testread”commandtoreadbackthefileandprintitscontentsouttothescreen.

4.Clickthe“Upload”buttonontheArduinoIDEtouploadtheimagecaptureprogramtoyourArduino.5.Waituntiltheprogramhasfinisheduploading.

6.Clickthe“SerialMonitor”buttontobringuptheserialmonitor.7.TheprogramshouldbegintoinitializeandproducethefollowingoutputontheSerialMonitorwindow.

ArduinoSERIAL_MONITOR_CONTROLLEDCAMERA…Usingov7670Camera–––––––––—CameraRegisters–––––––––

Page 175: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

RESETTINGALLREGISTERSBYSETTINGCOM7REGISTERto0x80:I2COperationOK…CLKRC=80COM7=0COM3=0COM14=0SCALING_XSC=3ASCALING_YSC=35SCALING_DCWCTR=11SCALING_PCLK_DIV=0SCALING_PCLK_DELAY=2TSLB(YUVOrder-HigherBit,Bit[3])=DCOM13(YUVOrder-LowerBit,Bit[1])=88COM17(DSPColorBarSelection)=0COM4(workswithCOM17)=0COM15(COLORFORMATSELECTION)=C0COM11(NightMode)=0COM8(ColorControl,AWB)=8FHAECC7(AECAlgorithmSelection)=14GFIX=0HSTART=11HSTOP=61HREF=80VSTRT=3VSTOP=7BVREF=0––––––––––––––––––––––––—InSetupCamera()…InitializingOV7670Camera…FINISHEDINITIALIZINGCAMERA…InitializingSDcard…Wiringiscorrectandacardispresent…Omnivisionov7670CameraImageCaptureSoftwareVersion1.0Copyright2015byRobertChin.AllRightsReserved.Typehorhelpformainhelpmenu…ReadytoAcceptnewCommand=>

TakingQQVGAPhotos

8.Nowletstakeaphotobysendinga“t”totheArduinoviatheSerialMonitor.SincethedefaultissettotakepicturesinQQVGAmodethepicturethatistakenwillbeofQQVGAresolution.Thefollowingshouldappearintheoutputwindow.Figure6-7andFigure6-8showsyousomephotosthatItookinQQVGAformat.

ImportantNote:Thedefaultfocusofthecameramayneedadjustment.Aftertakingthisfirstpicturetransfertheimagetoyourcomputerandthenconvertitintoaneasilyviewableimagefileusingffmpeg(pleaseseethesectiononffmpeginthischapter).Lookattheimageandseeifitisinfocus.Ifitisnotthenyouwillneedtoadjustthecamera’sfocusbyturningthelens.Takeanotherpicture.Ifthenewpictureisclearerthantheoldonethenyouareturningthelensintherightdirection.Ifitislessfocusedthenturnthe

Page 176: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

camera’slensintheoppositedirection.Continuetakingphotos,checkingthesharpnessofthepicture,andthenadjustingthecameralensuntilyougetaclearpicture.

ReadytoAcceptnewCommand=>RawCommandfromSerialMonitor:tGoingtotakephotowithcurrentcommand:CurrentCommand:Command:QQVGAFPSParam:ThirtyFPSAWBParam:SAWBAECParam:HistAECYUVMatrixParam:YUVMatrixOnDenoiseParam:DenoiseNoEdgeParam:EdgeNoABLCParam:AblcONTakingaQQVGAPhoto…–––––––––SettingCameraforQQVGAYUV––––––––—PhotoWidth=160PhotoHeight=120BytesPerPixel=2………..SettingBasicQQVGAParameters……..CLKRC:I2COperationOK…COM7:I2COperationOK…COM3:I2COperationOK…COM14:I2COperationOK…SCALING_XSC:I2COperationOK…SCALING_YSC:I2COperationOK…SCALING_DCWCTR:I2COperationOK…SCALING_PCLK_DIV:I2COperationOK…SCALING_PCLK_DELAY:I2COperationOK…TSLB:I2COperationOK…COM13:I2COperationOK…COM17:I2COperationOK…………..SettingCamerato30FPS……..CLKRC:I2COperationOK…DBLV:I2COperationOK…EXHCH:I2COperationOK…EXHCL:I2COperationOK…DM_LNL:I2COperationOK…DM_LNH:I2COperationOK…COM11:I2COperationOK…––––—SettingCameraHistogramBasedAEC/AGCRegisters––––—AEW:I2COperationOK…AEB:I2COperationOK…HAECC1:I2COperationOK…HAECC2:I2COperationOK…HAECC3:I2COperationOK…HAECC4:I2COperationOK…HAECC5:I2COperationOK…

Page 177: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

HAECC6:I2COperationOK…HAECC7:I2COperationOK…………..SettingCameratoSimpleAWB……..COM8(0x13):I2COperationOK…AWBCTR0ControlRegister0(0x6F):I2COperationOK…………..SettingCameraGain……..COM9:I2COperationOK…BLUEGAIN:I2COperationOK…REDGAIN:I2COperationOK…GREENGAIN:I2COperationOK…COM16(ENABLEGAIN):I2COperationOK…………..SettingCameraUndocumentedRegisters……..SettingB0UNDOCUMENTEDregisterto0x84:=I2COperationOK…………..SettingCameraColorMatrixforYUV……..MTX1:I2COperationOK…MTX2:I2COperationOK…MTX3:I2COperationOK…MTX4:I2COperationOK…MTX5:I2COperationOK…MTX6:I2COperationOK…CONTRAS:I2COperationOK…MTXS:I2COperationOK…………..SettingCameraSaturationLevel……..SATCTR:I2COperationOK…………..SettingCameraArrayControl……..CHLF:I2COperationOK…ARBLM:I2COperationOK…………..SettingCameraADCControl……..ADCCTR1:I2COperationOK…ADCCTR2:I2COperationOK…ADC:I2COperationOK…ACOM:I2COperationOK…OFON:I2COperationOK………..SettingCameraABLC…….ABLC1:I2COperationOK…THL_ST:I2COperationOK…………..SettingCameraWindowOutputParameters……..HSTART:I2COperationOK…HSTOP:I2COperationOK…HREF:I2COperationOK…VSTRT:I2COperationOK…VSTOP:I2COperationOK…VREF:I2COperationOK…–––––––––—CameraRegisters–––––––––CLKRC=80COM7=0COM3=4COM14=1A

Page 178: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

SCALING_XSC=3ASCALING_YSC=35SCALING_DCWCTR=22SCALING_PCLK_DIV=F2SCALING_PCLK_DELAY=2TSLB(YUVOrder-HigherBit,Bit[3])=0COM13(YUVOrder-LowerBit,Bit[1])=C8COM17(DSPColorBarSelection)=0COM4(workswithCOM17)=0COM15(COLORFORMATSELECTION)=C0COM11(NightMode)=ACOM8(ColorControl,AWB)=E7HAECC7(AECAlgorithmSelection)=94GFIX=0HSTART=13HSTOP=1HREF=A4VSTRT=2VSTOP=7AVREF=A––––––––––––––––––––––––—StartingCaptureofPhoto…TimeforFrameCapture(milliseconds)=130VSyncbeginningduration(microseconds)=392VSyncendduration(microseconds)=392StartingTransmissionofPhotoToSDCard…TotalBytesSavedtoSDCard=38400WritingPhoto’sInfofile(.txtfile)toSDCard…ElapsedTimeforTakingandSendingPhoto(secs)=4PhotoTakenandSavedtoArduinoSDCARD…ImageOutputFilename:QQVGA0.yuvReadytoAcceptnewCommand=>

Figure6-7.QQVGAPhoto Figure6-8.QQVGAPhoto

TakingQVGAPhotos

9.Next,let’stakesomeQVGAphotos.Sendthevalue“qvga”totheArduinousingtheSerialMonitor.Thecommandshouldbeackowledged,cameraregistersshouldbereset,andthenewcameracommandwithparametersshouldbedisplayed.Youshouldseeoutputsimilartothefollowing:

Page 179: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

ReadytoAcceptnewCommand=>RawCommandfromSerialMonitor:qvgaChangingcommandorparametersaccordingtoyourinput:Commandorparameterqvgasucessfullyset…RESETTINGALLREGISTERSBYSETTINGCOM7REGISTERto0x80:I2COperationOK…CurrentCommand:Command:QVGAFPSParam:ThirtyFPSAWBParam:SAWBAECParam:HistAECYUVMatrixParam:YUVMatrixOnDenoiseParam:DenoiseNoEdgeParam:EdgeNo

ABLCParam:AblcON10.TotakeaphotosendtheArduinoa“t”value.Thecommandshouldbeacknowledged,thecurrentcameracommandwithparametersshouldbedisplayed,adetailedbreakdownoftheexactcameraregisterwriteoperationsbeingperformedisdisplayed,aprintoutoftheresultingchangesinkeyregistersandinformationregardingthesavingofthephotototheSDCardisdisplayed.SomephotosthatIhavetakenareshowninFigure6-9andFigure6-10.Youshouldseeoutputsimilartothefollowing:

ReadytoAcceptnewCommand=>RawCommandfromSerialMonitor:tGoingtotakephotowithcurrentcommand:CurrentCommand:Command:QVGAFPSParam:ThirtyFPSAWBParam:SAWBAECParam:HistAECYUVMatrixParam:YUVMatrixOnDenoiseParam:DenoiseNoEdgeParam:EdgeNoABLCParam:AblcONTakingaQVGAPhoto…–––––––––SettingCameraforQVGA(YUV)––––––––—PhotoWidth=320PhotoHeight=240BytesPerPixel=2CLKRC:I2COperationOK…COM7:I2COperationOK…COM3:I2COperationOK…COM14:I2COperationOK…SCALING_XSC:I2COperationOK…SCALING_YSC:I2COperationOK…SCALING_DCWCTR:I2COperationOK…SCALING_PCLK_DIV:I2COperationOK…

Page 180: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

SCALING_PCLK_DELAY:I2COperationOK…TSLB:I2COperationOK…COM13:I2COperationOK…COM17:I2COperationOK…………..SettingCamerato30FPS……..CLKRC:I2COperationOK…DBLV:I2COperationOK…EXHCH:I2COperationOK…EXHCL:I2COperationOK…DM_LNL:I2COperationOK…DM_LNH:I2COperationOK…COM11:I2COperationOK…––––—SettingCameraHistogramBasedAEC/AGCRegisters––––—AEW:I2COperationOK…AEB:I2COperationOK…HAECC1:I2COperationOK…HAECC2:I2COperationOK…HAECC3:I2COperationOK…HAECC4:I2COperationOK…HAECC5:I2COperationOK…HAECC6:I2COperationOK…HAECC7:I2COperationOK…………..SettingCameratoSimpleAWB……..COM8(0x13):I2COperationOK…AWBCTR0ControlRegister0(0x6F):I2COperationOK…………..SettingCameraGain……..COM9:I2COperationOK…BLUEGAIN:I2COperationOK…REDGAIN:I2COperationOK…GREENGAIN:I2COperationOK…COM16(ENABLEGAIN):I2COperationOK…………..SettingCameraUndocumentedRegisters……..SettingB0UNDOCUMENTEDregisterto0x84:=I2COperationOK…………..SettingCameraColorMatrixforYUV……..MTX1:I2COperationOK…MTX2:I2COperationOK…MTX3:I2COperationOK…MTX4:I2COperationOK…MTX5:I2COperationOK…MTX6:I2COperationOK…CONTRAS:I2COperationOK…MTXS:I2COperationOK…………..SettingCameraSaturationLevel……..SATCTR:I2COperationOK…………..SettingCameraArrayControl……..CHLF:I2COperationOK…

Page 181: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

ARBLM:I2COperationOK…………..SettingCameraADCControl……..ADCCTR1:I2COperationOK…ADCCTR2:I2COperationOK…ADC:I2COperationOK…ACOM:I2COperationOK…OFON:I2COperationOK………..SettingCameraABLC…….ABLC1:I2COperationOK…THL_ST:I2COperationOK…………..SettingCameraWindowOutputParameters……..HSTART:I2COperationOK…HSTOP:I2COperationOK…HREF:I2COperationOK…VSTRT:I2COperationOK…VSTOP:I2COperationOK…VREF:I2COperationOK…–––––––––—CameraRegisters–––––––––CLKRC=80COM7=0COM3=4COM14=19SCALING_XSC=3ASCALING_YSC=35SCALING_DCWCTR=11SCALING_PCLK_DIV=F1SCALING_PCLK_DELAY=2TSLB(YUVOrder-HigherBit,Bit[3])=4COM13(YUVOrder-LowerBit,Bit[1])=C2COM17(DSPColorBarSelection)=0COM4(workswithCOM17)=0COM15(COLORFORMATSELECTION)=C0COM11(NightMode)=ACOM8(ColorControl,AWB)=E7HAECC7(AECAlgorithmSelection)=94GFIX=0HSTART=13HSTOP=1HREF=24VSTRT=2VSTOP=7AVREF=A––––––––––––––––––––––––—StartingCaptureofPhoto…TimeforFrameCapture(milliseconds)=74VSyncbeginningduration(microseconds)=392VSyncendduration(microseconds)=392StartingTransmissionofPhotoToSDCard…

Page 182: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

TotalBytesSavedtoSDCard=153600WritingPhoto’sInfofile(.txtfile)toSDCard…ElapsedTimeforTakingandSendingPhoto(secs)=15PhotoTakenandSavedtoArduinoSDCARD…ImageOutputFilename:QVGA3.yuvReadytoAcceptnewCommand=>

Figure6-9.QVGAphoto

Figure6-10.QVGAphoto

11.NextletstrytochangeacameraparameterbyturningtheYUVColorMatrixoff.TheYUVcolormatrixhastheeffectofmakingthecolorsmorevibrantbyincreasingthered,green,andbluecolorsinanimage.Byturningthismatrixoffwemaketheimagelessvibrantandcolorful.Enter“yuvmatrixoff”andsendthisvaluetotheArduinoviatheSerialMonitor.Youshouldseetextoutputlikethefollowingwhichconfirmstheparameterchange,resetsthecamera’sregisters,anddisplaysthenewchangedcamerasettings:ReadytoAcceptnewCommand=>

RawCommandfromSerialMonitor:yuvmatrixoffChangingcommandorparametersaccordingtoyourinput:Commandorparameteryuvmatrixoffsucessfullyset…

Page 183: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

RESETTINGALLREGISTERSBYSETTINGCOM7REGISTERto0x80:I2COperationOK…CurrentCommand:Command:QVGAFPSParam:ThirtyFPSAWBParam:SAWBAECParam:HistAECYUVMatrixParam:YUVMatrixOffDenoiseParam:DenoiseNoEdgeParam:EdgeNoABLCParam:AblcON

12.Next,takeaphotobysendingtheArduinoa“t”command.Youshouldseetextoutputsimilartothelasttimeyoutookaphotohoweverthe“………..SettingCameraColorMatrixforYUV……..”sectionshouldbemissing.ThisindicatesthattheYUVColorMatrixhasbeendeactivated.SeeFigure6-11foraphotoItookwiththesenewparameters.

Figure6-11.QVGAphotowithYUVcolormatrixisturnedoff

TakingVGAPPhotos

13.Next,letstrytotakeaphotousingtheprocessedVGAmode.Sendthecommand“vgap”totheArduinotochangethecameracommandsettings.Thecommandshouldbeconfirmed,thecamera’sregistersshouldbereset,andthecurrentcommandshouldbedisplayed.Youshouldseesomethinglikethefollowing:

ReadytoAcceptnewCommand=>RawCommandfromSerialMonitor:vgapChangingcommandorparametersaccordingtoyourinput:Commandorparametervgapsucessfullyset…RESETTINGALLREGISTERSBYSETTINGCOM7REGISTERto0x80:I2COperationOK…CurrentCommand:

Page 184: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

Command:VGAPFPSParam:ThirtyFPSAWBParam:SAWBAECParam:HistAECYUVMatrixParam:YUVMatrixOffDenoiseParam:DenoiseNoEdgeParam:EdgeNoABLCParam:AblcON

14.Now,sendtheArduinothe“t”commandtoactuallytakethephoto.Thecurrentcamerasettingsshouldbedisplayed,adetailedlistofregistersettingoperationsshouldbedisplayed,thecontentsofkeyregistersaredisplayed,andSDcardrelatedinformationisdisplayed.SeeFigure6-12foraphotoItookusingthesecamerasettings.Youshouldseeoutputsimilartothefollowing:

ReadytoAcceptnewCommand=>RawCommandfromSerialMonitor:tGoingtotakephotowithcurrentcommand:CurrentCommand:Command:VGAPFPSParam:ThirtyFPSAWBParam:SAWBAECParam:HistAECYUVMatrixParam:YUVMatrixOffDenoiseParam:DenoiseNoEdgeParam:EdgeNoABLCParam:AblcONTakingaVGAPPhoto…RESETTINGALLREGISTERSBYSETTINGCOM7REGISTERto0x80:I2COperationOK…–––––––––SettingCameraforVGA(RawRGB)––––––––—PhotoWidth=640PhotoHeight=480BytesPerPixel=1CLKRC:I2COperationOK…COM7:I2COperationOK…COM3:I2COperationOK…COM14:I2COperationOK…SCALING_XSC:I2COperationOK…SCALING_YSC:I2COperationOK…SCALING_DCWCTR:I2COperationOK…SCALING_PCLK_DIV:I2COperationOK…SCALING_PCLK_DELAY:I2COperationOK…COM17:I2COperationOK…………..SettingCamerato30FPS……..CLKRC:I2COperationOK…DBLV:I2COperationOK…EXHCH:I2COperationOK…EXHCL:I2COperationOK…DM_LNL:I2COperationOK…

Page 185: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

DM_LNH:I2COperationOK…COM11:I2COperationOK…––––—SettingCameraHistogramBasedAEC/AGCRegisters––––—AEW:I2COperationOK…AEB:I2COperationOK…HAECC1:I2COperationOK…HAECC2:I2COperationOK…HAECC3:I2COperationOK…HAECC4:I2COperationOK…HAECC5:I2COperationOK…HAECC6:I2COperationOK…HAECC7:I2COperationOK…SettingB0UNDOCUMENTEDregisterto0x84:=I2COperationOK…………..SettingCameraSaturationLevel……..SATCTR:I2COperationOK…………..SettingCameraArrayControl……..CHLF:I2COperationOK…ARBLM:I2COperationOK…………..SettingCameraADCControl……..ADCCTR1:I2COperationOK…ADCCTR2:I2COperationOK…ADC:I2COperationOK…ACOM:I2COperationOK…OFON:I2COperationOK………..SettingCameraABLC…….ABLC1:I2COperationOK…THL_ST:I2COperationOK…………..SettingCameraWindowOutputParameters……..HSTART:I2COperationOK…HSTOP:I2COperationOK…HREF:I2COperationOK…VSTRT:I2COperationOK…VSTOP:I2COperationOK…VREF:I2COperationOK…––––-SettingCameraforVGA(ProcessedBayerRGB)–––––COM7:I2COperationOK…InitializingTSLBregisterresult=I2COperationOK…SettingB0UNDOCUMENTEDregisterto0x84:=I2COperationOK…………..SettingCameratoSimpleAWB……..COM8(0x13):I2COperationOK…AWBCTR0ControlRegister0(0x6F):I2COperationOK…………..SettingCameraGain……..COM9:I2COperationOK…BLUEGAIN:I2COperationOK…REDGAIN:I2COperationOK…GREENGAIN:I2COperationOK…COM16(ENABLEGAIN):I2COperationOK…

Page 186: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

–––––––––—CameraRegisters–––––––––CLKRC=80COM7=5COM3=0COM14=0SCALING_XSC=3ASCALING_YSC=35SCALING_DCWCTR=11SCALING_PCLK_DIV=F0SCALING_PCLK_DELAY=2TSLB(YUVOrder-HigherBit,Bit[3])=4COM13(YUVOrder-LowerBit,Bit[1])=88COM17(DSPColorBarSelection)=0COM4(workswithCOM17)=0COM15(COLORFORMATSELECTION)=C0COM11(NightMode)=ACOM8(ColorControl,AWB)=E7HAECC7(AECAlgorithmSelection)=94GFIX=0HSTART=13HSTOP=1HREF=B6VSTRT=2VSTOP=7AVREF=A––––––––––––––––––––––––—StartingCaptureofPhoto…TimeforFrameCapture(milliseconds)=87VSyncbeginningduration(microseconds)=385VSyncendduration(microseconds)=385StartingTransmissionofPhotoToSDCard…TotalBytesSavedtoSDCard=307200WritingPhoto’sInfofile(.txtfile)toSDCard…ElapsedTimeforTakingandSendingPhoto(secs)=30PhotoTakenandSavedtoArduinoSDCARD…ImageOutputFilename:VGAP7.raw

Page 187: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

Figure6-12.VGAPmodephoto

15.Nextletschangethecamera’sparameterssothatedgeenhancementison.Whatthisdoesisincreasethesharpnessofthefinalphoto.Sendthevalue“edgeyes”totheArduinotoactivatetheedgeenhancement.Thecommandshouldbeconfirmed,theregistersreset,andthecurrentcamerasettingdisplayed.Theoutputshouldlooklikethefollowing:

ReadytoAcceptnewCommand=>RawCommandfromSerialMonitor:edgeyesChangingcommandorparametersaccordingtoyourinput:Commandorparameteredgeyessucessfullyset…RESETTINGALLREGISTERSBYSETTINGCOM7REGISTERto0x80:I2COperationOK…CurrentCommand:Command:VGAPFPSParam:ThirtyFPSAWBParam:SAWBAECParam:HistAECYUVMatrixParam:YUVMatrixOff

Page 188: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

DenoiseParam:DenoiseNoEdgeParam:EdgeYesABLCParam:AblcON

16.Next,takethephotobysendingtheArduinothe“t”value.Thetextoutputshouldbesimilartopreviousexamples.SeeFigure6-13forthephotoItookusingthesecamerasettings.Thekeythingtonotehereisthatthereshouldbeasectionthatshowsthatthatedgeenhancementisnowactivesuchasshowninthefollowing:

………..SettingCameraEdgeEnhancement……..EDGE:I2COperationOK…REG75:I2COperationOK…REG76:I2COperationOK…COM16:I2COperationOK…

Figure6-13.VGAphotowithedgeenhancementon

TakingVGAPhotos

17.Next,switchtoVGAbysending“vga”totheArudino.Thecommandshouldbe

Page 189: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

confirmed,thecameraregistersshouldberesetandthecurrentcamerasettingsshouldbedisplayedasinthefollowingoutput:

ReadytoAcceptnewCommand=>RawCommandfromSerialMonitor:vgaChangingcommandorparametersaccordingtoyourinput:Commandorparametervgasucessfullyset…RESETTINGALLREGISTERSBYSETTINGCOM7REGISTERto0x80:I2COperationOK…CurrentCommand:Command:VGAFPSParam:ThirtyFPSAWBParam:SAWBAECParam:HistAECYUVMatrixParam:YUVMatrixOffDenoiseParam:DenoiseNoEdgeParam:EdgeYesABLCParam:AblcON

18.Next,takeaphotobysendinga“t”charactertotheArduino.Thecurrentcamerasettingsshouldbedisplayed,thecameraregistersaresettotherequiredvalues,thevaluesofkeycameraregistersaredisplayedandphotofileinformationisdisplayed.See6-14foraphotoItookusingthesecamerasettings.Thetextoutputshouldlooksimilartothefollowing:

ReadytoAcceptnewCommand=>RawCommandfromSerialMonitor:tGoingtotakephotowithcurrentcommand:CurrentCommand:Command:VGAFPSParam:ThirtyFPSAWBParam:SAWBAECParam:HistAECYUVMatrixParam:YUVMatrixOffDenoiseParam:DenoiseNoEdgeParam:EdgeYesABLCParam:AblcONTakingaVGAPhoto…RESETTINGALLREGISTERSBYSETTINGCOM7REGISTERto0x80:I2COperationOK…–––––––––SettingCameraforVGA(RawRGB)––––––––—PhotoWidth=640PhotoHeight=480BytesPerPixel=1CLKRC:I2COperationOK…COM7:I2COperationOK…COM3:I2COperationOK…COM14:I2COperationOK…SCALING_XSC:I2COperationOK…

Page 190: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

SCALING_YSC:I2COperationOK…SCALING_DCWCTR:I2COperationOK…SCALING_PCLK_DIV:I2COperationOK…SCALING_PCLK_DELAY:I2COperationOK…COM17:I2COperationOK…………..SettingCamerato30FPS……..CLKRC:I2COperationOK…DBLV:I2COperationOK…EXHCH:I2COperationOK…EXHCL:I2COperationOK…DM_LNL:I2COperationOK…DM_LNH:I2COperationOK…COM11:I2COperationOK…––––—SettingCameraHistogramBasedAEC/AGCRegisters––––—AEW:I2COperationOK…AEB:I2COperationOK…HAECC1:I2COperationOK…HAECC2:I2COperationOK…HAECC3:I2COperationOK…HAECC4:I2COperationOK…HAECC5:I2COperationOK…HAECC6:I2COperationOK…HAECC7:I2COperationOK…SettingB0UNDOCUMENTEDregisterto0x84:=I2COperationOK…………..SettingCameraSaturationLevel……..SATCTR:I2COperationOK…………..SettingCameraArrayControl……..CHLF:I2COperationOK…ARBLM:I2COperationOK…………..SettingCameraADCControl……..ADCCTR1:I2COperationOK…ADCCTR2:I2COperationOK…ADC:I2COperationOK…ACOM:I2COperationOK…OFON:I2COperationOK………..SettingCameraABLC…….ABLC1:I2COperationOK…THL_ST:I2COperationOK…………..SettingCameraWindowOutputParameters……..HSTART:I2COperationOK…HSTOP:I2COperationOK…HREF:I2COperationOK…VSTRT:I2COperationOK…VSTOP:I2COperationOK…VREF:I2COperationOK…–––––––––—CameraRegisters–––––––––CLKRC=80COM7=1

Page 191: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

COM3=0COM14=0SCALING_XSC=3ASCALING_YSC=35SCALING_DCWCTR=11SCALING_PCLK_DIV=F0SCALING_PCLK_DELAY=2TSLB(YUVOrder-HigherBit,Bit[3])=DCOM13(YUVOrder-LowerBit,Bit[1])=88COM17(DSPColorBarSelection)=0COM4(workswithCOM17)=0COM15(COLORFORMATSELECTION)=C0COM11(NightMode)=ACOM8(ColorControl,AWB)=8FHAECC7(AECAlgorithmSelection)=94GFIX=0HSTART=13HSTOP=1HREF=B6VSTRT=2VSTOP=7AVREF=A––––––––––––––––––––––––—StartingCaptureofPhoto…TimeforFrameCapture(milliseconds)=90VSyncbeginningduration(microseconds)=392VSyncendduration(microseconds)=392StartingTransmissionofPhotoToSDCard…TotalBytesSavedtoSDCard=307200WritingPhoto’sInfofile(.txtfile)toSDCard…ElapsedTimeforTakingandSendingPhoto(secs)=30PhotoTakenandSavedtoArduinoSDCARD…ImageOutputFilename:VGA12.raw

Note:SinceVGAmodedoesnotincludedigitalsignalprocessingontheimage,featureslikeedgeenhancementthatusetheDigitalSignalProcessorinthecamerawillnotwork.

Page 192: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

Figure6-14.VGAphoto

TransferringthePhotostoyourComputer

InordertotransferyourphotosfromtheSDcardtoyourcomputerforfinalprocessingyouwillneedanotherSDcardreaderdesignedtoworkwithyourcomputer.

Ipurchasedthe“TranscendInformationUSB3.0CardReader(TS-RDF5K)”fromAmazon.comtotransfermyfilestomyWindowsbasedPC.SeeFigure6-15.ThereweresomereviewscomplainingofoverheatingafterusebutIdidnotencounteranyproblemswithexcessiveheatingoftheSDcardreader.

YouwillneedtostickyourSDcardintotheslotmarkedasSD.ThensticktheSDcardreaderintoanavailableUSBslotonyourcomputer.ThecomputershouldrecognizetheSDcardreaderasjustanotherdiskdrive.YoucanusetheWindowsExplorertocopyfilesfromtheSDcardtoafolderonyourharddiskdrive.

Page 193: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

Figure6-15.SDcardreaderforPC

ConvertingthePhotostoPNG(PortableNetworkGraphics)Format

OnceyougetyourfilestoyourcomputeryouwillneedtoconvertthesefilestoaformthatiseasilyreadableandviewablesuchasthePNGimageformat.Todothisyouwillneedaprogramcalledffmpeg.

Theofficialwebsitefortheffmpegprogramishttps://www.ffmpeg.org/Youshouldgothereanddownloadthelatestversionforyourcomputersystem.Itisfreeandavailableatnocharge.

Note:TheffmpegversionIusedforthisbookis“2015-03-12git-3bedc99”.IfyouarehavingproblemsconvertingthecameraimagesintoaviewablePNGfilethentrytodownloadthisversionofffmpeg.

FFMPEGCONVERSION

Thissectiondescribestheffmpegcommandlineoptionsthatarerequiredtoconverttheimagesintoaneasilyviewableformat.TheimagesfromthecamerathatarerecordedinYUVandRawBayerformatareconvertedtoPNGfiles.PNGstandsforportablenetworkgraphicsfilewhichisacommonimagefiletypethatcanbeviewedinWindowsExplorerorthoughapaintprogramlikePaintShopPro.

Note:ForeachofthefollowingcommandsreplaceINPUTFILE.YUVorINPUTFILE.RAWwiththeactualfilenameoftheYUVfileorBayerRAWfileyouwanttocovert.ChangetheOUTPUTFILE.PNGfilenametothefilenameyouwanttosavethenewimageas.

QQVGAffmpeg-frawvideo-s160x120-pix_fmtyuyv422-iINPUTFILE.YUV-fimage2-vcodecpngOUTPUTFILE.PNGQVGAffmpeg-frawvideo-s320x240-pix_fmtyuyv422-iINPUTFILE.YUV-fimage2-vcodecpngOUTPUTFILE.PNGVGAffmpeg-frawvideo-s640x480-pix_fmtbayer_bggr8-iINPUTFILE.RAW-f

Page 194: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

image2-vcodecpngOUTPUTFILE.PNG

Aneasywaytoconvertthefilesistocopytheimagefilesintothesamedirectorywhereyourffmpeg.exeislocated.Thenyoucancreateadirectorysuchas“outputdir”toholdtheprocessedimages.Basedontheimagefilenameyoucanchooseoneofthecommandsbelowtoconvertthefileandtoplacetheconvertedimagefileintoadirectory.

Note:Replacethe“outputdir”namewiththenameofthedirectorythatyouwanttosavetheconvertedfilein.QQVGAffmpeg-frawvideo-s160x120-pix_fmtyuyv422-iINPUTFILE.YUV-fimage2-vcodecpngoutputdir\OUTPUTFILE.PNGQVGAffmpeg-frawvideo-s320x240-pix_fmtyuyv422-iINPUTFILE.YUV-fimage2-vcodecpngoutputdir\OUTPUTFILE.PNGVGAffmpeg-frawvideo-s640x480-pix_fmtbayer_bggr8-iINPUTFILE.RAW-fimage2-vcodecpngoutputdir\OUTPUTFILE.PNG

Page 195: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

Summary

Thischapterprovidedaquickstartguidetotakingphotoswiththeov7670cameraandsavingthemusingaSDcard.SDcardreaderconnectionsandcameraconnectionstotheArduinoareshown.Theimagecapturesoftwareisdiscussedandstepbystepinstructionsonhowtouseitaregiven.ThenIshowhowtotransferthesephotostoyourcomputerandthenconvertthemintoviewableimages.

Page 196: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

AppendixA:CameraRegisterDefinesThisappendixliststhe#definesrelatedtothecameraregisters.//Registeraddressesandvalues#defineCLKRC0x11#defineCLKRC_VALUE_VGA0x01//RawBayer#defineCLKRC_VALUE_QVGA0x01#defineCLKRC_VALUE_QQVGA0x01#defineCLKRC_VALUE_NIGHTMODE_FIXED0x03//FixedFrame#defineCLKRC_VALUE_NIGHTMODE_AUTO0x80//AutoFrameRateAdjust#defineCOM70x12#defineCOM7_VALUE_VGA0x01//RawBayer#defineCOM7_VALUE_VGA_COLOR_BAR0x03//RawBayer#defineCOM7_VALUE_VGA_PROCESSED_BAYER0x05//ProcessedBayer#defineCOM7_VALUE_QVGA0x00#defineCOM7_VALUE_QVGA_COLOR_BAR0x02#defineCOM7_VALUE_QVGA_PREDEFINED_COLOR_BAR0x12#defineCOM7_VALUE_QQVGA0x00#defineCOM7_VALUE_QQVGA_COLOR_BAR0x02#defineCOM7_VALUE_RESET0x80#defineCOM30x0C#defineCOM3_VALUE_VGA0x00//RawBayer#defineCOM3_VALUE_QVGA0x04#defineCOM3_VALUE_QQVGA0x04//FromDocs#defineCOM3_VALUE_QQVGA_SCALE_ENABLED0x0C//EnableScaleandDCW#defineCOM140x3E#defineCOM14_VALUE_VGA0x00//RawBayer#defineCOM14_VALUE_QVGA0x19#defineCOM14_VALUE_QQVGA0x1A#defineCOM14_VALUE_MANUAL_SCALING0x08//ManualScalingEnabled#defineCOM14_VALUE_NO_MANUAL_SCALING0x00//ManualScalingDisEnabled#defineSCALING_XSC0x70#defineSCALING_XSC_VALUE_VGA0x3A//RawBayer#defineSCALING_XSC_VALUE_QVGA0x3A#defineSCALING_XSC_VALUE_QQVGA0x3A#defineSCALING_XSC_VALUE_QQVGA_SHIFT10x3A#defineSCALING_XSC_VALUE_COLOR_BAR0xBA#defineSCALING_YSC0x71#defineSCALING_YSC_VALUE_VGA0x35//RawBayer#defineSCALING_YSC_VALUE_QVGA0x35#defineSCALING_YSC_VALUE_QQVGA0x35#defineSCALING_YSC_VALUE_COLOR_BAR0x35//8barcolorbar#defineSCALING_YSC_VALUE_COLOR_BAR_GREY0xB5//fadetogreycolorbar#defineSCALING_YSC_VALUE_COLOR_BAR_SHIFT10xB5//fadetogreycolorbar

Page 197: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

#defineSCALING_DCWCTR0x72#defineSCALING_DCWCTR_VALUE_VGA0x11//RawBayer#defineSCALING_DCWCTR_VALUE_QVGA0x11

#defineSCALING_DCWCTR_VALUE_QQVGA0x22#defineSCALING_PCLK_DIV0x73

#defineSCALING_PCLK_DIV_VALUE_VGA0xF0//RawBayer#defineSCALING_PCLK_DIV_VALUE_QVGA0xF1#defineSCALING_PCLK_DIV_VALUE_QQVGA0xF2#defineSCALING_PCLK_DELAY0xA2#defineSCALING_PCLK_DELAY_VALUE_VGA0x02//RawBayer#defineSCALING_PCLK_DELAY_VALUE_QVGA0x02#defineSCALING_PCLK_DELAY_VALUE_QQVGA0x02//ControlsYUVorderUsedwithCOM13//NeedYUYVformatforAndroidDecoding-Defaultvalueis0xD#defineTSLB0x3A#defineTSLB_VALUE_YUYV_AUTO_OUTPUT_WINDOW_ENABLED0x01//Nocustomscaling#defineTSLB_VALUE_YUYV_AUTO_OUTPUT_WINDOW_DISABLED0x00//ForadjustingHSTART,etc.YUYVformat#defineTSLB_VALUE_UYVY_AUTO_OUTPUT_WINDOW_DISABLED0x08#defineTSLB_VALUE_TESTVALUE0x04//FromYCbCrReference//Defaultvalueis0x88//okifyouwantYUYVorder,noneedtochange#defineCOM130x3D#defineCOM13_VALUE_DEFAULT0x88#defineCOM13_VALUE_NOGAMMA_YUYV0x00#defineCOM13_VALUE_GAMMA_YUYV0x80#defineCOM13_VALUE_GAMMA_YVYU0x82#defineCOM13_VALUE_YUYV_UVSATAUTOADJ_ON0x40//WorkswithCOM4#defineCOM170x42#defineCOM17_VALUE_AEC_NORMAL_NO_COLOR_BAR0x00#defineCOM17_VALUE_AEC_NORMAL_COLOR_BAR0x08//ActivateColorBarforDSP#defineCOM40x0D//RGBSettingsandDataformat#defineCOM150x40//NightMode#defineCOM110x3B#defineCOM11_VALUE_NIGHTMODE_ON0x80//NightMode#defineCOM11_VALUE_NIGHTMODE_OFF0x00#defineCOM11_VALUE_NIGHTMODE_ON_EIGHTH0xE0//NightMode1/8framerateminimum#defineCOM11_VALUE_NIGHTMODE_FIXED0x0A#defineCOM11_VALUE_NIGHTMODE_AUTO0xEA//NightModeAutoFrameRateAdjust

Page 198: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

//ColorMatrixControlYUV#defineMTX10x4f#defineMTX1_VALUE0x80#defineMTX20x50#defineMTX2_VALUE0x80#defineMTX30x51#defineMTX3_VALUE0x00#defineMTX40x52#defineMTX4_VALUE0x22#defineMTX50x53#defineMTX5_VALUE0x5e#defineMTX60x54#defineMTX6_VALUE0x80#defineCONTRAS0x56#defineCONTRAS_VALUE0x40#defineMTXS0x58#defineMTXS_VALUE0x9e//COM8#defineCOM80x13#defineCOM8_VALUE_AWB_OFF0xE5#defineCOM8_VALUE_AWB_ON0xE7//AutomaticWhiteBalance#defineAWBC10x43#defineAWBC1_VALUE0x14#defineAWBC20x44#defineAWBC2_VALUE0xf0#defineAWBC30x45#defineAWBC3_VALUE0x34#defineAWBC40x46#defineAWBC4_VALUE0x58#defineAWBC50x47#defineAWBC5_VALUE0x28#defineAWBC60x48#defineAWBC6_VALUE0x3a#defineAWBC70x59#defineAWBC7_VALUE0x88#defineAWBC80x5A#defineAWBC8_VALUE0x88#defineAWBC90x5B#defineAWBC9_VALUE0x44#defineAWBC100x5C#defineAWBC10_VALUE0x67#defineAWBC110x5D#defineAWBC11_VALUE0x49#defineAWBC120x5E#defineAWBC12_VALUE0x0E#defineAWBCTR30x6C#defineAWBCTR3_VALUE0x0A#defineAWBCTR20x6D

Page 199: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

#defineAWBCTR2_VALUE0x55#defineAWBCTR10x6E#defineAWBCTR1_VALUE0x11#defineAWBCTR00x6F#defineAWBCTR0_VALUE_NORMAL0x9F#defineAWBCTR0_VALUE_ADVANCED0x9E//Gain#defineCOM90x14#defineCOM9_VALUE_MAX_GAIN_128X0x6A#defineCOM9_VALUE_4XGAIN0x10//00010000#defineBLUE0x01//AWBBlueChannelGain#defineBLUE_VALUE0x40#defineRED0x02//AWBRedChannelGain#defineRED_VALUE0x40#defineGGAIN0x6A//AWBGreenChannelGain#defineGGAIN_VALUE0x40#defineCOM160x41#defineCOM16_VALUE0x08//AWBGainon#defineGFIX0x69#defineGFIX_VALUE0x00//EdgeEnhancementAdjustment#defineEDGE0x3f#defineEDGE_VALUE0x00#defineREG750x75#defineREG75_VALUE0x03#defineREG760x76#defineREG76_VALUE0xe1//DeNoise#defineDNSTH0x4c#defineDNSTH_VALUE0x00#defineREG770x77#defineREG77_VALUE0x00//DenoiseandEdgeEnhancement#defineCOM16_VALUE_DENOISE_OFF_EDGE_ENHANCEMENT_OFF_AWBGAIN_ON0x08//Denoiseoff,AWBGainon#defineCOM16_VALUE_DENOISE_ON__EDGE_ENHANCEMENT_OFF__AWBGAIN_ON0x18#defineCOM16_VALUE_DENOISE_OFF__EDGE_ENHANCEMENT_ON__AWBGAIN_ON0x28#defineCOM16_VALUE_DENOISE_ON__EDGE_ENHANCEMENT_ON__AWBGAIN_ON0x38//Denoiseon,EdgeEnhancementon,AWBGainon//30FPSFrameRate,PCLK=24Mhz#defineCLKRC_VALUE_30FPS0x80#defineDBLV0x6b

Page 200: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

#defineDBLV_VALUE_30FPS0x0A#defineEXHCH0x2A#defineEXHCH_VALUE_30FPS0x00#defineEXHCL0x2B#defineEXHCL_VALUE_30FPS0x00#defineDM_LNL0x92#defineDM_LNL_VALUE_30FPS0x00#defineDM_LNH0x93#defineDM_LNH_VALUE_30FPS0x00#defineCOM11_VALUE_30FPS0x0A//SaturationControl#defineSATCTR0xc9#defineSATCTR_VALUE0x60//AEC/AGC-AutomaticExposure/GainControl#defineGAIN0x00#defineGAIN_VALUE0x00#defineAEW0x24#defineAEW_VALUE0x95#defineAEB0x25#defineAEB_VALUE0x33#defineVPT0x26#defineVPT_VALUE0xe3//AEC/AGCControl-Histogram#defineHAECC10x9f#defineHAECC1_VALUE0x78#defineHAECC20xa0#defineHAECC2_VALUE0x68#defineHAECC30xa6#defineHAECC3_VALUE0xd8#defineHAECC40xa7#defineHAECC4_VALUE0xd8#defineHAECC50xa8#defineHAECC5_VALUE0xf0#defineHAECC60xa9#defineHAECC6_VALUE0x90#defineHAECC70xaa//AECAlgorithmselection#defineHAECC7_VALUE_HISTOGRAM_AEC_ON0x94#defineHAECC7_VALUE_AVERAGE_AEC_ON0x00//ArrayControl#defineCHLF0x33#defineCHLF_VALUE0x0b#defineARBLM0x34#defineARBLM_VALUE0x11//ADCControl#defineADCCTR10x21#defineADCCTR1_VALUE0x02#defineADCCTR20x22#defineADCCTR2_VALUE0x91

Page 201: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

#defineADC0x37#defineADC_VALUE0x1d#defineACOM0x38#defineACOM_VALUE0x71#defineOFON0x39#defineOFON_VALUE0x2a//BlackLevelCalibration#defineABLC10xb1#defineABLC1_VALUE0x0c#defineTHL_ST0xb3#defineTHL_ST_VALUE0x82//WindowOutput#defineHSTART0x17#defineHSTART_VALUE_DEFAULT0x11#defineHSTART_VALUE_VGA0x13#defineHSTART_VALUE_QVGA0x13#defineHSTART_VALUE_QQVGA0x13//Works#defineHSTOP0x18#defineHSTOP_VALUE_DEFAULT0x61#defineHSTOP_VALUE_VGA0x01#defineHSTOP_VALUE_QVGA0x01#defineHSTOP_VALUE_QQVGA0x01//Works#defineHREF0x32#defineHREF_VALUE_DEFAULT0x80#defineHREF_VALUE_VGA0xB6#defineHREF_VALUE_QVGA0x24#defineHREF_VALUE_QQVGA0xA4#defineVSTRT0x19#defineVSTRT_VALUE_DEFAULT0x03#defineVSTRT_VALUE_VGA0x02#defineVSTRT_VALUE_QVGA0x02#defineVSTRT_VALUE_QQVGA0x02#defineVSTOP0x1A#defineVSTOP_VALUE_DEFAULT0x7B#defineVSTOP_VALUE_VGA0x7A#defineVSTOP_VALUE_QVGA0x7A#defineVSTOP_VALUE_QQVGA0x7A#defineVREF0x03#defineVREF_VALUE_DEFAULT0x03#defineVREF_VALUE_VGA0x0A#defineVREF_VALUE_QVGA0x0A#defineVREF_VALUE_QQVGA0x0A

Page 202: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

AppendixB:ImageCaptureProgramVariablesconstintchipSelect=48;constintHardwareSSPin=53;//ForArduinoMegaintPhotoTakenCount=0;//SerialInputconstintBUFFERLENGTH=255;charIncomingByte[BUFFERLENGTH];//forincomingserialdata//VGADefaultintPHOTO_WIDTH=640;intPHOTO_HEIGHT=480;intPHOTO_BYTES_PER_PIXEL=2;//CommandandParameterrelatedStringsStringRawCommandLine=””;StringCommand=“QQVGA”;StringFPSParam=“ThirtyFPS”;StringAWBParam=“SAWB”;StringAECParam=“HistAEC”;StringYUVMatrixParam=“YUVMatrixOn”;StringDenoiseParam=“DenoiseNo”;StringEdgeParam=“EdgeNo”;StringABLCParam=“AblcON”;enumResolutionType{VGA,VGAP,QVGA,QQVGA,None};ResolutionTypeResolution=None;//Camerainput/outputpinconnectiontoArduino#defineWRST22//OutputWritePointerReset#defineRRST23//OutputReadPointerReset#defineWEN24//OutputWriteEnable#defineVSYNC25//InputVerticalSyncmarkingframecapture#defineRCLK26//OutputFIFObufferoutputclock//setOEtolowgnd//FIFORaminputpins#defineDO728#defineDO629#defineDO530#defineDO431#defineDO332

Page 203: Beginning Arduino ov7670 Camera Developmentpdf.ebook777.com/039/B010Y37XQG.pdf · the ov7670 camera using an Arduino Mega 2560 and how to use a ... It comes in two versions one without

#defineDO233#defineDO134#defineDO035//I2C#defineOV7670_I2C_ADDRESS0x21#defineI2C_ERROR_WRITING_START_ADDRESS11#defineI2C_ERROR_WRITING_DATA22#defineDATA_TOO_LONG1//datatoolongtofitintransmitbuffer#defineNACK_ON_TRANSMIT_OF_ADDRESS2//receivedNACKontransmitofaddress#defineNACK_ON_TRANSMIT_OF_DATA3//receivedNACKontransmitofdata#defineOTHER_ERROR4//othererror#defineI2C_READ_START_ADDRESS_ERROR33#defineI2C_READ_DATA_SIZE_MISMATCH_ERROR44