You are on page 1of 59

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

CANINTERVIEWQUESTIONS: 1.WhatisCAN? Answer:1.CANisamultimasterbroadcastserialbusstandardforconnectingelectroniccontrol unit(ECUs). 2.Controllerareanetwork(CANorCANbus)isavehiclebusstandarddesignedtoallow microcontrollersadevicestocommunicatewitheachotherwithinavehiclewithoutahostcomputer. 3.CANisamessagebasedprotocol,designedspecicallyforautomotiveapplicationsbutnowalso usedinotherareassuchasindustrialautomationandmedicalequipment. 4.TheControllerAreaNetwork(CAN)busisaserialasynchronousbususedininstrumentation applicationsforindustriessuchasautomobiles 2.CANframeworks? Answer:SOF1Dominant ArbitrationField11bitIdentier,1bitRTR(or)11bit,1SRR,1IDE,18bit,1RTR ControlFieldIDE,r0,4bits(DLC) DataField(08)Bytes CRCField15bits,Delimiter(1bitrecessive) ACKField1bit,Delimiter(1bitrecessive) EOF7bitsrecessive IFS3bitsrecessive

1 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

TypesofframesData,remote,ErrorframeandOverloadframe TypesoferrorsACKerror,Biterror,Stuerror,Formerror,CRCerror Errorframe012superpositionags,8recessive(Delimiter) Overloadframe012superpositionags,8recessive(Delimiter) 3.WhyCANishaving120ohmsateachend? Answer:Tominimizethereectionreference,toreducenoise.Toensurethatreectiondoesnot causecommunicationfailure,thetransmissionlinemustbeterminated. 4.WhyCANismessageorientedprotocol? Answer:CANprotocolisamessagebasedprotocol,notanaddressbasedprotocol.Thismeansthat messagesarenottransmittedfromonenodetoanothernodebasedonaddresses.Embeddedinthe CANmessageitselfisthepriorityandthecontentsofthedatabeingtransmitted.Allnodesinthe systemreceiveeverymessagetransmittedonthebus(andwillacknowledgeifthemessagewas properlyreceived).Itisuptoeachnodeinthesystemtodecidewhetherthemessagereceivedshould beimmediatelydiscardedorkepttobeprocessed.Asinglemessagecanbedestinedforone particularnodetoreceive,ormanynodesbasedonthewaythenetworkandsystemaredesigned. Forexample,anautomotiveairbagsensorcanbeconnectedviaCANtoasafetysystemrouternode only.Thisrouternodetakesinothersafetysysteminformationandroutesittoallothernodesonthe safetysystemnetwork.Thenalltheothernodesonthesafetysystemnetworkcanreceivethelatest airbagsensorinformationfromtherouteratthesametime,acknowledgeifthemessagewasreceived properly,anddecidewhethertoutilizethisinformationordiscardit. 5.CANlogicwhatitfollows? Answer:WiredANDlogic 6.WhatisCANArbitration? Answer:CANArbitrationisnothingbutthenodetryingtotakecontrolontheCANbus. 7.HowCANwillfollowtheArbitration? Answer:CSMA/CD+AMP(ArbitrationonMessagePriority) Twobusnodeshavegotatransmissionrequest.ThebusaccessmethodisCSMA/CD+AMP(Carrier SenseMultipleAccesswithCollisionDetectionandArbitrationonMessagePriority).Accordingto thisalgorithmbothnetworknodeswaituntilthebusisfree(CarrierSense).Inthatcasethebusisfree bothnodestransmittheirdominantstartbit(MultipleAccess).Everybusnodereadsbackbitbybit fromthebusduringthecompletemessageandcomparesthetransmittedvaluewiththereceived value.Aslongasthebitsareidenticalfrombothtransmittersnothinghappens.Thersttimethere th wasadierenceinthisexamplethe7 bitofthemessagethearbitrationprocesstakesplace: NodeAtransmitsadominantlevel,nodeBtransmitsarecessivelevel.Therecessivelevelwillbe overwrittenbythedominantlevel.ThisisdetectedbynodeBbecausethetransmittedvalueisnot equaltothereceivedvalue(CollisionDetection).AtthispointoftimenodeBhaslostthearbitration,

2 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

stopsthetransmissionofanyfurtherbitimmediatelyandswitchestoreceivemode,becausethe messagethathaswonthearbitrationmustpossiblybeprocessedbythisnode(Arbitrationon MessagePriority) Forexample,considerthreeCANdeviceseachtryingtotransmitmessages: Device1address433(decimalor00110110001binary) Device2address154(00010011010) Device3address187(00010111011) Assumingallthreeseethebusisidleandbegintransmittingatthesametime,thisishowthe arbitrationworksout.Allthreedeviceswilldrivethebustoadominantstateforthestartofframe (SOF)andthetwomostsignicantbitsofeachmessageidentier.Eachdevicewillmonitorthebus anddeterminesuccess.Whentheywritebit8ofthemessageID,thedevicewritingmessageID433 willnoticethatthebusisinthedominantstatewhenitwastryingtoletitberecessive,soitwill assumeacollisionandgiveupfornow.Theremainingdeviceswillcontinuewritingbitsuntilbit5, thenthedevicewritingmessageID187willnoticeacollisionandaborttransmission.Thisleavesthe devicewritingmessageID154remaining.Itwillcontinuewritingbitsonthebusuntilcompleteoran errorisdetected.Noticethatthismethodofarbitrationwillalwayscausethelowestnumericalvalue messageIDtohavepriority.Thissamemethodofbitwisearbitrationandprioritizationappliestothe 18bitextensionintheextendedformataswell. 8.WhatisthespeedofCAN? Answer:40m@1Mbpsandifthecablelengthincreaseswilldecreasethespeed,duetoRLConthe cable. 9.Ifmastersends764andSlavesends744whichwillgetthearbitration? Answer:StartsfromMSB,rstnibbleissame,Mastersends7,slavesalsosends7themessagewith moredominantbitswillgainthearbitration,lowestthemessageidentierhigherthepriority. 10.StandardCANandExtendedCANdierence? Answer:Numberofidentierscanbeaccommodatedforstandardframeare2power11. Numberofidentiersmorecomparetobaseframe,forextendedframeare2power29. IDEbit1forextendedframe. IDEbit0forStandardframe. 11.Whatisbitstung? Answer:CANusesaNonReturntoZeroprotocol,NRZ5,withbitstung.Theideabehindbit stungistoprovideaguaranteededgeonthesignalsothereceivercanresynchronizewiththe transmitterbeforeminorclockdiscrepanciesbetweenthetwonodescancauseaproblem.With NRZ5thetransmittertransmitsatmostveconsecutivebitswiththesamevalue.Aftervebitswith thesamevalue(zeroorone),thetransmitterinsertsastubitwiththeoppositestate.

3 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

12.Whatistheuseofbitstung? Answer:LongNRZmessagescauseproblemsinreceivers Clockdriftmeansthatiftherearenoedges,receiverslosetrackofbits Periodicedgesallowreceivertoresynchronizetosenderclock 13.WhatarethefunctionsofCANtransceiver? Answer:Thetransceiverprovidesdierentialtransmitcapabilitytothebusanddierentialreceive capabilitytotheCANcontroller.Transceiverprovidesanadvancedinterfacebetweentheprotocol controllerandthephysicalbusinaControllerAreaNetwork(CAN)node. Typically,eachnodeinaCANsystemmusthaveadevicetoconvertthedigitalsignalsgeneratedby aCANcontrollertosignalssuitablefortransmissionoverthebuscabling(dierentialoutput).Italso providesabuerbetweentheCANcontrollerandthehighvoltagespikesthatcanbegeneratedon theCANbusbyoutsidesources(EMI,ESD,electricaltransients,etc.). ThecantransceiverisadevicewhichdetectsthesignallevelsthatareusedontheCANbustothe logicalsignallevelsrecognizedbyamicrocontroller. 14.FunctionalityofDatalinklayerinCAN? Answer:LLC(LogicalLinkControl)Overloadcontrol,notication,MessagelteringandRecovery managementfunctions. MAC(MediumAccessControl)Encapsulation/decapsulation,errordetectionandcontrol,stung anddestungandserialization/deserialization. 15.Whatismeantbysynchronization? Answer:Synchronizationistimekeepingwhichrequiresthecoordinationofeventstooperatea systeminunison. 16.WhatismeantbyHardsynchronizationandsoftsynchronization? Answer:HardSynchronizationtobeperformedateveryedgefromrecessivetodominantedge duringBusIdle.Additionally,HardSynchronizationisrequiredforeachreceivedSOFbit.AnSOF bitcanbereceivedbothduringBusIdle,andalsoduringSuspendTransmissionandattheendof InterframeSpace.AnynodedisablesHardSynchronizationifitsamplesanedgefromrecessiveto dominantorifitstartstosendthedominantSOFbit. Twotypesofsynchronizationaresupported: Hardsynchronizationisdonewithafallingedgeonthebuswhilethebusisidle,whichis interpretedasaStartofframe(SOF).ItrestartstheinternalBitTimeLogic. SoftsynchronizationisusedtolengthenorshortenabittimewhileaCANframeisreceived.

4 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

17.Whatisthedierencebetweenfunctionandphysicaladdressing? Answer:Functionaladdressingisanaddressingschemethatlabelsmessagesbasedupontheir operationcodeorcontent.Physicaladdressingisanaddressingschemethatlabelsmessagesbased uponthephysicaladdresslocationoftheirsourceand/ordestination(s). 18.WhathappensifIhavetosendmorethan8bytesofdata? Answer:TheJ1939standardhasdenedamethodofcommunicatingmorethan8bytesofdataby sendingthedatainpacketsasspeciedintheTransportProtocol(TP).TherearetwotypesofTP,one forbroadcastingthedata,andtheotherforsendingittoaspecicaddress. DTCconsistsof4componentsSPN,FMI,OCandCM. ADTCisacombinationoffourindependentelds:theSuspectParameterNumber(SPN)ofthe channelorfeaturethatcanhavefaults;aFailureModeIdentier(FMI)ofthespecicfault;the occurrencecount(OC)oftheSPN/FMIcombination;andtheSPNconversionmethod(CM)which tellsthereceivingmodehowtointerprettheSPN.Together,theSPN,FMI,OCandCMforma numberthatadiagnostictoolcanusetounderstandthefailurethatisbeingreported.

(http://automotivetechis.les.wordpress.com/2012/06 /clip_image002.jpg) Figure1Messageformat 19.WhatisKWP2000? Answer:KWP2000(ISO14230)isaDiagnosticcommunicationsstandard.Speciespossiblesystem congurationsusingtheK&Llines.As91412butlimitedtothephysicalcharacteristics.Species possiblesystemcongurationsusingtheK&Llines. 5Baudwakeupas91412 Newfastinitialisationmethod 20.WhatisOBDII? Answer:OnBoardDiagnosticsinanautomotivecontextisagenerictermreferringtoavehicles selfdiagnosticandreportingcapability 21.WhyDiagnosticStandards? Answer:Assystemsgotmorecomplexthelinkbetweencauseandsymptombecamelessobvious.
5 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

Thismeantthatelectronicsystemshadtohavesomelevelofselfdiagnosisandtocommunicatetothe outsideworld.Initiallymanysystemsusedtheirownprotocolswhichmeantthatgarageshadto havealargenumberoftoolseventodiagnoseasinglevehicle. 22.Whatismeantbyvericationandvalidation?? Answer:VericationandValidation(V&V)istheprocessofcheckingthatasoftwaresystemmeets specicationsandthatitfulllsitsintendedpurpose.Itisnormallypartofthesoftwaretesting processofaproject. AccordingtotheCapabilityMaturityModel(CMMISWv1.1), Verication:Theprocessofevaluatingsoftwaretodeterminewhethertheproductsofagiven developmentphasesatisfytheconditionsimposedatthestartofthatphase. Validation:Theprocessofevaluatingsoftwareduringorattheendofthedevelopmentprocessto determinewhetheritsatisesspeciedrequirements. Vericationshowsconformancewithspecication;validationshowsthattheprogrammeetsthe customersneeds 23.Canyouhavetwotransmittersusingthesameexactheadereld? Answer:Nothatwouldproduceabusconict Unlessyouhavemiddlewarethatensuresonlyonenodecantransmitatatime Forexampleusealowprioritymessageasatokentoemulatetokenpassing 24.CANphysicallayervoltagelevels

(http://automotivetechis.les.wordpress.com/2012/06/can1.jpg) 25.CANbittiming: AccordingtotheCANspecication,thebittimeisdividedintofoursegments.TheSynchronization Segment,thePropagationTimeSegment,thePhaseBuerSegment1,andthePhaseBuerSegment

6 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

2.Eachsegmentconsistsofaspecic,programmablenumberoftimequanta(seeTable1).Thelength ofthetimequantum(tq),whichisthebasictimeunitofthebittime,isdenedbytheCAN controllerssystemclockfsysandtheBaudRatePrescaler(BRP):tq=BRP/fsys.Typicalsystem clocksare:fsys=foscorfsys=fosc/2. TheSynchronizationSegmentSync_SegisthatpartofthebittimewhereedgesoftheCANbuslevel areexpectedtooccur;thedistancebetweenanedgethatoccursoutsideofSync_SegandtheSync_Seg iscalledthephaseerrorofthatedge.ThePropagationTimeSegmentProp_Segisintendedto compensateforthephysicaldelaytimeswithintheCANnetwork.ThePhaseBuerSegments Phase_Seg1andPhase_Seg2surroundtheSamplePoint.The(Re)SynchronizationJumpWidth(SJW) deneshowfararesynchronizationmaymovetheSamplePointinsidethelimitsdenedbythe PhaseBuerSegmentstocompensateforedgephaseerrors.

(http://automotivetechis.les.wordpress.com/2012/06/untitle436d.jpg) Twotypesofsynchronizationexist:HardSynchronizationandResynchronization.AHard Synchronizationisdoneonceatthestartofaframe;insideaframeonlyResynchronizationsoccur. HardSynchronizationAfterahardsynchronization,thebittimeisrestartedwiththeendof Sync_Seg,regardlessoftheedgephaseerror.Thushardsynchronizationforcestheedgewhichhas causedthehardsynchronizationtoliewithinthesynchronizationsegmentoftherestartedbittime. BitResynchronizationResynchronizationleadstoashorteningorlengtheningofthebittimesuch thatthepositionofthesamplepointisshiftedwithregardtotheedge. 26.FormulaforBaudratecalculation? Thebaudrateiscalculatedas:

baudrate(bitspersecond)=18.432x10^6/BRP/(1+TSEG1+TSEG2)

27.WhathappenwhentwoCANnodesaresendingsameidentieratasametime? Twonodesonthenetworkarenotallowedtosendmessageswiththesameid.Iftwonodestryto sendamessagewiththesameidatthesametimearbitrationwillnotwork.Instead,oneofthe transmittingnodeswilldetectthathismessageisdistortedoutsideofthearbitrationeld.Thenodes

7 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

willthenusetheerrorhandlingofCAN,whichinthiscaseultimatelywillleadtooneofthe transmittingnodebeingswitchedo(busomode). 28.whatisthedierencebetweenBitRateandBaudRate? ThedierencebetweenBitandBaudrateiscomplicatedandintertwining.Botharedependentand interrelated.ButthesimplestexplanationisthataBitRateishowmanydatabitsaretransmittedper second.AbaudRateisthenumberoftimespersecondasignalinacommunicationschannel changes.Bitratesmeasurethenumberofdatabits(thatis0sand1s)transmittedinonesecondina communicationchannel.Agureof2400bitspersecondmeans2400zerosoronescanbetransmitted inonesecond,hencetheabbreviationbps.Individualcharacters(forexamplelettersornumbers) thatarealsoreferredtoasbytesarecomposedofseveralbits.Abaudrateisthenumberoftimesa signalinacommunicationschannelchangesstateorvaries.Forexample,a2400baudratemeansthat thechannelcanchangestatesupto2400timespersecond.Thetermchangestatemeansthatitcan changefrom0to1orfrom1to0uptoX(inthiscase,2400)timespersecond.Italsoreferstothe actualstateoftheconnection,suchasvoltage,frequency,orphaselevel).Themaindierencebetween thetwoisthatonechangeofstatecantransmitonebit,or slightlymoreorlessthanonebit,thatdependsonthe modulationtechniqueused.Sothebitrate(bps)andbaud rate(baudpersecond)havethisconnection:bps=baudper secondxthenumberofbitperbaudThemodulation techniquedeterminesthenumberofbitperbaud.Hereare twoexamples:WhenFSK(FrequencyShiftKeying,a transmissiontechnique)isused,eachbaudtransmitsone bit.Onlyonechangeinstateisrequiredtosendabit.Thus, themodemsbpsrateisequaltothebaudrate.Whena baudrateof2400isused,amodulationtechniquecalled phasemodulationthattransmitsfourbitsperbaudisused. So:2400baudx4bitsperbaud=9600bpsSuchmodemsarecapableof9600bpsoperation. CInterviewQuestions: 1.Whatisthedierencebetweendeclarationanddenition? Answer:Denitionmeanswhereavariableorfunctionisdenedinrealityandactualmemoryis allocatedforvariableorfunction. Declarationmeansjustgivingareferenceofavariableandfunction. 2.WhatarethedierentstorageclassesinC? Answer:AUTO,STATIC,EXTERN,REGISTER autoisthedefaultstorageclassforlocalvariables. { intCount; autointMonth;

8 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

} registerisusedtodenelocalvariablesthatshouldbestoredinaregisterinsteadofRAMThis meansthatthevariablehasamaximumsizeequaltotheregistersize(usuallyoneword)andcannot havetheunary&operatorappliedtoit(asitdoesnothaveamemorylocation).

{ registerintMiles; }

Registershouldonlybeusedforvariablesthatrequirequickaccesssuchascounters.Itshouldalso benotedthatdeningregistergoesnotmeanthatthevariablewillbestoredinaregister.Itmeans thatitMIGHTbestoredinaregisterdependingonhardwareandimplementationrestrictions. staticStorageClass staticisthedefaultstorageclassforglobalvariables.Thetwovariablesbelow(countandroad)both haveastaticstorageclass. staticintCount;intRoad;main(){printf(%d\n,Count);printf(%d\n,Road);} staticcanalsobedenedwithinafunction.Ifthisisdone,thevariableisinitalizedatcompilation timeandretainsitsvaluebetweencalls.Becauseitisinitializedatcompilationtime,theinitialization valuemustbeaconstant.Thisisseriousstutreadwithcare. voidFunc(void){staticCount=1;} Hereisanexample Thereisoneveryimportantuseforstatic.Considerthisbitofcode. char*Func(void);main(){char*Text1;Text1=Func();}char*Func(void){charText2[10]=martin; return(Text2);} FuncreturnsapointertothememorylocationwhereText2startsBUTText2hasastorageclass ofautoandwilldisappearwhenweexitthefunctionandcouldbeoverwrittenbysomethingelse. Theansweristospecify: staticcharText[10]=martin; ThestorageassignedtoText2willremainreservedforthedurationiftheprogram. externstorageClass externdenesaglobalvariablethatisvisabletoALLobjectmodules.Whenyouuseexternthe variablecannotbeinitalizedasallitdoesispointthevariablenameatastoragelocationthathas beenpreviouslydened.

9 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

Source1Source2 externintcount;intcount=5; write()main() {{ printf(countis%d\n,count);write(); }} Countinsource1willhaveavalueof5.Ifsource1changesthevalueofcountsource2willseethe newvalue.Herearesomeexamplesourceles. 3.Whatisinterrupt? Answer:Interrupts(alsoknownastrapsorexceptionsinsomeprocessors)areatechniqueof divertingtheprocessorfromtheexecutionofthecurrentprogramsothatitmaydealwithsome eventthathasoccurred.Suchaneventmaybeanerrorfromaperipheral,orsimplythatanI/O devicehasnishedthelasttaskitwasgivenandisnowreadyforanother.Aninterruptisgenerated inyourcomputereverytimeyoutypeakeyormovethemouse.Youcanthinkofitasahardware generatedfunctioncall. 4.WhatisHardwareInterrupt? Answer:TherearetwowaysoftellingwhenanI/Odevice(suchasaserialcontrolleroradisk controller)isreadyforthenextsequenceofdatatobetransferred.Therstisbusywaitingorpolling, wheretheprocessorcontinuouslychecksthedevicesstatusregisteruntilthedeviceisready.This wastestheprocessorstimebutisthesimplesttoimplement.Forsometimecriticalapplications, pollingcanreducethetimeittakesfortheprocessortorespondtoachangeofstateinaperipheral. 5.WhatisSoftwareInterrupt? Answer:Asoftwareinterruptisgeneratedbyaninstruction.Itisthelowestpriorityinterruptandis generallyusedbyprogramstorequestaservicetobeperformedbythesystemsoftware(operating systemorrmware). DierencebetweenHardwareInterruptandSoftwareInterrupt Aninterruptisaspecialsignalthatcausesthecomputerscentralprocessingunittosuspendwhatit isdoingandtransfersitscontroltoaspecialprogramcalledaninterrupthandler.Theresponsibility ofaninterrupthandleristodeterminewhatcausedtheinterrupt,servicetheinterruptandthen returnthecontroltothepointfromwheretheinterruptwascaused.Thedierence betweenhardwareinterruptandsoftwareinterruptisasbelow: HardwareInterrupt:ThisinterruptiscausedbysomeexternaldevicesuchasrequesttostartanI/O

10 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

oroccurrenceofahardwarefailure. SoftwareInterrupt:ThisinterruptcanbeinvokedwiththehelpofINTinstruction.Aprogrammer triggeredthiseventthatimmediatelystopsexecutionoftheprogramandpassesexecutionovertothe INThandler.TheINThandlerisusuallyapartoftheoperatingsystemanddeterminestheactionto betakene.g.outputtothescreen,executeleetc. Thusasoftwareinterruptasitsnamesuggestsisdrivenbyasoftwareinstructionandahardware interruptistheresultofexternalcauses. 6.WhatisInterruptlatency?Howdoyoumeasureinterruptlatency?Howtoreducetheinterrupt latency? Answer:Interruptlatencyisthetimebetweeninterruptrequestandexecutionofrstinstructionof theISR. Weneedaoscilloscopeoralogicstateanalyzer.Byenteringtheinterruptserviceroutine(ISR),you needtoactivateanavailableportonyourhardware(likealedportorsoon)anddeactivateitjust beforereturningfromtheISR.Youcandothatbywritingtheappropriatecode. Byconnectingoneinputoftheoscilloscope(orlogicstateanalyzer)totheINTRpinofthe microprocessorandthesecondonetotheportyouactivate/deactivate,youcanmeasurethelatency timeandthedurationoftheISR Causesofinterruptlatencies Therstdelayistypicallyinthehardware:Theinterruptrequestsignalneedstobesynchronized totheCPUclock.Dependingonthesynchronizationlogic,typicallyupto3CPUcyclescanbelost beforetheinterruptrequesthasreachedtheCPUcore. TheCPUwilltypicallycompletethecurrentinstruction.Thisinstructioncantakealotofcycles; onmostsystems,divide,pushmultipleormemorycopyinstructionsaretheinstructionswhich requiremostclockcycles.OntopofthecyclesrequiredbytheCPU,thereareinmostcases additionalcyclesrequiredformemoryaccess.InanARM7system,theinstructionSTMDB SP!,{R0R11,LR};Pushparametersandperm.Registersistypicallytheworstcaseinstruction.It stores1332bitregistersonthestack.TheCPUrequires15clockcycles.Thememorysystemmay requireadditionalcyclesforwaitstates. Aftercompletionofthecurrentinstruction,theCPUperformsamodeswitchorpushesregisters (typicallyPCandagregisters)onthestack.Ingeneral,modernCPUs(suchasARM)performa modeswitch,whichrequireslessCPUcyclesthansavingregisters. Pipelinell:MostmodernCPUsarepipelined.Executionofaninstructionhappensinvarious stagesofthepipeline.Aninstructionisexecutedwhenithasreacheditsnalstageofthepipeline. Sincethemodeswitchhasushedthepipeline,afewextracyclesarerequiredtorellthe pipeline. 7.Vonneumanandharvardarchitecturedierences? Answer:ThenameHarvardArchitecturecomesfromtheHarvardMarkIrelaybasedcomputer.The mostobviouscharacteristicoftheHarvardArchitectureisthatithasphysicallyseparatesignalsand storageforcodeanddatamemory.Itispossibletoaccessprogrammemoryanddatamemory

11 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

simultaneously.Typically,code(orprogram)memoryisreadonlyanddatamemoryisreadwrite. Therefore,itisimpossibleforprogramcontentstobemodiedbytheprogramitself. ThevonneumannArchitectureisnamedafterthemathematicianandearlycomputerscientistJohn vonNeumann.vonNeumannmachineshavesharedsignalsandmemoryforcodeanddata.Thus, theprogramcanbeeasilymodiedbyitselfsinceitisstoredinreadwritememory. Harvardarchitecturehasseparatedataandinstructionbusses,allowingtransferstobeperformed simultaneouslyonbothbuses.VonNeumannarchitecturehasonlyonebuswhichisusedforboth datatransfersandinstructionfetches,andthereforedatatransfersandinstructionfetchesmustbe scheduledtheycannotbeperformedatthesametime. ItispossibletohavetwoseparatememorysystemsforaHarvardarchitecture.Aslongasdataand instructionscanbefedinatthesametime,thenitdoesntmatterwhetheritcomesfromacacheor memory.Butthereareproblemswiththis.Compilersgenerallyembeddata(literalpools)withinthe code,anditisoftenalsonecessarytobeabletowritetotheinstructionmemoryspace,forexamplein thecaseofselfmodifyingcode,or,ifanARMdebuggerisused,tosetsoftwarebreakpointsin memory.Iftherearetwocompletelyseparate,isolatedmemorysystems,thisisnotpossible.There mustbesomekindofbridgebetweenthememorysystemstoallowthis. Usingasimple,uniedmemorysystemtogetherwithaHarvardarchitectureishighlyinecient. Unlessitispossibletofeeddataintobothbusesatthesametime,itmightbebettertouseavon Neumannarchitectureprocessor. Useofcaches Athigherclockspeeds,cachesareusefulasthememoryspeedisproportionallyslower.Harvard architecturestendtobetargetedathigherperformancesystems,andsocachesarenearlyalways usedinsuchsystems. VonNeumannarchitecturesusuallyhaveasingleuniedcache,whichstoresbothinstructionsand data.Theproportionofeachinthecacheisvariable,whichmaybeagoodthing.Itwouldinprinciple bepossibletohaveseparateinstructionanddatacaches,storingdataandinstructionsseparately. Thisprobablywouldnotbeveryusefulasitwouldonlybepossibletoeveraccessonecacheata time. CachesforHarvardarchitecturesareveryuseful.Suchasystemwouldhaveseparatecachesforeach bus.TryingtouseasharedcacheonaHarvardarchitecturewouldbeveryinecientsincethenonly onebuscanbefedatatime.Havingtwocachesmeansitispossibletofeedbothbuses simultaneously.exactlywhatisnecessaryforaHarvardarchitecture. Thisalsoallowstohaveaverysimpleuniedmemorysystem,usingthesameaddressspaceforboth instructionsanddata.Thisgetsaroundtheproblemofliteralpoolsandselfmodifyingcode.Whatit doesmean,however,isthatwhenstartingwithemptycaches,itisnecessarytofetchinstructionsand datafromthesinglememorysystem,atthesametime.Obviously,twomemoryaccessesareneeded thereforebeforethecorehasallthedataneeded.Thisperformancewillbenobetterthanavon Neumannarchitecture.However,asthecachesllup,itismuchmorelikelythattheinstructionor datavaluehasalreadybeencached,andsoonlyoneofthetwohastobefetchedfrommemory.The othercanbesupplieddirectlyfromthecachewithnoadditionaldelay.Thebestperformanceis

12 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

achievedwhenbothinstructionsanddataaresuppliedbythecaches,withnoneedtoaccessexternal memoryatall. ThisisthemostsensiblecompromiseandthearchitectureusedbyARMsHarvardprocessorcores. Twoseparatememorysystemscanperformbetter,butwouldbediculttoimplement 8.RISCandCISCdierences? Answer: CISC:(ComplexInstructionSetComputer) Eg:IntelandAMDCPUs CISCchipshavealargeamountofdierentandcomplexinstructions. CISCchipsarerelativelyslow(comparedtoRISCchips)perinstruction,butuselittle(lessthan RISC)instructions. CISCarchitectureistocompleteataskinasfewlinesofassemblyaspossible.Thisisachievedby buildingprocessorhardwarethatiscapableofunderstandingandexecutingaseriesof operations. InCISC,compilerhastodoverylittleworktotranslateahighlevellanguagestatementinto assembly.Becausethelengthofthecodeisrelativelyshort,verylittleRAMisrequiredtostore instructions.Theemphasisisputonbuildingcomplexinstructionsdirectlyintothehardware. Whenexecuted,thisinstructionloadsthetwovaluesintoseparateregisters,multipliesthe operandsintheexecutionunit,andthenstorestheproductintheappropriateregister. RISC:(ReducedInstructionSetComputer) Eg:Apple,ARMprocessors Fewer,simplerandfasterinstructionswouldbebetter,thanthelarge,complexandslowerCISC instructions.However,moreinstructionsareneededtoaccomplishatask. RISCchipsrequirefewertransistors,whichmakesthemeasiertodesignandcheapertoproduce. itseasiertowritepowerfuloptimizedcompilers,sincefewerinstructionsexist. RISCischeaperandfaster. RISCputsagreaterburdenonthesoftware.Softwareneedstobecomemorecomplex.Software developersneedtowritemorelinesforthesametasks.ThereforetheyarguethatRISCisnotthe architectureofthefuture,sinceconventionalCISCchipsarebecomingfasterandcheaper Simpleinstructionsthatcanbeexecutedwithinoneclockcycle. MULTcommanddescribedabovecouldbedividedintothreeseparatecommands:LOAD, whichmovesdatafromthememorybanktoaregister,PROD,whichndstheproductoftwo operandslocatedwithintheregisters,andSTORE,whichmovesdatafromaregistertothe memorybanks. Atrst,thismayseemlikeamuchlessecientwayofcompletingtheoperation.Becausethere aremorelinesofcode,moreRAMisneededtostoretheassemblylevelinstructions.Thecompiler mustalsoperformmoreworktoconvertahighlevellanguagestatementintocodeofthisform. SeparatingtheLOADandSTOREinstructionsactuallyreducestheamountofworkthatthe computermustperform. MajorproblemofRISCtheydontaordthewidespreadcompatibility,thatx86chipsdo.

13 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

CISC Emphasisonhardware Includesmulticlock complexinstructions Memorytomemory: LOADandSTORE incorporatedininstructions Smallcodesizes, highcyclespersecond Transistorsusedforstoring complexinstructions CISC Complexinstructionsrequiremultiplecycles Manyinstructionscanreferencememory RISC

RISC Emphasisonsoftware Singleclock, reducedinstructiononly Registertoregister: LOADandSTORE areindependentinstructions Lowcyclespersecond, largecodesizes Spendsmoretransistors onmemoryregisters

Reducedinstructionstake1 cycle OnlyLoadandStore instructionscanreference memory Usespipeliningtoexecute instructions Manygeneralregisters

Instructionsareexecutedoneatatime Fewgeneralregisters 9.Whatarethestartupcodesteps? Answer: 1. 2. 3. 4. 5. 6. Disablealltheinterrupts. CopyandinitializeddatafromROMtoRAM. Zerotheuninitializeddataarea. Allocatespaceandforinitializethestack. Initializetheprocessorstackpointer Callmain

10.WhatarethebootingstepsforaCPU? Answer: ThepowersupplydoesaselfcheckandsendsapowergoodsignaltotheCPU. TheCPUstartsexecutingthecodestoredinROMonthemotherboardstartstheaddress0xFFFF0. TheroutinesinROMtestthecentralhardware,searchforvideoROM,performachecksumonthe videoROMandexecutestheroutinesinvideoROM. TheroutinesinthemotherboardROMthencontinuesearchingforanyROM,checksumand

14 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

executestheseroutines. AfterperformingthePOST(PowerOnSelfTest)isexecuted.Thesystemwillsearchforaboot device. Assumingthatthevalidbootdeviceisfound,IO.SYSisloadedintomemoryandexecuted.IO.SYS consistsprimarilyofinitializationcodeandextensiontothememoryboardROMBIOS. MSDOS.SYSisloadedintomemoryandexecuted.MSDOS.SYScontainstheDOSroutines. CONFIG.SYS(createdandmodiedbytheuser.loadadditionaldevicedriversforperipheral devices),COMMAND.COM(ItiscommandinterpreterIttranslatesthecommandsenteredby theuser.ItalsocontainsinternalDOScommands.ItexecutesandAUTOEXEC.BAT), AUTOEXEC.BAT(Itcontainsallthecommandsthattheuserwantswhichareexecuted automaticallyeverytimethecomputedisstarted). 11.WhatLittleEndianandBigEndian?HowcanIdeterminewhetheramachinesbyteorderis bigendianorlittleendian?Howcanweconvertfromonetoanother? Firstofall,DoyouknowwhatLittleEndianandBigEndianmean? LittleEndianmeansthatthelowerorderbyteofthenumberisstoredinmemoryatthelowest address,andthehigherorderbyteisstoredatthehighestaddress.Thatis,thelittleendcomesrst. Forexample,a4byte,32bitintegerByte3Byte2Byte1Byte0willbearrangedinmemoryas follows:Base_Address+0Byte0 Base_Address+1Byte1 Base_Address+2Byte2 Base_Address+3Byte3IntelprocessorsuseLittleEndianbyteorder.BigEndianmeansthatthe higherorderbyteofthenumberisstoredinmemoryatthelowestaddress,andthelowerorderbyte atthehighestaddress.Thebigendcomesrst.Base_Address+0Byte3 Base_Address+1Byte2 Base_Address+2Byte1 Base_Address+3Byte0Motorola,SolarisprocessorsuseBigEndianbyteorder.InLittleEndian form,codewhichpicksupa1,2,4,orlongerbytenumberproceedinthesamewayforallformats. Theyrstpickupthelowestorderbyteatoset0andproceedfromthere.Also,becauseofthe1:1 relationshipbetweenaddressosetandbytenumber(oset0isbyte0),multipleprecision mathematicroutinesareeasytocode.InBigEndianform,sincethehighorderbytecomesrst,the codecantestwhetherthenumberispositiveornegativebylookingatthebyteatosetzero.Itsnot requiredtoknowhowlongthenumberis,nordoesthecodehavetoskipoveranybytestondthe bytecontainingthesigninformation.Thenumbersarealsostoredintheorderinwhichtheyare printedout,sobinarytodecimalroutinesareparticularlyecient.Hereissomecodetodetermine whatisthetypeofyourmachine. intnum=1; if(*(char*)&num==1) { printf(\nLittleEndian\n); } else { printf(BigEndian\n); }AndhereissomecodetoconvertfromoneEndiantoanother.intmyreversefunc(intnum) { intbyte0,byte1,byte2,byte3;byte0=(num&x000000FF)>>0;
15 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

byte1=(num&x0000FF00)>>8; byte2=(num&x00FF0000)>>16; byte3=(num&xFF000000)>>24;return((byte0<<24)|(byte1<<16)|(byte2<<8)|(byte3<<0)); } 12.Programtondifamachineisbigendianorlittleendian? 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 #include"stdio.h" #defineBIG_ENDIAN0 #defineLITTLE_ENDIAN1 intmain() { intvalue; value=endian(); if(value==1) printf("Machineislittleendian\n",value); else printf("MachineisBigEndian\n",value); } intendian(){ shortintword=0x0001; char*byte=(char*)&word; return(byte[0]?LITTLE_ENDIAN:BIG_ENDIAN); }

13.Swap2variableswithoutusingtemporaryvariable! a=a+b b=ab a=ab 14.WriteaprogramtogeneratetheFibonacciSeries? #include<stdio.h> #include<conio.h> main() { intn,i,c,a=0,b=1; printf(EnterFibonacciseriesofnthterm:); scanf(%d,&n); printf(%d%d,a,b); for(i=0;i<=(n3);i++) {

16 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

c=a+b; a=b; b=c; printf(%d,c); } getch(); }Output: EnterFibonacciseriesofnthterm:7 0112358 15.Writeaprogramtonduniquenumbersinanarray? Answer: for(i=1;i<=array.length;i++){ found=false; for(k=i+1;k<=array.length;k++){ if(array[i]==array[k])found=true; } if(!found)println(array[i]); } 16.WriteaCprogramtoprintEquilateralTriangleusingnumbers? 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 /*CprogramtoprintEquilateralTriangle*/ #include<stdio.h> main() { inti,j,k,n; printf("Enternumberofrowsofthetriangle\n"); scanf("%d",&n); for(i=1;i<=n;i++) { for(j=1;j<=ni;j++) { printf(""); } for(k=1;k<=(2*i)1;k++)

17 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

17 18 19 20 21 22

{ printf("i"); } printf("\n"); } getch();

17.Writeaprogramfordeletionandinsertionofanodeinsinglelinkedlist? #include<stdio.h> #include<stdlib.h> typedefstructNode { intdata; structNode*next; }node; voidinsert(node*pointer,intdata) { /*Iteratethroughthelisttillweencounterthelastnode.*/ while(pointer>next!=NULL) { pointer=pointer>next; } /*Allocatememoryforthenewnodeandputdatainit.*/ pointer>next=(node*)malloc(sizeof(node)); pointer=pointer>next; pointer>data=data; pointer>next=NULL; } intnd(node*pointer,intkey) { pointer=pointer>next;//Firstnodeisdummynode. /*Iteratethroughtheentirelinkedlistandsearchforthekey.*/ while(pointer!=NULL) { if(pointer>data==key)//keyisfound. { return1; } pointer=pointer>next;//Searchinthenextnode. } /*Keyisnotfound*/ return0; }

18 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

voiddelete(node*pointer,intdata) { /*Gotothenodeforwhichthenodenexttoithastobedeleted*/ while(pointer>next!=NULL&&(pointer>next)>data!=data) { pointer=pointer>next; } if(pointer>next==NULL) { printf(Element%disnotpresentinthelist\n,data); return; } /*Nowpointerpointstoanodeandthenodenexttoithastoberemoved*/ node*temp; temp=pointer>next; /*temppointstothenodewhichhastoberemoved*/ pointer>next=temp>next; /*Weremovedthenodewhichisnexttothepointer(whichisalsotemp)*/ free(temp); /*Beacusewedeletedthenode,wenolongerrequirethememoryusedforit. free()willdeallocatethememory. */ return; } voidprint(node*pointer) { if(pointer==NULL) { return; } printf(%d,pointer>data); print(pointer>next); } intmain() { /*startalwayspointstotherstnodeofthelinkedlist. tempisusedtopointtothelastnodeofthelinkedlist.*/ node*start,*temp; start=(node*)malloc(sizeof(node)); temp=start; temp>next=NULL; /*Hereinthiscode,wetaketherstnodeasadummynode. Therstnodedoesnotcontaindata,butitusedbecausetoavoidhandlingspecialcases ininsertanddeletefunctions. */ printf(1.Insert\n); printf(2.Delete\n); printf(3.Print\n);
19 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

printf(4.Find\n); while(1) { intquery; scanf(%d,&query); if(query==1) { intdata; scanf(%d,&data); insert(start,data); } elseif(query==2) { intdata; scanf(%d,&data); delete(start,data); } elseif(query==3) { printf(Thelistis); print(start>next); printf(\n); } elseif(query==4) { intdata; scanf(%d,&data); intstatus=nd(start,data); if(status) { printf(ElementFound\n); } else { printf(ElementNotFound\n);} } }} 18.Canavariablebebothconstandvolatile?Yes.Theconstmodiermeansthatthiscodecannot changethevalueofthevariable,butthatdoesnotmeanthatthevaluecannotbechangedbymeans outsidethiscode.Forinstance,intheexampleinFAQ8,thetimerstructurewasaccessedthrougha volatileconstpointer.Thefunctionitselfdidnotchangethevalueofthetimer,soitwasdeclared const.However,thevaluewaschangedbyhardwareonthecomputer,soitwasdeclaredvolatile.Ifa variableisbothconstandvolatile,thetwomodierscanappearineitherorder. 19.whatareConstantandVolatileQualiers?

20 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

constisusedwithadatatypedeclarationordenitiontospecifyanunchangingvalue Examples: constintfive=5; constdoublepi=3.141593;

constobjectsmaynotbechanged Thefollowingareillegal: constintfive=5; constdoublepi=3.141593; pi=3.2; five=6;

volatilespeciesavariablewhosevaluemaybechangedbyprocessesoutsidethecurrent program Oneexampleofavolatileobjectmightbeabuerusedtoexchangedatawithanexternal device: int check_iobuf(void) { volatileintiobuf; intval; while(iobuf==0){ } val=iobuf; iobuf=0;

21 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

return(val); }

ifiobufhadnotbeendeclaredvolatile,thecompilerwouldnoticethatnothinghappensinside theloopandthuseliminatetheloop constandvolatilecanbeusedtogether Aninputonlybuerforanexternaldevicecouldbedeclaredasconst volatile(orvolatileconst,orderisnotimportant)tomakesurethecompilerknowsthat thevariableshouldnotbechanged(becauseitisinputonly)andthatitsvaluemaybealtered byprocessesotherthanthecurrentprogram Thekeywordsconstandvolatilecanbeappliedtoanydeclaration,includingthoseofstructures, unions,enumeratedtypesortypedefnames.Applyingthemtoadeclarationiscalledqualifyingthe declarationthatswhyconstandvolatilearecalledtypequaliers,ratherthantypespeciers.Here areafewrepresentativeexamples:

volatilei; volatileintj; constlongq; constvolatileunsignedlongintrt_clk; struct{ constlongintli; signedcharsc; }volatilevs;

Dontbeputo;someofthemaredeliberatelycomplicated:whattheymeanwillbeexplainedlater. Rememberthattheycouldalsobefurthercomplicatedbyintroducingstorageclassspecicationsas well!Infact,thetrulyspectacular

externconstvolatileunsignedlongintrt_clk;

isastrongpossibilityinsomerealtimeoperatingsystemkernels.

Letslookatwhatismeantwhenconstisused.Itsreallyquitesimple:constmeansthatsomething
22 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

isnotmodiable,soadataobjectthatisdeclaredwithconst asapartofitstypespecicationmust notbeassignedtoinanywayduringtherunofaprogram.Itisverylikelythatthedenitionofthe objectwillcontainaninitializer(otherwise,sinceyoucantassigntoit,howwoulditevergeta value?),butthisisnotalwaysthecase.Forexample,ifyouwereaccessingahardwareportataxed memoryaddressandpromisedonlytoreadfromit,thenitwouldbedeclaredtobeconstbutnot initialized. Takingtheaddressofadataobjectofatypewhichisntconstandputtingitintoapointerto theconstqualiedversionofthesametypeisbothsafeandexplicitlypermitted;youwillbeableto usethepointertoinspecttheobject,butnotmodifyit.Puttingtheaddressofaconsttypeintoa pointertotheunqualiedtypeismuchmoredangerousandconsequentlyprohibited(althoughyou cangetaroundthisbyusingacast).Hereisanexample:

#include<stdio.h> #include<stdlib.h> main(){ inti; constintci=123; /*declareapointertoaconst..*/ constint*cpi; /*ordinarypointertoanonconst*/ int*ncpi; cpi=&ci; ncpi=&i; /* *thisisallowed */ cpi=ncpi; /* *thisneedsacast *becauseitisusuallyabigmistake, *seewhatitpermitsbelow. */ ncpi=(int*)cpi; /* *nowtogetundefinedbehaviour... *modifyaconstthroughapointer */

23 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

*ncpi=0; exit(EXIT_SUCCESS); }

Example8.3 Astheexampleshows,itispossibletotaketheaddressofaconstantobject,generateapointertoa nonconstant,thenusethenewpointer.Thisisanerrorinyourprogramandresultsinundened behaviour. Themainintentionofintroducingconstobjectswastoallowthemtobeputintoreadonlystore,and topermitcompilerstodoextraconsistencycheckinginaprogram.Unlessyoudefeattheintentby doingnaughtythingswithpointers,acompilerisabletocheckthatconstobjectsarenotmodied explicitlybytheuser. Aninterestingextrafeaturepopsupnow.Whatdoesthismean?

charc; char*constcp=&c;

Itssimplereally;cpisapointertoachar,whichisexactlywhatitwouldbeiftheconstwerent there.Theconstmeansthatcpisnottobemodied,althoughwhateveritpointstocanbethe pointerisconstant,notthethingthatitpointsto.Theotherwayroundis

constchar*cp;

whichmeansthatnowcpisanordinary,modiablepointer,butthethingthatitpointstomustnot bemodied.So,dependingonwhatyouchoosetodo,boththepointerandthethingitpointstomay bemodiableornot;justchoosetheappropriatedeclaration.

Afterconst,wetreatvolatile.Thereasonforhavingthistypequalierismainlytodowiththe problemsthatareencounteredinrealtimeorembeddedsystemsprogrammingusingC.Imagine thatyouarewritingcodethatcontrolsahardwaredevicebyplacingappropriatevaluesinhardware registersatknownabsoluteaddresses.

24 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

Letsimaginethatthedevicehastworegisters,each16bitslong,atascendingmemoryaddresses;the rstoneisthecontrolandstatusregister(csr)andthesecondisadataport.Thetraditionalwayof accessingsuchadeviceislikethis:

/*StandardCexamplebutwithoutconstorvolatile*/ /* *Declarethedeviceregisters *Whethertouseintorshort *isimplementationdependent */ structdevregs{ unsignedshortcsr;/*control&status*/ unsignedshortdata;/*dataport*/ }; /*bitpatternsinthecsr*/ #defineERROR0x1 #defineREADY0x2 #defineRESET0x4 /*absoluteaddressofthedevice*/ #defineDEVADDR((structdevregs*)0xffff0004) /*numberofsuchdevicesinsystem*/ #defineNDEVS4 /* *Busywaitfunctiontoreadabytefromdevicen. *checkrangeofdevicenumber. *WaituntilREADYorERROR *ifnoerror,readbyte,returnit *otherwisereseterror,return0xffff */ unsignedintread_dev(unsigneddevno){ structdevregs*dvp=DEVADDR+devno; if(devno>=NDEVS) return(0xffff); while((dvp>csr&(READY|ERROR))==0) ;/*NULLwaittilldone*/ if(dvp>csr&ERROR){

25 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

dvp>csr=RESET; return(0xffff); } return((dvp>data)&0xff); }

Example8.4 Thetechniqueofusingastructuredeclarationtodescribethedeviceregisterlayoutandnamesis verycommonpractice.Noticethattherearentactuallyanyobjectsofthattypedened,sothe declarationsimplyindicatesthestructurewithoutusingupanystore. Toaccessthedeviceregisters,anappropriatelycastconstantisusedasifitwerepointingtosucha structure,butofcourseitpointstomemoryaddressesinstead. However,amajorproblemwithpreviousCcompilerswouldbeinthewhileloopwhichteststhe statusregisterandwaitsfortheERRORorREADYbittocomeon.Anyselfrespectingoptimizing compilerwouldnoticethattheloopteststhesamememoryaddressoverandoveragain.Itwould almostcertainlyarrangetoreferencememoryonceonly,andcopythevalueintoahardwareregister, thusspeedinguptheloop.Thisis,ofcourse,exactlywhatwedontwant;thisisoneofthefewplaces wherewemustlookattheplacewherethepointerpoints,everytimearoundtheloop. Becauseofthisproblem,mostCcompilershavebeenunabletomakethatsortofoptimizationinthe past.Toremovetheproblem(andothersimilaronestodowithwhentowritetowhereapointer points),thekeywordvolatilewasintroduced.Ittellsthecompilerthattheobjectissubjectto suddenchangeforreasonswhichcannotbepredictedfromastudyoftheprogramitself,andforces everyreferencetosuchanobjecttobeagenuinereference. Hereishowyouwouldrewritetheexample,makinguseofconstandvolatiletogetwhatyou want.

/* *Declarethedeviceregisters *Whethertouseintorshort *isimplementationdependent */ structdevregs{ unsignedshortvolatilecsr; unsignedshortconstvolatiledata; }; /*bitpatternsinthecsr*/

26 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

#defineERROR0x1 #defineREADY0x2 #defineRESET0x4 /*absoluteaddressofthedevice*/ #defineDEVADDR((structdevregs*)0xffff0004) /*numberofsuchdevicesinsystem*/ #defineNDEVS4 /* *Busywaitfunctiontoreadabytefromdevicen. *checkrangeofdevicenumber. *WaituntilREADYorERROR *ifnoerror,readbyte,returnit *otherwisereseterror,return0xffff */ unsignedintread_dev(unsigneddevno){ structdevregs*constdvp=DEVADDR+devno; if(devno>=NDEVS) return(0xffff); while((dvp>csr&(READY|ERROR))==0) ;/*NULLwaittilldone*/ if(dvp>csr&ERROR){ dvp>csr=RESET; return(0xffff); } return((dvp>data)&0xff); }

Example8.5 Therulesaboutmixingvolatileandregulartypesresemblethoseforconst.Apointerto avolatileobjectcanbeassignedtheaddressofaregularobjectwithsafety,butitisdangerous(and needsacast)totaketheaddressofavolatileobjectandputitintoapointertoaregularobject. Usingsuchaderivedpointerresultsinundenedbehaviour. Ifanarray,unionorstructureisdeclaredwithconstorvolatileattributes,thenallofthemembers takeonthatattributetoo.Thismakessensewhenyouthinkaboutithowcouldamemberof aconststructurebemodiable?

27 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

Thatmeansthatanalternativerewriteofthelastexamplewouldbepossible.Insteadofdeclaringthe deviceregisterstobevolatileinthestructure,thepointercouldhavebeendeclaredtopointto avolatilestructureinstead,likethis:

structdevregs{ unsignedshortcsr;/*control&status*/ unsignedshortdata;/*dataport*/ }; volatilestructdevregs*constdvp=DEVADDR+devno;

Sincedvppointstoavolatileobject,itnotpermittedtooptimizereferencesthroughthepointer. Ourfeelingisthat,althoughthiswouldwork,itisbadstyle.Thevolatiledeclarationbelongsinthe structure:itisthedeviceregisterswhicharevolatileandthatiswheretheinformationshouldbe kept;itreinforcesthefactforahumanreader. So,foranyobjectlikelytobesubjecttomodicationeitherbyhardwareorasynchronousinterrupt serviceroutines,thevolatiletypequalierisimportant. Now,justwhenyouthoughtthatyouunderstoodallthat,herecomesthenaltwist.Adeclaration likethis:

volatilestructdevregs{ /*stuff*/ }v_decl;

declaresthetypestructdevregsandalsoavolatilequaliedobjectofthattype,calledv_decl. Alaterdeclarationlikethis

structdevregsnv_decl;

declaresnv_declwhichisnotqualiedwithvolatile!Thequalicationisnotpartofthetype ofstructdevregsbutappliesonlytothedeclarationofv_decl.Lookatitthiswayround,which perhapsmakesthesituationmoreclear(thetwodeclarationsarethesameintheireect):

structdevregs{ /*stuff*/ }volatilev_decl;

28 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

Ifyoudowanttogetashorthandwayofattachingaqualiertoanothertype,youcan usetypedeftodoit:

structx{ inta; }; typedefconststructxcsx; csxconst_sx; structxnon_const_sx={1}; const_sx=non_const_sx;/*errorattempttomodifyaconst*/

20.WhatarethedierencesbetweenaunionandastructureinC? Aunionisawayofprovidinganalternatewayofdescribingthesamememoryarea.Inthisway,you couldhaveastructthatcontainsaunion,sothatthestatic,orsimilarportionofthedatais describedrst,andtheportionthatchangesisdescribedbytheunion.Theideaofaunioncouldbe handledinadierentwaybyhaving2dierentstructsdened,andmakingapointertoeachkindof struct.Thepointertostructacouldbeassignedtothevalueofabuer,andthepointertostruct bcouldbeassignedtothesamebuer,butnowa>someeldandb>someothereldareboth locatedinthesamebuer.Thatistheideabehindaunion.Itgivesdierentwaystobreakdownthe samebuerarea. Thedierencebetweenstructureandunionare:1.unionallocatesthememoryequaltothe maximummemoryrequiredbythememberoftheunionbutstructureallocatesthememoryequalto thetotalmemoryrequiredbythemembers.2.Inunion,oneblockisusedbyallthememberofthe unionbutincaseofstructure,eachmemberhavetheirownmemoryspace DierenceBetweenStuctureandUnion: Structure i.AccessMembers Wecanaccessallthemembersofstructureat anytime. ii.MemoryAllocation Memoryisallocatedforallvariables. iii.Initialization Allmembersofstructurecanbeinitialized iv.Keyword Onlytherstmemberofaunioncanbe initialized. Allocatesmemoryforvariablewhichvariable requiremorememory. Onlyonememberofunioncanbeaccessedat anytime. Union

29 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

structkeywordisusedtodeclarestructure. v.Syntax structstruct_name { structureelement1; structureelement2; structureelementn; }struct_var_nm;

unionkeywordisusedtodeclareunion.

unionunion_name { unionelement1; unionelement2; unionelementn; }union_var_nm;

vi.Example structitem_mst { intrno; charnm[50]; }it; unionitem_mst { intrno; charnm[50]; }it;

Whilestructureenablesustreatanumberofdierentvariablesstoredatdierentinmemory,a unionenablesustotreatthesamespaceinmemoryasanumberofdierentvariables.Thatisa Unionoersawayforasectionofmemorytobetreatedasavariableofonetypeononeoccasion andasadierentvariableofadierenttypeonanotheroccasion. Thereisfrequentrequirementwhileinteractingwithhardwaretoaccessaccessabyteorgroupof bytessimultaneouslyandsometimeseachbyteindividually.Usuallyunionistheanswer. =======DierenceWithexample======= Letssayastructurecontaininganint,charandoatiscreatedandaunioncontainingintcharoat aredeclared. structTT{inta;oatb;charc;}UnionUU{inta;oatb;charc;} sizeofTT(struct)wouldbe>9bytes(compilerdependentifint,oat,chararetakenas4,4,1) sizeofUU(Union)wouldbe4bytesassupposedfromabove.Ifavariableindoubleexistsinunion thenthesizeofunionandstructwouldbe8bytesandcumulativesizeofallvariablesinstruct.

30 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

structfoo { charc; longl; char*p; }; unionbar { charc; longl; char*p; }; Astructfoocontainsalloftheelementsc,l,andp.Eachelementisseparateanddistinct. Aunionbarcontainsonlyoneoftheelementsc,l,andpatanygiventime.Eachelementisstoredin thesamememorylocation(well,theyall startatthesamememorylocation),andyoucanonlyrefertotheelementwhichwaslaststored.(ie: afterbarptr>c=2;youcannotreference anyoftheotherelements,suchasbarptr>pwithoutinvokingundenedbehavior.) Trythefollowingprogram.(Yes,Iknowitinvokestheabovementionedundenedbehavior,but mostlikelywillgivesomesortofoutputonmostcomputers.) ========== #include structfoo { charc; longl; char*p; }; unionbar { charc; longl; char*p; }; intmain(intargc,char*argv[])

31 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

{ structfoomyfoo; unionbarmybar; myfoo.c=1; myfoo.l=2L; myfoo.p=Thisismyfoo; mybar.c=1; mybar.l=2L; mybar.p=Thisismybar; printf(myfoo:%d%ld%s\n,myfoo.c,myfoo.l,myfoo.p); printf(mybar:%d%ld%s\n,mybar.c,mybar.l,mybar.p); return0; } ========== Onmysystem,Iget: myfoo:12Thisismyfoo mybar:1004197476Thisismybar ========== credittooriginalauthor. Structure:Structureisacombinationelements,whichcanbepredeneddatatypesorotherstructure. Thelength/sizeofthestructureisthesumofthelengthofitselements. InC,structurescannotcontainfunctions.inC++itcan. Union:Unionisacombinationelements,whichcanbepredeneddatatypesorotherunion.But,the size/lengthofunionisthemaximumofinternalelements. thesizeof()operatorreturnsthesizeslightlymorethancalculatedsizeduetopadding,whichagain dependsonOS ==Answer==Unionallocatesthememoryequaltothemaximummemoryrequiredbythemember oftheunionbutstructureallocatesthememoryequaltothetotalmemoryrequiredbythemembers. Inunion,oneblockisusedbyallthememberoftheunionbutincaseofstructure,eachmemberhave theirownmemoryspace. 21.Whatismeantbystructurepadding? Answer:compilerspadstructurestooptimizedatatransfers.Thisisanhardwarearchitectureissue. MostmodernCPUsperformbestwhenfundamentaltypes,likeintoroat,arealignedonmemory boundariesofaparticularsize(eg.oftena4bytewordon32bitarchs).Manyarchitecturesdontallow misalignedaccessoriftheydoinoccuraperformancepenality.Whenacompilerprocessesa structuredeclarationitwilladdextrabytesbetweeneldstomeetalignmentneeds. Mostprocessorsrequirespecicmemoryalignmentonvariablescertaintypes.Normallythe

32 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

minimumalignmentisthesizeofthebasictypeinquestion,forinstancethisiscommon charvariablescanbebytealignedandappearatanybyteboundary short(2byte)variablesmustbe2bytealigned,theycanappearatanyevenbyteboundary.This meansthat010004567isnotavalidlocationforashortvariablebut010004566is. long(4byte)variablesmustbe4bytealigned,theycanonlyappearatbyteboundariesthatarea multipleof4bytes.Thismeansthat010004566isnotavalidlocationforalongvariablebut 010004568is. Structurepaddingoccursbecausethemembersofthestructuremustappearatthecorrectbyte boundary,toachievethisthecompilerputsinpaddingbytes(orbitsifbiteldsareinuse)sothatthe structuremembersappearinthecorrectlocation.Additionallythesizeofthestructuremustbesuch thatinanarrayofthestructuresallthestructuresarecorrectlyalignedinmemorysotheremaybe paddingbytesattheendofthestructuretoo structexample{ charc1; shorts1; charc2; longl1; charc3; } Inthisstructure,assumingthealignmentschemeIhavepreviouslystatedthen c1canappearatanybyteboundary,howevers1mustappearata2byteboundarysothereisa paddingbytebetweenc1ands1. c2canthenappearintheavailablememorylocation,howeverl1mustbeata4byteboundaryso thereare3paddingbytesbetweenc2andl1 c3thenappearintheavailablememorylocation,howeverbecausethestructurecontainsalong memberthestructuremustbe4bytealignedandmustbeamultipleof4bytesinsize.Therefore thereare3paddingbytesattheendofthestructure.Itwouldappearinmemoryinthisorder c1 paddingbyte s1byte1 s1byte2 c2 paddingbyte paddingbyte paddingbyte l1byte1 l1byte2 l1byte3 l1byte4 c3
33 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

paddingbyte paddingbyte paddingbyte Thestructurewouldbe16byteslong. rewrittenlikethis structexample{ longl1; shorts1; charc1; charc2; charc3; } Thenl1appearsatthecorrectbytealignment,s1willbecorrectlyalignedsononeedforpadding betweenl1ands1.c1,c2,c3canappearatanylocation.Thestructuremustbeamultipleof4bytesin sizesinceitcontainsalongso3paddingbytesappearafterc3 Itappearsinmemoryintheorder l1byte1 l1byte2 l1byte3 l1byte4 s1byte1 s1byte2 c1 c2 c3 paddingbyte paddingbyte paddingbyte andisonly12byteslong. Ishouldpointoutthatstructurepackingisplatformandcompiler(andinsomecasescompiler switch)dependent. MemoryPoolsarejustasectionofmemoryreservedforallocatingtemporarilytootherpartsofthe application Amemoryleakoccurswhenyouallocatesomememoryfromtheheap(orapool)andthendeleteall referencestothatmemorywithoutreturningittothepoolitwasallocatedfrom. Program: structMyStructA{ chara;

34 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

charb; intc; }; structMyStructB{ chara; intc; charb; }; intmain(void){ intsizeA=sizeof(structMyStructA); intsizeB=sizeof(structMyStructB); printf(A=%d\n,sizeA); printf(B=%d\n,sizeB); return0; } 22.WhatisthedierencebetweenmacroandconstantvariablesinC? Macrosarereplacedbypreprocessor,butinconstantdatatypewillbecheckedbycompiler.Macros arereplacedwithoutcheckingthevaluessometimestheprogrammerwanttochangevaluesonlyina singlefunctionatthatprefertouseconstantthanamacro. ThersttechniquecomesfromtheCprogramminglanguage.Constantsmaybedenedusingthe preprocessordirective,#deneThepreprocessorisaprogramthatmodiesyoursourcelepriorto compilation.Commonpreprocessordirectivesare#include,whichisusedto includeadditionalcodeintoyoursourcele,#dene,whichisusedtodeneaconstantand #if/#endif,whichcanbeusedtoconditionallydeterminewhichpartsofyourcodewillbecompiled. The#denedirectiveisusedasfollows. #denepi3.1415#deneid_no12345 Wherevertheconstantappearsinyoursourcele,thepreprocessorreplacesitbyitsvalue.So,for instance,everypiinyoursourcecodewillbereplaceby3.1415.Thecompilerwillonlyseethe value3.1415inyourcode,notpi.Theproblemwiththistechniqueisthatthereplacementisdone lexically,withoutanytypechecking,withoutanyboundcheckingandwithoutanyscopechecking. Everypiisjustreplacedbyitsvalue.Thetechniqueisoutdated,existstosupportlegacycodeand shouldbeavoided. Const Thesecondtechniqueistousethekeywordconstwhendeningavariable.Whenusedthecompiler willcatchattemptstomodifyvariablesthathavebeendeclaredconst. constoatpi=3.1415;constintid_no=12345;

35 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

Therearetwomainadvantagesoverthersttechnique. First,thetypeoftheconstantisdened.piisoat.id_noisint.Thisallowssometypechecking bythecompiler.&nbsp; Second,theseconstantsarevariableswithadenitescope.Thescopeofavariablerelatestopartsof yourprograminwhichitisdened.Somevariablesmayexistonlyincertainfunctionsorincertain blocksofcode. Ex:Youmaywanttouseid_noinonefunction andacompletelyunrelatedid_noinyourmainprogram. 23.WhatisdierencebetweenreentrantfunctionandrecursivefunctioninC? Answer:Reentrantfunctionisafunctionwhichguaranteedthatwhichcanbeworkwellundermulti threadedenvironment.meanwhilefunctionisaccessbyonethread,anotherthreadcancallitmean thereisseparateexecutionstackandhandlingforeach.Sofunctionshouldnotcontainanystaticor sharedvariablewhichcanharmordisturbtheexecution.Meanfunctionwhichcanbecalledby thread,whilerunningfromanotherthreadsafelyandproperly Example:

intt; voidswap(int*x,int*y) { ints; s=t;//saveglobalvariable t=*x; *x=*y; //hardwareinterruptmightinvokeisr()here! *y=t; t=s;//restoreglobalvariable } voidisr() { intx=1,y=2; swap(&x,&y); }

RecursivefunctionExample: voiddoll(intsize) { if(size==0)//Nodollcanbesmallerthan1atom(10^0==1)sodoesntcallitself

36 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

return;//Returndoesnothavetoreturnsomething,itcanbeused //toexitafunction doll(size1);//Decrementsthesizevariablesothenextdollwillbesmaller. } intmain() { doll(10);//Startsowithalargedoll(itsalogarithmicscale) 24.WhatisVModel?Whatarethebenets? TheVmodelrepresentsasoftwaredevelopmentprocess(alsoapplicabletohardwaredevelopment) whichmaybeconsideredanextensionofthewaterfallmodel.Insteadofmovingdowninalinear way,theprocessstepsarebentupwardsafterthecodingphase,toformthetypicalVshape.The VModeldemonstratestherelationshipsbetweeneachphaseofthedevelopmentlifecycleandits associatedphaseoftesting. TheVmodelhasanumberofbenets: 1.Systemsdevelopmentprojectsusuallyhaveatestapproach,orteststrategydocument,which deneshowtestingwillbeperformedthroughoutthelifecycleoftheproject.TheVmodelprovidesa consistentbasisandstandardforpartofthatstrategy. 2.TheVmodelexplicitlysuggeststhattesting(qualityassurance)shouldbeconsideredearlyonin thelifeofaproject.Testingandxingcanbedoneatanystageinthelifecycle.However,thecostof ndingandxingfaultsincreasesdramaticallyasdevelopmentprogresses.Evidencesuggeststhatif afaultuncoveredduringdesigncosts1.0monetaryunittocorrect,thenthesamefaultuncoveredjust beforetestingwillcost6.5units,duringtesting15units,andafterreleasebetween60and100units. Theneedtondfaultsassoonaspossiblereinforcestheneedforthequalityassuranceofdocuments suchastherequirementsspecicationandthefunctionalspecication.Thisisperformedusingstatic testingtechniquessuchasinspectionsandwalkthroughs. 3.Itintroducestheideaofspecifyingtestrequirementsandexpectedoutcomespriortoperforming theactualtests.Forexample,theacceptancetestsareperformedagainstaspecicationof requirements,ratherthanagainstsomecriteriadreamedupwhentheacceptancestagehasbeen reached 4.TheVmodelprovidesafocusfordeningthetestingthatmusttakeplacewithineachstage.The denitionoftestingisassistedbytheideaofentryandexitcriteria.Hence,themodelcanbeusedto denethestateadeliverablemustbeinbeforeitcanenterandleaveeachstage.Theexitcriteriaof onestageareusuallytheentrycriteriaofthenext.Inmanyorganizations,thereisconcernaboutthe qualityoftheprogramcodereleasedbyindividualprogrammers.Someprogrammersreleasecode thatappearstobefaultfree,whileothersreleasecodethatstillhasmanyfaultsinit.Theproblemof programmersreleasingcodewithdierentlevelsofrobustnesswouldbeaddressedintheexit criteriaofunitdesignandunittesting.Unitdesignwouldrequireprogrammerstospecifytheir intendedtestcasesbeforetheywroteanyprogramcode.Codingcouldnotbeginuntilthesetestcases hadbeenagreedwithanappropriatemanager.Second,thetestcaseswouldhavetobeconducted successfullybeforetheprogramcouldleavetheunitteststageandbereleasedtointegrationtesting. 5.Finally,theVmodelprovidesabasisfordeningwhoisresponsibleforperformingthetestingat

37 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

eachstage.Herearesometypicalresponsibilities: acceptancetestingperformedbyusers systemtestingperformedbysystemtesters integrationtestingperformedbyprogramteamleaders unittestingperformedbyprogrammers. TheVmodelisthereforeanexcellentbasisforthepartitioningoftesting,highlightingthefactthatall theparticipantsinthedevelopmentofasystemhavearesponsibilityforqualityassuranceand testing. 25.WhatismeantbyBlackboxtestingandwhiteboxtesting? Whiteboxtesting(alsoknownasclearboxtesting,glassboxtesting,transparentboxtesting, andstructuraltesting)isamethodoftestingsoftwarethattestsinternalstructuresorworkingsofan application,asopposedtoitsfunctionality(i.e.blackboxtesting).Inwhiteboxtestinganinternal perspectiveofthesystem,aswellasprogrammingskills,areusedtodesigntestcases.Thetester choosesinputstoexercisepathsthroughthecodeanddeterminetheappropriateoutputs.Thisis analogoustotestingnodesinacircuit,e.g.incircuittesting(ICT). Whilewhiteboxtestingcanbeappliedattheunit,integrationandsystemlevelsofthesoftware testingprocess,itisusuallydoneattheunitlevel.Itcantestpathswithinaunit,pathsbetweenunits duringintegration,andbetweensubsystemsduringasystemleveltest.Thoughthismethodoftest designcanuncovermanyerrorsorproblems,itmightnotdetectunimplementedpartsofthe specicationormissingrequirement. Blackboxtestingisamethodofsoftwaretestingthatteststhefunctionalityofanapplicationas opposedtoitsinternalstructuresorworkings(seewhiteboxtesting).Thismethodoftestcanbe appliedtoalllevelsofsoftwaretesting:unit,integration,systemandacceptance.Ittypically comprisesmostifnotalltestingathigherlevels,butcanalsodominateunittestingaswell. (http://en.wikipedia.org/wiki/File:Blackbox.svg) WhiteBoxTesting:Meanstestingtheapplicationwithcoding/programmingknowledge.That meansthetesterhastocorrectthecodealso. Blackboxtesting:Testingtheapplicationwithoutcoding/programmingknowledgethatmeansthe testerdoesntrequirecodingknowledge.Justheexaminestheapplicationexternalfunctional behaviourandGUIfeatures. Sl.No 1 2 BlackBox Focusesonthefunctionalityofthe system Techniquesusedare: Equivalencepartitioning Boundaryvalueanalysis Errorguessing WhiteBox Focusesonthestructure(Program)of thesystem Techniquesusedare: BasisPathTesting FlowGraphNotation ControlStructureTesting

38 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

Raceconditions Causeeectgraphing Syntaxtesting Statetransitiontesting Graphmatrix

1.ConditionTesting 2.DataFlowtesting LoopTesting 1.SimpleLoops 2.NestedLoops 3.ConcatenatedLoops 4.UnstructuredLoops

3 4

Testercanbenontechnical

Testershouldbetechnical Helpstoidentifythelogicaland codingissues.

Helpstoidentifythevaguenessand contradictioninfunctional specications 26.Whatarethetypesoftestings? unittesting Componenttesting Integrationtesting Systemtesting

27.TheDierencebetweenBitRateandBaudRate? ThedierencebetweenBitandBaudrateiscomplicatedandintertwining.Botharedependentand interrelated.ButthesimplestexplanationisthataBitRateishowmanydatabitsaretransmittedper second.AbaudRateisthenumberoftimespersecondasignalinacommunicationschannel changes. Bitratesmeasurethenumberofdatabits(thatis0sand1s)transmittedinonesecondina communicationchannel.Agureof2400bitspersecondmeans2400zerosoronescanbetransmitted inonesecond,hencetheabbreviationbps.Individualcharacters(forexamplelettersornumbers) thatarealsoreferredtoasbytesarecomposedofseveralbits. Abaudrateisthenumberoftimesasignalinacommunicationschannelchangesstateorvaries.For example,a2400baudratemeansthatthechannelcanchangestatesupto2400timespersecond.The termchangestatemeansthatitcanchangefrom0to1orfrom1to0uptoX(inthiscase,2400) timespersecond.Italsoreferstotheactualstateoftheconnection,suchasvoltage,frequency,or phaselevel). Themaindierencebetweenthetwoisthatonechangeofstatecantransmitonebit,orslightlymore orlessthanonebit,thatdependsonthemodulationtechniqueused.Sothebitrate(bps)andbaud rate(baudpersecond)havethisconnection:

39 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

bps=baudpersecondxthenumberofbitperbaud Themodulationtechniquedeterminesthenumberofbitperbaud.Herearetwoexamples: WhenFSK(FrequencyShiftKeying,atransmissiontechnique)isused,eachbaudtransmitsonebit. Onlyonechangeinstateisrequiredtosendabit.Thus,themodemsbpsrateisequaltothebaud rate.Whenabaudrateof2400isused,amodulationtechniquecalledphasemodulationthat transmitsfourbitsperbaudisused.So: 2400baudx4bitsperbaud=9600bps Suchmodemsarecapableof9600bpsoperation. 3)DierencebetweenashandEEprom 1. Similarities BothashandEEPROMaredigitalstoragemethodsusedbycomputersandotherdevices.Both arenonvolatileROMtechnologiestowhichyoucanwriteandfromwhichyoucanerasemultiple times. Dierences TheprimarydierencebetweenashandEEPROMisthewaytheyerasedata.WhileEEPROM destroystheindividualbytesofmemoryusedtostoredata,ashdevicescanonlyerasememory inlargerblocks.Thismakesashdevicesfasteratrewriting,astheycanaectlargeportionsof memoryatonce.Sincearewritemayaectunusedblocksofdata,italsoaddsunnecessarilyto usageofthedevice,shorteningitslifespanincomparisonwithEEPROM. Usage FlashstorageiscommonlyusedinUSBmemorydrivesandsolidstateharddrives.EEPROMis usedinavarietyofdevices,fromprogrammableVCRstoCDplayers. 28.Canstructuresbepassedtothefunctionsbyvalue? Ans:yesstructurescanbepassedbyvalue.Butunnecessarymemorywastage. 29.Whycannotarraysbepassedbyvaluestofunctions? Ans:Whenaarrayispassedtoafunction,thearrayisinternallychangedtoapointer.Andpointers arealwayspassedbyreference. 30.Whatismeantbystaticfunctions? Ans:staticfunctionsarefunctionsthatareonlyvisibletootherfunctionsinthesamele Example: main.c #include<STDIO.H>

40 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

main() { Func1(); Func2(); }

funcs.c /************************************* * *Functiondeclarations(prototypes). * *************************************/ /*Func1isonlyvisabletofunctionsinthisfile.*/ staticvoidFunc1(void); /*Func2isvisabletoallfunctions.*/ voidFunc2(void); /************************************* * *Functiondefinitions * *************************************/ voidFunc1(void) { puts("Func1called"); } /*************************************/voidFunc2(void) { puts("Func2called"); }

31.Dierencebetweendeclaration,denition&initialization? Ans:Adeclarationintroducesanameanidentiertothecompiler.IttellsthecompilerThis functionorthisvariableexistssomewhere,andhereiswhatitshouldlooklike.


41 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

Adenition,ontheotherhand,says:MakethisvariablehereorMakethisfunction here.It allocatesstorageforthename.Thismeaningworkswhether youretalkingaboutavariableorafunction;ineithercase,atthepointofdenitionthecompiler allocatesstorage. externconstintx=1;/*Initialization*/ Thisinitializationestablishesthisasadenition,notadeclaration. externconstintx;/*Declaration*/ ThisdeclarationinC++meansthatthedenitionexistselsewhere. 32.Whatisthedierencebetweenpassbyvaluebyreferenceincandpassbyreferenceinc? PassByReference: InPassbyreferenceaddressofthevariableispassedtoafunction.Whateverchangesmadetotheformal parameterwillaecttotheactualparameters Samememorylocationisusedforbothvariables.(FormalandActual) itisusefulwhenyourequiredtoreturnmorethen1values PassByValue: Inthismethodvalueofthevariableispassed.Changesmadetoformalwillnotaecttheactualparameters. Dierentmemorylocationswillbecreatedforbothvariables. Heretherewillbetemporaryvariablecreatedinthefunctionstackwhichdoesnotaecttheoriginalvariable. 33.Whatisthedierencebetweenashmemory,EPROMandEEPROM? EEPROMisanolder,morereliabletechnology.ItissomewhatslowerthanFlash.FlashandEEPROM areverysimilar,butthereisasubtledierence.FlashandEEPROMbothusequantumcellstotrap electons.Eachcellrepresentsonebitofdata.Thepresenceorabsenceofelectonsinacellindicates whetherthebitisa1or0.Thecellshaveanitelifeeverytimeacelliserased,itwearsoutalittle bit.InEEPROM,cellsareerasedonebyone.Theonlycellserasedarethosewhichare1butneedto bezero.(Writinga1toacellthats0causesverylittlewear,IIRC)InFlash,alargeblockiserasedall atonce.Insomedevices,thisblockistheentiredevice.Soinash,cellsareerasedwhetherthey needitornot.Thiscutsdownonthelifespanofthedevice,butismuch,muchfasterthanthe EEPROMmethodofgoingcellbycell. Erasuremethod:BothFlashandEEPROMerasecellsbymeansofanelectriceld.Ithinkitis highfrequencyandpopstheelectronsoutoftheOthersimilardevicesareEPROM(sometimes UVEPROM)andOTPROM(sometimesPROM).EPROM/UVEPROMlacksthestructuresthat generatetheelectricaleldforerasure.Thesedeviceshaveawindowontop,usuallycoveredbya papersticker.Toerase,thestickerisremovedandthedeviceisexposedtointenseultravioletlightfor 3045minutes.TheonlydierencebetweenOTPROMandUVEPROMisthatOTPROMlackstheUV windowthereisnowaytoerasethedata.AddingtheUVwindowtothedevicepackage signicantlyincreasescost,sothereisanicheforonetimeprogrammabledevices

TheinformationstoredinanEPROMchipcanbeerasedbyexposingthechiptostrongUVlight.

42 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

EPROMchipsareeasilyrecognizedbythesmallquartz windowusedforerasure.Onceerasedthe chipcanbereprogrammed. EPROMismoreexpensivetobuyperunitcost,butcanprovecheaperinthelongrunforsome applications.ForexampleifPROMwasusedforrmwarethatneededupgradedevery6monthsor soitcouldprovequiteexpensivebuyingnewchips!

Thishastheaddedadvantagethattheinformationstoredcanberewritteninblocksandhencecan beusedtostoresystemsettingsthattheusermaywanttochangeperiodically. Thissolidstatememoryhasconsiderablyreducedinpriceoverrecentyearsandisnowadays commonlyusedtostoresystemsettingssuchasBIOSsettings 34.WhatisdierencebetweenVolatile&NonVolatileMemory? Volatilememory Volatilememoryiscomputermemorythatrequirespowertomaintainthestoredinformation.Most modernsemiconductorvolatilememoryiseitherStaticRAM(seeSRAM)ordynamicRAM(see DRAM).SRAMretainsitscontentsaslongasthepowerisconnectedandiseasytointerfacetobut usessixtransistorsperbit.DynamicRAMismorecomplicatedtointerfacetoandcontrolandneeds regularrefreshcyclestopreventitscontentsbeinglost.However,DRAMusesonlyonetransistorand acapacitorperbit,allowingittoreachmuchhigherdensitiesand,withmorebitsonamemorychip, bemuchcheaperperbit.SRAMisnotworthwhilefordesktopsystemmemory,whereDRAM dominates,butisusedfortheircachememories.SRAMiscommonplaceinsmallembeddedsystems, whichmightonlyneedtensofkilobytesorless.Forthcomingvolatilememorytechnologiesthathope toreplaceorcompetewithSRAMandDRAMincludeZRAM,TTRAM,ARAMandETARAM.

Nonvolatilememoryiscomputermemorythatcanretainthestoredinformationevenwhennot powered.Examplesofnonvolatilememoryincludereadonlymemory(seeROM),ashmemory, mosttypesofmagneticcomputerstoragedevices(e.g.harddisks,oppydiscsandmagnetictape), opticaldiscs,andearlycomputerstoragemethodssuchaspapertapeandpunchedcards. ForthcomingnonvolatilememorytechnologiesincludeFeRAM,CBRAM,PRAM,SONOS,RRAM, Racetrackmemory,NRAMandMillipede.

43 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

35.Whatisareentrantfunction? Areentrantfunctionisafunctionwhichcanbesafelyexecutedconcurrently.Thismeansitshould allowareentrywhileitisrunning.Thereentrantfunctionshouldworkonlyonthedatagivenbythe callingfunction.Itmustnothaveanystaticdataalso. Thetermreentrantisusedtorefertosidewallprolesofthenozzles,whereinexitdiametersofthe nozzlesaresmallerthanentrancediametersofthenozzlessothatthesidewallsofthenozzlesarenot perpendiculartoaplanedenedbyanexitsurfaceofthenozzlemember. AReentrantfunctionisafunctionwhichguaranteedthatwhichcanbeworkwellundermulti threadedenvironment.Meanwhilefunctionisaccessbyonethread,anotherthreadcancallit meanthereisseparateexecutionstackandhandlingforeach.Sofunctionshouldnotcontainany staticorsharedvariablewhichcanharmordisturbtheexecution. 36.WhyweareusingUDS,IfCANsupportdiagnosticscommunication? InCANitwillsupportinternaldiagnosticmessages.UDS&KWP2000areusedfortotestwith externaltesterandtoknowthetypeofproblem 37.HowtorecoverfromCANBuso?

TodistinguishbetweentemporaryandpermanentfailureseveryCANbuscontrollerhastwoError Counters:TheREC(ReceiveErrorCounter)andtheTEC(TransmitErrorCounter).Thecountersare incrementedupondetectederrorsrespectivelyaredecrementeduponcorrecttransmissionsor receptions.Dependingonthecountervaluesthestateofthenodeischanged:Theinitialstateofa CANbuscontrollerisErrorActivethatmeansthecontrollercansendactiveErrorFlags.The controllergetsintheErrorPassivestateifthereisanaccumulationoferrors. OnCANbuscontrollerfailureoranextremeaccumulationoferrorsthereisastatetransitiontoBus O.Thecontrollerisdisconnectedfromthebusbysettingitinastateofhighresistance.TheBusO stateshouldonlybeleftbyasoftwarereset.AftersoftwareresettheCANbuscontrollerhasto waitfor128x11recessivebitstotransmitaframe.Thisisbecauseothernodesmaypending transmissionrequests.Itisrecommendednottostartanhardwareresetbecausethewaittimerule willnotbefollowedthen.

44 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

37.WhatisVirtualfunctionalbus? Virtualfunctionbuscanbedescribedasasystemmodelingandcommunicationconcept.Itislogical entitythatfacilitatesthe conceptofrelocatabilitywithintheAUTOSARsoftwarearchitecturebyprovidingavirtual infrastructurethatisindependentfromanyactualunderlyinginfrastructureandprovidesallservices requiredforavirtualinteractionbetweenAUTOSARcomponents. 38.IntraandInterECUcommunication? IntraECUwhichdenotesthecommunicationbetweentwosoftwarecomponentsresidingonthe sameECUandInterECUwhichdenotesthesituationwhentwosoftwarecomponentsresideon dierentECUsthatareconnectedviaabusnetwork. 39.Whatisthedierencebetweenglobalandstaticglobalvariables? Globalvariablesarevariablesdenedoutsideofanyfunction.Theirscopestartsatthepointwhere theyaredenedandlaststotheendofthele.Theyhaveexternallinkage,whichmeansthatinother sourceles,thesamenamereferstothesamelocationinmemory. Staticglobalvariablesareprivatetothesourcelewheretheyaredenedanddonotconictwith othervariablesinothersourceleswhichwouldhavethesamename. 40.HowtoaccessaGlobalvariablesinotherles? Variablesdeclaredoutsideofablockarecalledglobalvariables.Globalvariableshaveprogram scope,whichmeanstheycanbeaccessedeverywhereintheprogram,andtheyareonlydestroyed whentheprogramends. Hereisanexampleofdeclaringaglobalvariable: 1 2 3 4 5 6 7 8 9 10 intg_nX;//globalvariable intmain() { intnY;//localvariablenY //globalvarscanbeseeneverywhereinprogram //sowecanchangetheirvalueshere g_nX=5; }//nYisdestroyedhere Becauseglobalvariableshaveprogramscope,theycanbeusedacrossmultipleles.Inthesectionon programswithmultipleles,youlearnedthatinordertouseafunctiondeclaredinanotherle,you havetouseaforwarddeclaration,oraheaderle. Similarly,inordertouseaglobalvariablethathasbeendeclaredinanotherle,youhavetousea forwarddeclarationoraheaderle,alongwiththeexternkeyword.Externtellsthecompilerthat youarenotdeclaringanewvariable,butinsteadreferringtoavariabledeclaredelsewhere.

45 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

Hereisanexampleofusingaforwarddeclarationstyleextern: global.cpp: 1 2 //declarationofg_nValue intg_nValue=5;

main.cpp: 1 2 3 4 5 6 7 8 //externtellsthecompilerthisvariableisdeclaredelsewhere externintg_nValue; intmain() { g_nValue=7; return0; } Hereisanexampleofusingaheaderleextern: global.cpp: 1 2 //declarationofg_nValue intg_nValue=5;

global.h: 1 2 3 4 5 6 7 #ifndefGLOBAL_H//headerguards #defineGLOBAL_H //externtellsthecompilerthisvariableisdeclaredelsewhere externintg_nValue; #endif main.cpp: 1 2 3 4 5 6 #include"global.h" intmain() { g_nValue=7; return0; }

Generallyspeaking,ifaglobalvariableisgoingtobeusedinmorethan2les,itsbettertousethe headerleapproach.Someprogrammersplaceallofaprogramsglobalvariablesinalecalled globals.cpp,andcreateaheaderlenamedglobals.htobeincludedbyother.cpplesthatneedto usethem.


46 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

Localvariableswiththesamenameasaglobalvariablehidetheglobalvariableinsidethatblock. However,theglobalscopeoperator(::)canbeusedtotellthecompileryoumeantheglobalversion: 1 2 3 4 5 6 7 8 9 intnValue=5; intmain() { intnValue=7;//hidestheglobalnValuevariable nValue++;//incrementslocalnValue,notglobalnValue ::nValue;//decrementsglobalnValue,notlocalnValue return0; }//localnValueisdestroyed However,havinglocalvariableswiththesamenameasglobalvariablesisusuallyarecipefor trouble,andshouldbeavoidedwheneverpossible.UsingHungarianNotation,itiscommonto declareglobalvariableswithag_prex.Thisisaneasywaytodierentiateglobalvariablefrom localvariables,andavoidvariablesbeinghiddenduetonamingcollisions. Newprogrammersareoftentemptedtouselotsofglobalvariables,becausetheyareeasytowork with,especiallywhenmanyfunctionsareinvolved.However,thisisaverybadidea.Infact,global variablesshouldgenerallybeavoidedcompletely! Whyglobalvariablesareevil Globalvariablesshouldbeavoidedforseveralreasons,buttheprimaryreasonisbecausethey increaseyourprogramscomplexityimmensely.Forexample,sayyouwereexaminingaprogram andyouwantedtoknowwhatavariablenamedg_nValuewasusedfor.Becauseg_nValueisa global,andglobalscanbeusedanywhereintheentireprogram,youdhavetoexamineeverysingle lineofeverysinglele!Inacomputerprogramwithhundredsoflesandmillionsoflinesofcode, youcanimaginehowlongthiswouldtake! Second,globalvariablesaredangerousbecausetheirvaluescanbechangedbyanyfunctionthatis called,andthereisnoeasywayfortheprogrammertoknowthatthiswillhappen.Considerthe followingprogram: 1 2 3 4 5 6 7 8 9 10 11 12 //declareglobalvariable intg_nMode=1; voiddoSomething() { g_nMode=2; } intmain() {

47 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

13 14 15 16 17 18 19 20 21 22 23 24

g_nMode=1; doSomething(); //Programmerexpectsg_nModetobe1 //ButdoSomethingchangeditto2! if(g_nMode==1) cout<<"Nothreatdetected."<<endl; else cout<<"Launchingnuclearmissiles..."<<endl; return0;

} Notethattheprogrammersetg_nModeto1,andthencalleddoSomething().Unlesstheprogrammer hadexplicitknowledgethatdoSomething()wasgoingtochangethevalueofg_nMode,heorshewas probablynotexpectingdoSomething()tochangethevalue!Consequently,therestofmain()doesnt workliketheprogrammerexpects(andtheworldisobliterated). Globalvariablesmakeeveryfunctioncallpotentiallydangerous,andtheprogrammerhasnoeasy wayofknowingwhichonesaredangerousandwhichonesarent!Localvariablesaremuchsafer becauseotherfunctionscannotaectthemdirectly.Consequently,globalvariablesshouldnotbe usedunlessthereisaverygoodreason! 41.WhatistheuseofComplexDeviceDriversinAUTOSAR? SincetheAUTOSARlayeredsoftwarearchitecturerestrictsdirectaccesstohardwarefromupper layers,anadditionalconceptisprovidedinordertobypassthatrestrictionforresourcecriticaland/or NonAUTOSARcompliantsoftwarecomponents.TheComplexDeviceDriverprovidesan AUTOSARInterfacetotheapplicationlayerandhasdirectaccesstovaluesonthephysicallayer.This isusuallyusedfortheimplementationofcomplexsensororactuatordriversthatneeddirectcontrol overtheunderlyinghardware. 42.Howtoset,clear,toggleandcheckingasinglebitinC? UsethebitwiseORoperator(|)tosetabit.

number|=1<<x;

Thatwillsetbitx.

48 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

Clearingabit UsethebitwiseANDoperator(&)toclearabit.

number&=~(1<<x);

Thatwillclearbitx.YoumustinvertthebitstringwiththebitwiseNOToperator(~),thenANDit. Togglingabit TheXORoperator(^)canbeusedtotoggleabit.

number^=1<<x;

Thatwilltogglebitx. Checkingabit YoudidntaskforthisbutImightaswelladdit. Tocheckabit,ANDitwiththebityouwanttocheck:

bit=number&(1<<x);

Thatwillputthevalueofbitxintothevariablebit. 42.WhatisWatchdogtimer? Awatchdogtimer(orcomputeroperatingproperly(COP)timer)isacomputerhardwareorsoftware timerthattriggersasystemresetorothercorrectiveactionifthemainprogram,duetosomefault condition,suchasahang,neglectstoregularlyservicethewatchdog(writingaservicepulsetoit, alsoreferredtoaskickingthedog,pettingthedog,feedingthewatchdogorwakingthe watchdog).Theintentionistobringthesystembackfromtheunresponsivestateintonormal operation.Watchdogtimerscanbemorecomplex,attemptingtosavedebuginformationontoa persistentmedium;i.e.informationusefulfordebuggingtheproblemthatcausedthefault.Inthis caseasecond,simpler,watchdogtimerensuresthatiftherstwatchdogtimerdoesnotreport completionofitsinformationsavingtaskwithinacertainamountoftime,thesystemwillresetwith orwithouttheinformationsaved.Themostcommonuseofwatchdogtimersisinembedded

49 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

systems,wherethisspecializedtimerisoftenabuiltinunitofamicrocontroller.

(http://automotivetechis.les.wordpress.com/2012/06 /untitled4.jpg) 43.Whatisthedierencebetween8bit16bitand32bitprocessor? Dierentfamiliesofmicrosvaryintheircapabilities.Thenumberofbitsjustreferstothewidthofthe datapipe,whichlimitstheprecisionofmath,althoughmanymicroswilleitheremulatehigherorder mathorhavespecialHWthatcanperformhigherprecisionmathfunctions. Thehistoricdierencehasbeenprice:8bitwascheapest,32bitwasexpensive.Thisisstilltruein generally,butthepriceof16bitpartshavecomedownsignicantly. Most8bitprocessorsareoldandrunonoldarchitectures,sotheytendtobeslower.Theyarealso mademorecheaply,sincethatiswherethecompetitionisatthe8bitpoint,andthismakesthem tendtowardsslowness.TheyalsotendtohavealowlimitonsupportedRAM/otherstorage,butthe actualamountdependsonthefamily. 16bitprocessorstendtofocusonpriceaswell,butthereisalargerangeofpartsavailable,someof whichhavefairlyhighperformanceandlargeamountsofonchipperipherals.Thesepartsusually performfasterthan8bitpartsonmathwheretheprecisionisgreaterthan8bits,andtendtohave moreaddressablememory. 32bitchipscompeteprimarilyonperformanceforanapplication.Thereisaconsiderablerangeof 32bitpartsavailable,eachtargetedatsomespecicapplication.Theytendtocomeloadedwith peripheralsandcompeteonfeaturecompleteness.Theyhavealargeamountofaddressablememory andtheperformancetendstobebetterthan16bitparts. 44.WhatisaFunctionPointer? Afunctionpointerisavariablethatstorestheaddressofafunctionthatcanlaterbecalledthrough thatfunctionpointer.Thisisusefulbecausefunctionsencapsulatebehavior.Forinstance,everytime youneedaparticularbehaviorsuchasdrawingaline,insteadofwritingoutabunchofcode,allyou needtodoiscallthefunction.Butsometimesyouwouldliketochoosedierentbehaviorsat dierenttimesinessentiallythesamepieceofcode. Example:int(*fp)(int,int);>Functionpointerreturninganinteger 45.SizeofDatatypes

50 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

Name char short int(short) int

Description Characterorsmallinteger. ShortInteger. Integer.

Size* 1byte 2bytes 4bytes

Range* signed:128to127 unsigned:0to255 signed:32768to32767 unsigned:0to65535 signed:2147483648to 2147483647 unsigned:0to4294967295 signed:2147483648to 2147483647 unsigned:0to4294967295 trueorfalse +/3.4e+/38(~7digits) +/1.7e+/308(~15digits) +/1.7e+/308(~15digits)

long int(long) bool float double longdouble

Longinteger.

4bytes

Booleanvalue.Itcantakeoneoftwo values:trueorfalse. Floatingpointnumber. Doubleprecisionoatingpointnumber. Longdoubleprecisionoatingpoint number.

1byte 4bytes 8bytes 8bytes

46.Whatisthedierencebetweentypedef&Macros? Typedefisusedtocreateanewnametoanalreadyexistingdatatype.Redenethenamecreates conictwiththepreviousdeclaration. eg: typedefunsignedintUINT32 Macros[#dene]isadirectsubstitutionofthetextbeforecomplingthewholecode.Inthegiven example,itsjustatextualsubstitution.wherethereisaposibilityofredeningthemacro eg: #denechPointerchar* #undefchPointer #denechPointerint* Typedefareusedfordeclarationswhencomparewithmacro typedefscancorrectlyencodepointertypes.whereas#DEFINESarejustreplacementsdonebythe preprocessor. Forexample, 1. typedefchar*String_t; 2. #deneString_dchar* 3. String_ts1,s2;String_ds3,s4;

51 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

s1,s2,ands3arealldeclaredaschar*,buts4isdeclaredasachar,whichisprobablynotthe intention. 47.Whatisthedierencebetweenamacroandafunction? Macrosareessentiallyshorthandrepresentationsofarbitrarysectionsofthesourcecode,which makesthesourcecode,whileits(themacrotemplates)expansionreplaceseachofitspresenceprior tocompilation.WhateveristheretodowithMacros,itisdonebythepreprocessor,sothatthesource codeisreadyforcompilation.Functionisacallingroutine,whencealargeprogramisdividedinto separateportions,eachportiondoingaseparatejob,andpropercallingoftheseportionsindierent placescombinestheworksdonebythemintotherequiredcompleteoutput.Thusfunctionshave nothingtodowiththepreprocessingperiod,theyarejustcompiled.Tosomeextentfunctionand macroissimilar,foramacrocanoccasionallybeinvokedtoperformataskthatisgenerallyentrusted toafunction.Butthesimilarityendsthere. Thedierencesare: 1. Macroconsumeslesstime.Whenafunctioniscalled,argumentshavetobepassedtoit,those argumentsareacceptedbycorrespondingdummyvariablesinthefunction,theyareprocessed, andnallythefunctionreturnsavaluethatisassignedtoavariable(exceptforavoidfunction).If afunctionisinvokedanumberoftimes,thetimesaddup,andcompilationisdelayed.Onthe otherhand,themacroexpansionhadalreadytakenplaceandreplacedeachoccurrenceofthe macrointhesourcecodebeforethesourcecodestartscompiling,soitrequiresnoadditionaltime toexecute. 2. Functionconsumeslessmemory.Whileafunctionrepletewithmacrosmaylooksuccincton surface,priortocompilation,allthemacropresencesarereplacedbytheircorrespondingmacro expansions,whichconsumesconsiderablememory.Ontheotherhand,evenifafunctionis invoked100times,itstilloccupiesthesamespace.Hencefunctionismoreamenabletoless memoryrequirements 48.Whatisinlinefunction? Inlinefunctionistheoptimizationtechniqueusedbythecompilers.Onecansimplyprependinline keywordtofunctionprototypetomakeafunctioninline.Inlinefunctioninstructcompilertoinsert completebodyofthefunctionwhereverthatfunctiongotusedincode. Advantages: 1)Itdoesnotrequirefunctioncallingoverhead. 2)Italsosaveoverheadofvariablespush/poponthestack,whilefunctioncalling. 3)Italsosaveoverheadofreturncallfromafunction. 4)Itincreaseslocalityofreferencebyutilizinginstructioncache. 5)Afterinliningcompilercanalsoapplyintraproceduraloptmizationifspecied.Thisisthemost importantone,inthiswaycompilercannowfocusondeadcodeelimination,cangivemorestresson branchprediction,inductionvariableeliminationetc.. Disadvantages: 1)Mayincreasefunctionsizesothatitmaynottonthecache,causinglotsofcahcemiss. 2)Afterinliningfunctionifvariablesnumberwhicharegoingtouseregisterincreasesthantheymay createoverheadonregistervariableresourceutilization.

52 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

3)Itmaycausecompilationoverheadasifsomebodychangescodeinsideinlinefunctionthanall callinglocationwillalsobecompiled. 4)Ifusedinheaderle,itwillmakeyourheaderlesizelargeandmayalsomakeitunreadable. 5)Ifsomebodyusedtoomanyinlinefunctionresultantinalargercodesizethanitmaycause thrashinginmemory.Moreandmorenumberofpagefaultbringingdownyourprogram performance. 6)Itsnotusefulforembededsystemwherelargebinarysizeisnotpreferredatallduetomemory sizeconstraints 49.Whatisthedierencebetweenamacroandainlinefunction? Macros: 1.inputargumentdatatypecheckingcantbedone. 2.compilerhasnoideaaboutmacros 3.Codeisnotreadable 4.macrosarealwaysexpandedorreplacedduringpreprocessing,hencecodesizeismore. 5.macrocantreturn. Inlinefunction: 1.inputargumentdatatypecanbedone. 2.compilerknowsaboutinlinefunctions. 3.codeisreadable 4.inlinefunctionsaremaynotbeexpandedalways 5.canreturn. 50.PreprocessorStatements#ifdef,#else,#endif Theseprovidearapidwaytoclipoutandinsertcode. Consider;

#defineFIRST main() { inta,b,c; #ifdefFIRST a=2;b=6;c=4; #else printf("Entera:"); scanf("%d",&a); printf("Entera:"); scanf("%d",&a);

53 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

printf("Entera:"); scanf("%d",&a); #endif additonalcode

NotethatifFIRSTisdened(whichitisintheabove)thevaluesofa,bandcarehardcodedtovalues of2,6and4.Thiscansavealotoftimewhendevelopingsoftwareasitavoidstediouslytyping everythingineachandeverytimeyourunyourroutine.WhenFIRSTisdened,allthatispassedto thecompileristhecodebetweenthe#ifdefandthe#else.Thecodebetweenthe#elseandthe#endifis notseenbythecompiler.Itisasifitwereallacomment. Onceyouhaveyourroutineworking,anddesiretoinserttheprintfandscanfs,allthatisrequiredis togobackanddeletethethe#deneFIRST.Now,thecompilerdoesnotseethe;

a=2;b=6;c=4; HowtocalculateCRCSequenceinaCANFrame?

ThereceiverscalculatetheCRCinthesamewayasthetransmitterasfollows: 1. Themessageisregardedaspolynomandisdividedbythegeneratorpolynom: 15 x +x14+x10+x8+x7+x4+x3+1. 2. Thedivisionrestofthismodulo2divisionistheCRCsequencewhichistransmittedtogetherwith themessage. 3. ThereceiverdividesthemessageinclusivetheCRCsequencebythegeneratorpolynom.

ACRCerrorhastobedetected,ifthecalculatedresultisnotthesameasthatreceivedintheCRC sequence.InthiscasethereceiverdiscardsthemessageandtransmitsanErrorFrametorequest retransmission.


54 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

51.DierencebetweenstaticanddynamicRAM? StaticRAM(SRAM)Highcost&Fast 1.4timesmoreexpensive 2.Verylowaccesstime 3.Canstoreasmuch 4.InformationstoredonRSipops 5.Noneedforrefreshing DynamicRAM(DRAM)Lowcost&slow 1.Lowcost 2.Consumeslesspower 3.Canstore4timesasmuch 4.InformationstoredonFETtransistors 5.Needstoberefreshed CANoeToolQuestions: WhatisdierencethebetweenIGandGblockinCANalyzer/CANoetool? Answer:TherearetwolimitationstotheGeneratorblockthatlimititseectivenessincomplextasks. Theblockismisleadingforsomepeoplebecauseitrequiresmultiplewindowsforsettingupthe transmitmessagelist.ThesecondproblemistheblocksettingshavetobesetbeforetheCANalyzer measurementstarts.Nochangescanbemadeifthemeasurementisrunning. Fortunately,CANalyzerhasanothertransmissionblockthateliminatesbothpracticallimitations:the InteractiveGeneratorblock(IG).TheIGblockcombinesthecongurationwindowsoftheGenerator blockintoonewindow;therefore,everythingcanbesetupinonespot.Inaddition,changescanbe madewiththeIG. WithoutCAPL,canwesimulatetheotherECUsCANMessagesexceptTestECUintheCAN SimulationNetworkinCANoetoolwithoutusingIGorGblocks. HowtochangethebaudrateinCANoewithoutchangingthecode? Thebitratemaybechangedbyeitherchangingtheoscillatorfrequency,whichisusually restrictedbytheprocessorrequirements,orbyspecifyingthelengthofthebitsegmentsintime quantumandtheprescalervalue. InCanoetool,wecanchangethebustimingregister0&1valuesforcorrectingthebaudrate. InAutosar,wecanusepostbuildcongurationforCANbaudratevalues. Whatisenvironmentvariable? EnvironmentvariablesaredataobjectsglobaltotheCANoeenvironmentandareusedtolinkthe functionsofaCANoepaneltoCAPLprograms.

55 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

WhatisHILandSILtesting? Answer:Hardwareintheloop(HIL)simulationisatechniquethatisusedinthedevelopmentand testofcomplexrealtimeembeddedsystems.HILsimulationprovidesaneectiveplatformby addingthecomplexityoftheplantundercontroltothetestplatform.Thecomplexityoftheplant undercontrolisincludedintestanddevelopmentbyaddingamathematicalrepresentationofall relateddynamicsystems.Thesemathematicalrepresentationsarereferredtoastheplant simulation.Theembeddedsystemtobetestedinteractswiththisplantsimulation. HardwareIntheLoopSystemisaneectiveplatformfordevelopingandtestingcomplexrealtime embeddedsystems.HILsystemprovidesthecomplexityoftheplantundercontrolusing mathematicalrepresentation,calledplantsimulation,ofallrelateddynamicsystems.Italso includeselectricalemulationofsensorsandactuatorswhichactastheinterfacebetweentheplant simulationandtheembeddedsystemundertest. AdvantagesofHILSystem ProvidesCostSavingsbyShortenedDevelopmenttime Complete,consistenttestcoverage. Supportsautomatedtesting Enablestestingthehardwarewithoutbuildingaplantprototype Simulatorperformstestoutsidethenormalrangeofoperation Supportsreproducibletestrunsthatcanassistinuncoveringandtrackingdownhardtond problems. Enablestestingwithlessriskofdestroyingthesystem SIL:SILreferstothekindoftestingdonetovalidatethebehavioroftheCcodeusedinthe controller.Thatcodecanbeautogeneratedfromthemodelusedinalgorithmdevelopment. EmmeskayhasadeepunderstandingofSILtestingandautocodegenerationfromthemanySIL projectswehaveperformedforourcustomers. TestingandValidation PlantmodeldevelopedinvehiclesimulationenvironmentisimportedtoSimulinkasalibrary. Controlleristestedinloopwiththeplantfordierentroutesandspeedproles. ControlleristestedfordierentfaultmodesofthesystemusingGUIVisualConnex RTOSQuestion: WhatisRTOS? RealTimeOperatingSystemisamultitaskingoperatingsystemintendedforrealtimeapplications.It isusedoneverydevice/systemneedingrealtimeoperationsthatmeansoperationsbasednotonlyon correctnessbutalsouponthetime(clockcycles)inwhichtheyareperformed. Ingeneral,anoperatingsystem(OS)isresponsibleformanagingthehardwareresourcesofa computerandhostingapplicationsthatrunonthecomputer.AnRTOSperformsthesetasks,butis alsospeciallydesignedtorunapplicationswithveryprecisetimingandahighdegreeofreliability. Thiscanbeespeciallyimportantinmeasurementandautomationsystemswheredowntimeiscostly oraprogramdelaycouldcauseasafetyhazard.Tobeconsideredrealtime,anoperatingsystem
56 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

musthaveaknownmaximumtimeforeachofthecriticaloperationsthatitperforms(oratleastbe abletoguaranteethatmaximummostofthetime).SomeoftheseoperationsincludeOScallsand interrupthandling.Operatingsystemsthatcanabsolutelyguaranteeamaximumtimeforthese operationsarecommonlyreferredtoashardrealtime,whileoperatingsystemsthatcanonly guaranteeamaximummostofthetimearereferredtoassoftrealtime. Example:Imaginethatyouaredesigninganairbagsystemforanewmodelofcar.Inthiscase,a smallerrorintiming(causingtheairbagtodeploytooearlyortoolate)couldbecatastrophicand causeinjury.Therefore,ahardrealtimesystemisneeded;youneedassuranceasthesystemdesigner thatnosingleoperationwillexceedcertaintimingconstraints.Ontheotherhand,ifyouwereto designamobilephonethatreceivedstreamingvideo,itmaybeoktoloseasmallamountofdata occasionallyeventhoughonaverageitisimportanttokeepupwiththevideostream.Forthis application,asoftrealtimeoperatingsystemmaysuce.AnRTOScanguaranteethataprogram willrunwithveryconsistenttiming.Realtimeoperatingsystemsdothisbyprovidingprogrammers withahighdegreeofcontroloverhowtasksareprioritized,andtypicallyalsoallowcheckingto makesurethatimportantdeadlinesaremet. HowRealTimeOSsDierfromGeneralPurposeOSs? OperatingsystemssuchasMicrosoftWindowsandMacOScanprovideanexcellentplatformfor developingandrunningyournoncriticalmeasurementandcontrolapplications.However,these operatingsystemsaredesignedfordierentusecasesthanrealtimeoperatingsystems,andarenot theidealplatformforrunningapplicationsthatrequireprecisetimingorextendeduptime.This sectionwillidentifysomeofthemajorunderthehooddierencesbetweenbothtypesofoperating systems,andexplainwhatyoucanexpectwhenprogrammingarealtimeapplication.

Interruptlatencyismeasuredastheamountoftimebetweenwhenadevicegeneratesaninterrupt andwhenthatdeviceisserviced.Whilegeneralpurposeoperatingsystemsmaytakeavariable amountoftimetorespondtoagiveninterrupt,realtimeoperatingsystemsmustguaranteethatall interruptswillbeservicedwithinacertainmaximumamountoftime.Inotherwords,theinterrupt latencyofrealtimeoperatingsystemsmustbebounded UnansweredInterviewQuestions Ifyouknowcommentasreply) WhatistheuseofPassiveerrornode? ErrorPassivereceiverscannolongerinterruptthedatatransferasarecessiveErrorFlagdoesnot inuencethebuslevels.AnErrorPassivetransmittercanstillinterruptitsownmessagebysendinga passiveErrorFlag.Attention,ifoneReceiverisinerrorpassivemodenodataconsistencyis guaranteedanymore. Howtondthebugincodeusingdebuggerifpointerispointingtoaillegalvalue? IftwoCANmessageswithsameIDsendingatasametime,dierentdatawhichcannodewill

57 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

gainarbitration?Howtotestit? Isitpossibletodeclarestructanduniononeinsideother?Explainwithexample 1. 2. 3. 4. 5. 6. 7. 8. SpiandI2Cdierence.? WhatisUDSadvantages? Whatiscrosscompiler Unit/integration/alltestings. Regressiontesting. Testcasetypes. Malloccalloc FunctionpointersAdvantagewhereitisused?

HowmanycandatabaselesarerequiredforCANNetworksimulationinCANoetool. whatisthedierencebetweenCANalyzer,CANoeandCANapetools? MentionthefewusesoftheCANoetool? whatisapanelisCANoeToolanditsUse? WhyCAPLscriptingisusedinCANoetool? IsitpossibletosimulateotherECUsExceptTestECUwithoutCAPLScriptinginCANoetool? whatispurposeofCCPprotocolwhichisalsousedinCANapetool? EmbeddedDevelopmentDocuments: Introduction_to_prog_embedded_systems(http://automotivetechis.les.wordpress.com/2012/06 /lecinto_to_prog_embedded_systems.pdf) youtubehttp://www.youtube.com/watch?v=sw3ADKPo1Uo&feature=player_detailpage%5D (http://www.youtube.com/watch?v=sw3ADKPo1Uo&feature=player_detailpage%5D)

PrateekDewangan JULY1,2013@3:38PM ImustSaythanksforthisarticel REPLY Vijaisankar JULY24,2013@6:54AM superbgenerallycovered.andtheperformanceofacandiadatedependsonhowhepresentsand hispastexperience.Thanksalot.

58 of 59

8/6/2013 4:17 PM

Automotive Interview Questions | AUTOMOTIVE BASICS

http://automotivetechis.wordpress.com/automotive-interview-questions/

REPLY pavan AUGUST2,2013@8:54AM trulygood Thanks. REPLY Sonali AUGUST2,2013@11:51AM Thankyouverymuchforthisarticalitisreallyhelpful. REPLY

BlogatWordPress.com.|TheiTheme2Theme. Follow

PoweredbyWordPress.com

59 of 59

8/6/2013 4:17 PM

You might also like