Академический Документы
Профессиональный Документы
Культура Документы
com/automotive-interview-questions/
CANINTERVIEWQUESTIONS:
1.WhatisCAN?
Answer:1.CANisamultimasterbroadcastserialbusstandardforconnectingelectroniccontrol
unit(ECUs).
2.Controllerareanetwork(CANorCANbus)isavehiclebusstandarddesignedtoallow
microcontrollersadevicestocommunicatewitheachotherwithinavehiclewithoutahostcomputer.
3.CANisamessagebasedprotocol,designedspecificallyforautomotiveapplicationsbutnowalso
usedinotherareassuchasindustrialautomationandmedicalequipment.
4.TheControllerAreaNetwork(CAN)busisaserialasynchronousbususedininstrumentation
applicationsforindustriessuchasautomobiles
2.CANframeworks?
Answer:SOF1Dominant
ArbitrationField11bitIdentifier,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
Errorframe012superpositionflags,8recessive(Delimiter)
Overloadframe012superpositionflags,8recessive(Delimiter)
3.WhyCANishaving120ohmsateachend?
Answer:Tominimizethereflectionreference,toreducenoise.Toensurethatreflectiondoesnot
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.Thefirsttimethere
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)andthetwomostsignificantbitsofeachmessageidentifier.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,firstnibbleissame,Mastersends7,slavesalsosends7themessagewith
moredominantbitswillgainthearbitration,lowestthemessageidentifierhigherthepriority.
10.StandardCANandExtendedCANdierence?
Answer:Numberofidentifierscanbeaccommodatedforstandardframeare2power11.
Numberofidentifiersmorecomparetobaseframe,forextendedframeare2power29.
IDEbit1forextendedframe.
IDEbit0forStandardframe.
11.Whatisbitstung?
Answer:CANusesaNonReturntoZeroprotocol,NRZ5,withbitstung.Theideabehindbit
stungistoprovideaguaranteededgeonthesignalsothereceivercanresynchronizewiththe
transmitterbeforeminorclockdiscrepanciesbetweenthetwonodescancauseaproblem.With
NRZ5thetransmittertransmitsatmostfiveconsecutivebitswiththesamevalue.Afterfivebitswith
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,notification,MessagefilteringandRecovery
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:TheJ1939standardhasdefinedamethodofcommunicatingmorethan8bytesofdataby
sendingthedatainpacketsasspecifiedintheTransportProtocol(TP).TherearetwotypesofTP,one
forbroadcastingthedata,andtheotherforsendingittoaspecificaddress.
DTCconsistsof4componentsSPN,FMI,OCandCM.
ADTCisacombinationoffourindependentfields:theSuspectParameterNumber(SPN)ofthe
channelorfeaturethatcanhavefaults;aFailureModeIdentifier(FMI)ofthespecificfault;the
occurrencecount(OC)oftheSPN/FMIcombination;andtheSPNconversionmethod(CM)which
tellsthereceivingmodehowtointerprettheSPN.Together,theSPN,FMI,OCandCMforma
numberthatadiagnostictoolcanusetounderstandthefailurethatisbeingreported.
(http://automotivetechis.files.wordpress.com/2012/06
/clip_image002.jpg)
Figure1Messageformat
19.WhatisKWP2000?
Answer:KWP2000(ISO14230)isaDiagnosticcommunicationsstandard.Specifiespossiblesystem
configurationsusingtheK&Llines.As91412butlimitedtothephysicalcharacteristics.Specifies
possiblesystemconfigurationsusingtheK&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.Whatismeantbyverificationandvalidation??
Answer:VerificationandValidation(V&V)istheprocessofcheckingthatasoftwaresystemmeets
specificationsandthatitfulfillsitsintendedpurpose.Itisnormallypartofthesoftwaretesting
processofaproject.
AccordingtotheCapabilityMaturityModel(CMMISWv1.1),
Verification:Theprocessofevaluatingsoftwaretodeterminewhethertheproductsofagiven
developmentphasesatisfytheconditionsimposedatthestartofthatphase.
Validation:Theprocessofevaluatingsoftwareduringorattheendofthedevelopmentprocessto
determinewhetheritsatisfiesspecifiedrequirements.
Verificationshowsconformancewithspecification;validationshowsthattheprogrammeetsthe
customersneeds
23.Canyouhavetwotransmittersusingthesameexactheaderfield?
Answer:Nothatwouldproduceabusconflict
Unlessyouhavemiddlewarethatensuresonlyonenodecantransmitatatime
Forexampleusealowprioritymessageasatokentoemulatetokenpassing
24.CANphysicallayervoltagelevels
(http://automotivetechis.files.wordpress.com/2012/06/can1.jpg)
25.CANbittiming:
AccordingtotheCANspecification,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.Eachsegmentconsistsofaspecific,programmablenumberoftimequanta(seeTable1).Thelength
ofthetimequantum(tq),whichisthebasictimeunitofthebittime,isdefinedbytheCAN
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)
defineshowfararesynchronizationmaymovetheSamplePointinsidethelimitsdefinedbythe
PhaseBuerSegmentstocompensateforedgephaseerrors.
(http://automotivetechis.files.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.WhathappenwhentwoCANnodesaresendingsameidentifieratasametime?
Twonodesonthenetworkarenotallowedtosendmessageswiththesameid.Iftwonodestryto
sendamessagewiththesameidatthesametimearbitrationwillnotwork.Instead,oneofthe
transmittingnodeswilldetectthathismessageisdistortedoutsideofthearbitrationfield.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.Afigureof2400bitspersecondmeans2400zerosoronescanbetransmitted
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.Whatisthedierencebetweendeclarationanddefinition?
Answer:Definitionmeanswhereavariableorfunctionisdefinedinrealityandactualmemoryis
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/
registerisusedtodefinelocalvariablesthatshouldbestoredinaregisterinsteadofRAMThis
meansthatthevariablehasamaximumsizeequaltotheregistersize(usuallyoneword)andcannot
havetheunary&operatorappliedtoit(asitdoesnothaveamemorylocation).
{
registerintMiles;
}
Registershouldonlybeusedforvariablesthatrequirequickaccesssuchascounters.Itshouldalso
benotedthatdefiningregistergoesnotmeanthatthevariablewillbestoredinaregister.Itmeans
thatitMIGHTbestoredinaregisterdependingonhardwareandimplementationrestrictions.
staticStorageClass
staticisthedefaultstorageclassforglobalvariables.Thetwovariablesbelow(countandroad)both
haveastaticstorageclass.
staticintCount;intRoad;main(){printf(%d\n,Count);printf(%d\n,Road);}
staticcanalsobedefinedwithinafunction.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
externdefinesaglobalvariablethatisvisabletoALLobjectmodules.Whenyouuseexternthe
variablecannotbeinitalizedasallitdoesispointthevariablenameatastoragelocationthathas
beenpreviouslydefined.
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.Herearesomeexamplesourcefiles.
3.Whatisinterrupt?
Answer:Interrupts(alsoknownastrapsorexceptionsinsomeprocessors)areatechniqueof
divertingtheprocessorfromtheexecutionofthecurrentprogramsothatitmaydealwithsome
eventthathasoccurred.Suchaneventmaybeanerrorfromaperipheral,orsimplythatanI/O
devicehasfinishedthelasttaskitwasgivenandisnowreadyforanother.Aninterruptisgenerated
inyourcomputereverytimeyoutypeakeyormovethemouse.Youcanthinkofitasahardware
generatedfunctioncall.
4.WhatisHardwareInterrupt?
Answer:TherearetwowaysoftellingwhenanI/Odevice(suchasaserialcontrolleroradisk
controller)isreadyforthenextsequenceofdatatobetransferred.Thefirstisbusywaitingorpolling,
wheretheprocessorcontinuouslychecksthedevicesstatusregisteruntilthedeviceisready.This
wastestheprocessorstimebutisthesimplesttoimplement.Forsometimecriticalapplications,
pollingcanreducethetimeittakesfortheprocessortorespondtoachangeofstateinaperipheral.
5.WhatisSoftwareInterrupt?
Answer:Asoftwareinterruptisgeneratedbyaninstruction.Itisthelowestpriorityinterruptandis
generallyusedbyprogramstorequestaservicetobeperformedbythesystemsoftware(operating
systemorfirmware).
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,executefileetc.
Thusasoftwareinterruptasitsnamesuggestsisdrivenbyasoftwareinstructionandahardware
interruptistheresultofexternalcauses.
6.WhatisInterruptlatency?Howdoyoumeasureinterruptlatency?Howtoreducetheinterrupt
latency?
Answer:Interruptlatencyisthetimebetweeninterruptrequestandexecutionoffirstinstructionof
theISR.
Weneedaoscilloscopeoralogicstateanalyzer.Byenteringtheinterruptserviceroutine(ISR),you
needtoactivateanavailableportonyourhardware(likealedportorsoon)anddeactivateitjust
beforereturningfromtheISR.Youcandothatbywritingtheappropriatecode.
Byconnectingoneinputoftheoscilloscope(orlogicstateanalyzer)totheINTRpinofthe
microprocessorandthesecondonetotheportyouactivate/deactivate,youcanmeasurethelatency
timeandthedurationoftheISR
Causesofinterruptlatencies
Thefirstdelayistypicallyinthehardware: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
(typicallyPCandflagregisters)onthestack.Ingeneral,modernCPUs(suchasARM)performa
modeswitch,whichrequireslessCPUcyclesthansavingregisters.
Pipelinefill:MostmodernCPUsarepipelined.Executionofaninstructionhappensinvarious
stagesofthepipeline.Aninstructionisexecutedwhenithasreacheditsfinalstageofthepipeline.
Sincethemodeswitchhasflushedthepipeline,afewextracyclesarerequiredtorefillthe
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,itisimpossibleforprogramcontentstobemodifiedbytheprogramitself.
ThevonneumannArchitectureisnamedafterthemathematicianandearlycomputerscientistJohn
vonNeumann.vonNeumannmachineshavesharedsignalsandmemoryforcodeanddata.Thus,
theprogramcanbeeasilymodifiedbyitselfsinceitisstoredinreadwritememory.
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,unifiedmemorysystemtogetherwithaHarvardarchitectureishighlyinecient.
Unlessitispossibletofeeddataintobothbusesatthesametime,itmightbebettertouseavon
Neumannarchitectureprocessor.
Useofcaches
Athigherclockspeeds,cachesareusefulasthememoryspeedisproportionallyslower.Harvard
architecturestendtobetargetedathigherperformancesystems,andsocachesarenearlyalways
usedinsuchsystems.
VonNeumannarchitecturesusuallyhaveasingleunifiedcache,whichstoresbothinstructionsand
data.Theproportionofeachinthecacheisvariable,whichmaybeagoodthing.Itwouldinprinciple
bepossibletohaveseparateinstructionanddatacaches,storingdataandinstructionsseparately.
Thisprobablywouldnotbeveryusefulasitwouldonlybepossibletoeveraccessonecacheata
time.
CachesforHarvardarchitecturesareveryuseful.Suchasystemwouldhaveseparatecachesforeach
bus.TryingtouseasharedcacheonaHarvardarchitecturewouldbeveryinecientsincethenonly
onebuscanbefedatatime.Havingtwocachesmeansitispossibletofeedbothbuses
simultaneously.exactlywhatisnecessaryforaHarvardarchitecture.
Thisalsoallowstohaveaverysimpleunifiedmemorysystem,usingthesameaddressspaceforboth
instructionsanddata.Thisgetsaroundtheproblemofliteralpoolsandselfmodifyingcode.Whatit
doesmean,however,isthatwhenstartingwithemptycaches,itisnecessarytofetchinstructionsand
datafromthesinglememorysystem,atthesametime.Obviously,twomemoryaccessesareneeded
thereforebeforethecorehasallthedataneeded.Thisperformancewillbenobetterthanavon
Neumannarchitecture.However,asthecachesfillup,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,whichfindstheproductoftwo
operandslocatedwithintheregisters,andSTORE,whichmovesdatafromaregistertothe
memorybanks.
Atfirst,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 RISC
Emphasisonhardware Emphasisonsoftware
Includesmulticlock Singleclock,
complexinstructions reducedinstructiononly
Memorytomemory: Registertoregister:
LOADandSTORE LOADandSTORE
incorporatedininstructions areindependentinstructions
Smallcodesizes, Lowcyclespersecond,
highcyclespersecond largecodesizes
Transistorsusedforstoring Spendsmoretransistors
complexinstructions onmemoryregisters
CISC RISC
Complexinstructionsrequiremultiplecycles Reducedinstructionstake1
cycle
Manyinstructionscanreferencememory OnlyLoadandStore
instructionscanreference
memory
Instructionsareexecutedoneatatime Usespipeliningtoexecute
instructions
Fewgeneralregisters Manygeneralregisters
9.Whatarethestartupcodesteps?
Answer:
1. Disablealltheinterrupts.
2. CopyandinitializeddatafromROMtoRAM.
3. Zerotheuninitializeddataarea.
4. Allocatespaceandforinitializethestack.
5. Initializetheprocessorstackpointer
6. 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(createdandmodifiedbytheuser.loadadditionaldevicedriversforperipheral
devices),COMMAND.COM(ItiscommandinterpreterIttranslatesthecommandsenteredby
theuser.ItalsocontainsinternalDOScommands.ItexecutesandAUTOEXEC.BAT),
AUTOEXEC.BAT(Itcontainsallthecommandsthattheuserwantswhichareexecuted
automaticallyeverytimethecomputedisstarted).
11.WhatLittleEndianandBigEndian?HowcanIdeterminewhetheramachinesbyteorderis
bigendianorlittleendian?Howcanweconvertfromonetoanother?
Firstofall,DoyouknowwhatLittleEndianandBigEndianmean?
LittleEndianmeansthatthelowerorderbyteofthenumberisstoredinmemoryatthelowest
address,andthehigherorderbyteisstoredatthehighestaddress.Thatis,thelittleendcomesfirst.
Forexample,a4byte,32bitintegerByte3Byte2Byte1Byte0willbearrangedinmemoryas
follows:Base_Address+0Byte0
Base_Address+1Byte1
Base_Address+2Byte2
Base_Address+3Byte3IntelprocessorsuseLittleEndianbyteorder.BigEndianmeansthatthe
higherorderbyteofthenumberisstoredinmemoryatthelowestaddress,andthelowerorderbyte
atthehighestaddress.Thebigendcomesfirst.Base_Address+0Byte3
Base_Address+1Byte2
Base_Address+2Byte1
Base_Address+3Byte0Motorola,SolarisprocessorsuseBigEndianbyteorder.InLittleEndian
form,codewhichpicksupa1,2,4,orlongerbytenumberproceedinthesamewayforallformats.
Theyfirstpickupthelowestorderbyteatoset0andproceedfromthere.Also,becauseofthe1:1
relationshipbetweenaddressosetandbytenumber(oset0isbyte0),multipleprecision
mathematicroutinesareeasytocode.InBigEndianform,sincethehighorderbytecomesfirst,the
codecantestwhetherthenumberispositiveornegativebylookingatthebyteatosetzero.Itsnot
requiredtoknowhowlongthenumberis,nordoesthecodehavetoskipoveranybytestofindthe
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.Programtofindifamachineisbigendianorlittleendian?
01 #include"stdio.h"
02 #defineBIG_ENDIAN0
03 #defineLITTLE_ENDIAN1
04 intmain()
05 {
06 intvalue;
07 value=endian();
08 if(value==1)
09 printf("Machineislittleendian\n",value);
10 else
11 printf("MachineisBigEndian\n",value);
12 }
13 intendian(){
14 shortintword=0x0001;
15 char*byte=(char*)&word;
16 return(byte[0]?LITTLE_ENDIAN:BIG_ENDIAN);
17 }
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.Writeaprogramtofinduniquenumbersinanarray?
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 /*CprogramtoprintEquilateralTriangle*/
02 #include<stdio.h>
03 main()
04 {
05 inti,j,k,n;
06
07 printf("Enternumberofrowsofthetriangle\n");
08 scanf("%d",&n);
09
10 for(i=1;i<=n;i++)
11 {
12 for(j=1;j<=ni;j++)
13 {
14 printf("");
15 }
16 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 printf("i");
19 }
20 printf("\n");
21 }
22 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;
}
intfind(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()
{
/*startalwayspointstothefirstnodeofthelinkedlist.
tempisusedtopointtothelastnodeofthelinkedlist.*/
node*start,*temp;
start=(node*)malloc(sizeof(node));
temp=start;
temp>next=NULL;
/*Hereinthiscode,wetakethefirstnodeasadummynode.
Thefirstnodedoesnotcontaindata,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=find(start,data);
if(status)
{
printf(ElementFound\n);
}
else
{
printf(ElementNotFound\n);}
}
}}
18.Canavariablebebothconstandvolatile?Yes.Theconstmodifiermeansthatthiscodecannot
changethevalueofthevariable,butthatdoesnotmeanthatthevaluecannotbechangedbymeans
outsidethiscode.Forinstance,intheexampleinFAQ8,thetimerstructurewasaccessedthrougha
volatileconstpointer.Thefunctionitselfdidnotchangethevalueofthetimer,soitwasdeclared
const.However,thevaluewaschangedbyhardwareonthecomputer,soitwasdeclaredvolatile.Ifa
variableisbothconstandvolatile,thetwomodifierscanappearineitherorder.
19.whatareConstantandVolatileQualifiers?
20 of 59 8/6/2013 4:17 PM
Automotive Interview Questions | AUTOMOTIVE BASICS http://automotivetechis.wordpress.com/automotive-interview-questions/
constisusedwithadatatypedeclarationordefinitiontospecifyanunchangingvalue
Examples:
constintfive=5;
constdoublepi=3.141593;
constobjectsmaynotbechanged
Thefollowingareillegal:
constintfive=5;
constdoublepi=3.141593;
pi=3.2;
five=6;
volatilespecifiesavariablewhosevaluemaybechangedbyprocessesoutsidethecurrent
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
declarationthatswhyconstandvolatilearecalledtypequalifiers,ratherthantypespecifiers.Here
areafewrepresentativeexamples:
volatilei;
volatileintj;
constlongq;
constvolatileunsignedlongintrt_clk;
struct{
constlongintli;
signedcharsc;
}volatilevs;
Dontbeputo;someofthemaredeliberatelycomplicated:whattheymeanwillbeexplainedlater.
Rememberthattheycouldalsobefurthercomplicatedbyintroducingstorageclassspecificationsas
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/
isnotmodifiable,soadataobjectthatisdeclaredwithconst asapartofitstypespecificationmust
notbeassignedtoinanywayduringtherunofaprogram.Itisverylikelythatthedefinitionofthe
objectwillcontainaninitializer(otherwise,sinceyoucantassigntoit,howwoulditevergeta
value?),butthisisnotalwaysthecase.Forexample,ifyouwereaccessingahardwareportatafixed
memoryaddressandpromisedonlytoreadfromit,thenitwouldbedeclaredtobeconstbutnot
initialized.
Takingtheaddressofadataobjectofatypewhichisntconstandputtingitintoapointerto
theconstqualifiedversionofthesametypeisbothsafeandexplicitlypermitted;youwillbeableto
usethepointertoinspecttheobject,butnotmodifyit.Puttingtheaddressofaconsttypeintoa
pointertotheunqualifiedtypeismuchmoredangerousandconsequentlyprohibited(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.Thisisanerrorinyourprogramandresultsinundefined
behaviour.
Themainintentionofintroducingconstobjectswastoallowthemtobeputintoreadonlystore,and
topermitcompilerstodoextraconsistencycheckinginaprogram.Unlessyoudefeattheintentby
doingnaughtythingswithpointers,acompilerisabletocheckthatconstobjectsarenotmodified
explicitlybytheuser.
Aninterestingextrafeaturepopsupnow.Whatdoesthismean?
charc;
char*constcp=&c;
Itssimplereally;cpisapointertoachar,whichisexactlywhatitwouldbeiftheconstwerent
there.Theconstmeansthatcpisnottobemodified,althoughwhateveritpointstocanbethe
pointerisconstant,notthethingthatitpointsto.Theotherwayroundis
constchar*cp;
whichmeansthatnowcpisanordinary,modifiablepointer,butthethingthatitpointstomustnot
bemodified.So,dependingonwhatyouchoosetodo,boththepointerandthethingitpointstomay
bemodifiableornot;justchoosetheappropriatedeclaration.
Afterconst,wetreatvolatile.Thereasonforhavingthistypequalifierismainlytodowiththe
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
firstoneisthecontrolandstatusregister(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.Noticethattherearentactuallyanyobjectsofthattypedefined,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.
Usingsuchaderivedpointerresultsinundefinedbehaviour.
Ifanarray,unionorstructureisdeclaredwithconstorvolatileattributes,thenallofthemembers
takeonthatattributetoo.Thismakessensewhenyouthinkaboutithowcouldamemberof
aconststructurebemodifiable?
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,foranyobjectlikelytobesubjecttomodificationeitherbyhardwareorasynchronousinterrupt
serviceroutines,thevolatiletypequalifierisimportant.
Now,justwhenyouthoughtthatyouunderstoodallthat,herecomesthefinaltwist.Adeclaration
likethis:
volatilestructdevregs{
/*stuff*/
}v_decl;
declaresthetypestructdevregsandalsoavolatilequalifiedobjectofthattype,calledv_decl.
Alaterdeclarationlikethis
structdevregsnv_decl;
declaresnv_declwhichisnotqualifiedwithvolatile!Thequalificationisnotpartofthetype
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/
Ifyoudowanttogetashorthandwayofattachingaqualifiertoanothertype,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
describedfirst,andtheportionthatchangesisdescribedbytheunion.Theideaofaunioncouldbe
handledinadierentwaybyhaving2dierentstructsdefined,andmakingapointertoeachkindof
struct.Thepointertostructacouldbeassignedtothevalueofabuer,andthepointertostruct
bcouldbeassignedtothesamebuer,butnowa>somefieldandb>someotherfieldareboth
locatedinthesamebuer.Thatistheideabehindaunion.Itgivesdierentwaystobreakdownthe
samebuerarea.
Thedierencebetweenstructureandunionare:1.unionallocatesthememoryequaltothe
maximummemoryrequiredbythememberoftheunionbutstructureallocatesthememoryequalto
thetotalmemoryrequiredbythemembers.2.Inunion,oneblockisusedbyallthememberofthe
unionbutincaseofstructure,eachmemberhavetheirownmemoryspace
DierenceBetweenStuctureandUnion:
Structure Union
i.AccessMembers
Wecanaccessallthemembersofstructureat Onlyonememberofunioncanbeaccessedat
anytime. anytime.
ii.MemoryAllocation
Memoryisallocatedforallvariables. Allocatesmemoryforvariablewhichvariable
requiremorememory.
iii.Initialization
Allmembersofstructurecanbeinitialized Onlythefirstmemberofaunioncanbe
initialized.
iv.Keyword
29 of 59 8/6/2013 4:17 PM
Automotive Interview Questions | AUTOMOTIVE BASICS http://automotivetechis.wordpress.com/automotive-interview-questions/
structkeywordisusedtodeclarestructure. unionkeywordisusedtodeclareunion.
v.Syntax
structstruct_name unionunion_name
{ {
structureelement1; unionelement1;
structureelement2; unionelement2;
structureelementn; unionelementn;
}struct_var_nm; }union_var_nm;
vi.Example
structitem_mst unionitem_mst
{ {
intrno; intrno;
charnm[50]; charnm[50];
}it; }it;
Whilestructureenablesustreatanumberofdierentvariablesstoredatdierentinmemory,a
unionenablesustotreatthesamespaceinmemoryasanumberofdierentvariables.Thatisa
Unionoersawayforasectionofmemorytobetreatedasavariableofonetypeononeoccasion
andasadierentvariableofadierenttypeonanotheroccasion.
Thereisfrequentrequirementwhileinteractingwithhardwaretoaccessaccessabyteorgroupof
bytessimultaneouslyandsometimeseachbyteindividually.Usuallyunionistheanswer.
=======DierenceWithexample=======
Letssayastructurecontaininganint,charandfloatiscreatedandaunioncontainingintcharfloat
aredeclared.
structTT{inta;floatb;charc;}UnionUU{inta;floatb;charc;}
sizeofTT(struct)wouldbe>9bytes(compilerdependentifint,float,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>pwithoutinvokingundefinedbehavior.)
Trythefollowingprogram.(Yes,Iknowitinvokestheabovementionedundefinedbehavior,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,whichcanbepredefineddatatypesorotherstructure.
Thelength/sizeofthestructureisthesumofthelengthofitselements.
InC,structurescannotcontainfunctions.inC++itcan.
Union:Unionisacombinationelements,whichcanbepredefineddatatypesorotherunion.But,the
size/lengthofunionisthemaximumofinternalelements.
thesizeof()operatorreturnsthesizeslightlymorethancalculatedsizeduetopadding,whichagain
dependsonOS
==Answer==Unionallocatesthememoryequaltothemaximummemoryrequiredbythemember
oftheunionbutstructureallocatesthememoryequaltothetotalmemoryrequiredbythemembers.
Inunion,oneblockisusedbyallthememberoftheunionbutincaseofstructure,eachmemberhave
theirownmemoryspace.
21.Whatismeantbystructurepadding?
Answer:compilerspadstructurestooptimizedatatransfers.Thisisanhardwarearchitectureissue.
MostmodernCPUsperformbestwhenfundamentaltypes,likeintorfloat,arealignedonmemory
boundariesofaparticularsize(eg.oftena4bytewordon32bitarchs).Manyarchitecturesdontallow
misalignedaccessoriftheydoinoccuraperformancepenality.Whenacompilerprocessesa
structuredeclarationitwilladdextrabytesbetweenfieldstomeetalignmentneeds.
Mostprocessorsrequirespecificmemoryalignmentonvariablescertaintypes.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(orbitsifbitfieldsareinuse)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.
ThefirsttechniquecomesfromtheCprogramminglanguage.Constantsmaybedefinedusingthe
preprocessordirective,#defineThepreprocessorisaprogramthatmodifiesyoursourcefilepriorto
compilation.Commonpreprocessordirectivesare#include,whichisusedto
includeadditionalcodeintoyoursourcefile,#define,whichisusedtodefineaconstantand
#if/#endif,whichcanbeusedtoconditionallydeterminewhichpartsofyourcodewillbecompiled.
The#definedirectiveisusedasfollows.
#definepi3.1415#defineid_no12345
Wherevertheconstantappearsinyoursourcefile,thepreprocessorreplacesitbyitsvalue.So,for
instance,everypiinyoursourcecodewillbereplaceby3.1415.Thecompilerwillonlyseethe
value3.1415inyourcode,notpi.Theproblemwiththistechniqueisthatthereplacementisdone
lexically,withoutanytypechecking,withoutanyboundcheckingandwithoutanyscopechecking.
Everypiisjustreplacedbyitsvalue.Thetechniqueisoutdated,existstosupportlegacycodeand
shouldbeavoided.
Const
Thesecondtechniqueistousethekeywordconstwhendefiningavariable.Whenusedthecompiler
willcatchattemptstomodifyvariablesthathavebeendeclaredconst.
constfloatpi=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/
Therearetwomainadvantagesoverthefirsttechnique.
First,thetypeoftheconstantisdefined.piisfloat.id_noisint.Thisallowssometypechecking
bythecompiler.
Second,theseconstantsarevariableswithadefinitescope.Thescopeofavariablerelatestopartsof
yourprograminwhichitisdefined.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?Whatarethebenefits?
TheVmodelrepresentsasoftwaredevelopmentprocess(alsoapplicabletohardwaredevelopment)
whichmaybeconsideredanextensionofthewaterfallmodel.Insteadofmovingdowninalinear
way,theprocessstepsarebentupwardsafterthecodingphase,toformthetypicalVshape.The
VModeldemonstratestherelationshipsbetweeneachphaseofthedevelopmentlifecycleandits
associatedphaseoftesting.
TheVmodelhasanumberofbenefits:
1.Systemsdevelopmentprojectsusuallyhaveatestapproach,orteststrategydocument,which
defineshowtestingwillbeperformedthroughoutthelifecycleoftheproject.TheVmodelprovidesa
consistentbasisandstandardforpartofthatstrategy.
2.TheVmodelexplicitlysuggeststhattesting(qualityassurance)shouldbeconsideredearlyonin
thelifeofaproject.Testingandfixingcanbedoneatanystageinthelifecycle.However,thecostof
findingandfixingfaultsincreasesdramaticallyasdevelopmentprogresses.Evidencesuggeststhatif
afaultuncoveredduringdesigncosts1.0monetaryunittocorrect,thenthesamefaultuncoveredjust
beforetestingwillcost6.5units,duringtesting15units,andafterreleasebetween60and100units.
Theneedtofindfaultsassoonaspossiblereinforcestheneedforthequalityassuranceofdocuments
suchastherequirementsspecificationandthefunctionalspecification.Thisisperformedusingstatic
testingtechniquessuchasinspectionsandwalkthroughs.
3.Itintroducestheideaofspecifyingtestrequirementsandexpectedoutcomespriortoperforming
theactualtests.Forexample,theacceptancetestsareperformedagainstaspecificationof
requirements,ratherthanagainstsomecriteriadreamedupwhentheacceptancestagehasbeen
reached
4.TheVmodelprovidesafocusfordefiningthetestingthatmusttakeplacewithineachstage.The
definitionoftestingisassistedbytheideaofentryandexitcriteria.Hence,themodelcanbeusedto
definethestateadeliverablemustbeinbeforeitcanenterandleaveeachstage.Theexitcriteriaof
onestageareusuallytheentrycriteriaofthenext.Inmanyorganizations,thereisconcernaboutthe
qualityoftheprogramcodereleasedbyindividualprogrammers.Someprogrammersreleasecode
thatappearstobefaultfree,whileothersreleasecodethatstillhasmanyfaultsinit.Theproblemof
programmersreleasingcodewithdierentlevelsofrobustnesswouldbeaddressedintheexit
criteriaofunitdesignandunittesting.Unitdesignwouldrequireprogrammerstospecifytheir
intendedtestcasesbeforetheywroteanyprogramcode.Codingcouldnotbeginuntilthesetestcases
hadbeenagreedwithanappropriatemanager.Second,thetestcaseswouldhavetobeconducted
successfullybeforetheprogramcouldleavetheunitteststageandbereleasedtointegrationtesting.
5.Finally,theVmodelprovidesabasisfordefiningwhoisresponsibleforperformingthetestingat
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
specificationormissingrequirement.
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.
Equivalencepartitioning BasisPathTesting
Boundaryvalueanalysis FlowGraphNotation
Errorguessing ControlStructureTesting
38 of 59 8/6/2013 4:17 PM
Automotive Interview Questions | AUTOMOTIVE BASICS http://automotivetechis.wordpress.com/automotive-interview-questions/
Raceconditions 1.ConditionTesting
Causeeectgraphing
Syntaxtesting 2.DataFlowtesting
Statetransitiontesting
LoopTesting
Graphmatrix
1.SimpleLoops
2.NestedLoops
3.ConcatenatedLoops
4.UnstructuredLoops
3 Testercanbenontechnical Testershouldbetechnical
4 Helpstoidentifythevaguenessand Helpstoidentifythelogicaland
contradictioninfunctional codingissues.
specifications
26.Whatarethetypesoftestings?
unittesting
Componenttesting
Integrationtesting
Systemtesting
27.TheDierencebetweenBitRateandBaudRate?
ThedierencebetweenBitandBaudrateiscomplicatedandintertwining.Botharedependentand
interrelated.ButthesimplestexplanationisthataBitRateishowmanydatabitsaretransmittedper
second.AbaudRateisthenumberoftimespersecondasignalinacommunicationschannel
changes.
Bitratesmeasurethenumberofdatabits(thatis0sand1s)transmittedinonesecondina
communicationchannel.Afigureof2400bitspersecondmeans2400zerosoronescanbetransmitted
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)DierencebetweenflashandEEprom
1. Similarities
BothflashandEEPROMaredigitalstoragemethodsusedbycomputersandotherdevices.Both
arenonvolatileROMtechnologiestowhichyoucanwriteandfromwhichyoucanerasemultiple
times.
Dierences
TheprimarydierencebetweenflashandEEPROMisthewaytheyerasedata.WhileEEPROM
destroystheindividualbytesofmemoryusedtostoredata,flashdevicescanonlyerasememory
inlargerblocks.Thismakesflashdevicesfasteratrewriting,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:staticfunctionsarefunctionsthatareonlyvisibletootherfunctionsinthesamefile
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,definition&initialization?
Ans:Adeclarationintroducesanameanidentifiertothecompiler.IttellsthecompilerThis
functionorthisvariableexistssomewhere,andhereiswhatitshouldlooklike.
41 of 59 8/6/2013 4:17 PM
Automotive Interview Questions | AUTOMOTIVE BASICS http://automotivetechis.wordpress.com/automotive-interview-questions/
Adefinition,ontheotherhand,says:MakethisvariablehereorMakethisfunction here.It
allocatesstorageforthename.Thismeaningworkswhether
youretalkingaboutavariableorafunction;ineithercase,atthepointofdefinitionthecompiler
allocatesstorage.
externconstintx=1;/*Initialization*/
Thisinitializationestablishesthisasadefinition,notadeclaration.
externconstintx;/*Declaration*/
ThisdeclarationinC++meansthatthedefinitionexistselsewhere.
32.Whatisthedierencebetweenpassbyvaluebyreferenceincandpassbyreferenceinc?
PassByReference:
InPassbyreferenceaddressofthevariableispassedtoafunction.Whateverchangesmadetotheformal
parameterwillaecttotheactualparameters
Samememorylocationisusedforbothvariables.(FormalandActual)
itisusefulwhenyourequiredtoreturnmorethen1values
PassByValue:
Inthismethodvalueofthevariableispassed.Changesmadetoformalwillnotaecttheactualparameters.
Dierentmemorylocationswillbecreatedforbothvariables.
Heretherewillbetemporaryvariablecreatedinthefunctionstackwhichdoesnotaecttheoriginalvariable.
33.Whatisthedierencebetweenflashmemory,EPROMandEEPROM?
EEPROMisanolder,morereliabletechnology.ItissomewhatslowerthanFlash.FlashandEEPROM
areverysimilar,butthereisasubtledierence.FlashandEEPROMbothusequantumcellstotrap
electons.Eachcellrepresentsonebitofdata.Thepresenceorabsenceofelectonsinacellindicates
whetherthebitisa1or0.Thecellshaveafinitelifeeverytimeacelliserased,itwearsoutalittle
bit.InEEPROM,cellsareerasedonebyone.Theonlycellserasedarethosewhichare1butneedto
bezero.(Writinga1toacellthats0causesverylittlewear,IIRC)InFlash,alargeblockiserasedall
atonce.Insomedevices,thisblockistheentiredevice.Soinflash,cellsareerasedwhetherthey
needitornot.Thiscutsdownonthelifespanofthedevice,butismuch,muchfasterthanthe
EEPROMmethodofgoingcellbycell.
Erasuremethod:BothFlashandEEPROMerasecellsbymeansofanelectricfield.Ithinkitis
highfrequencyandpopstheelectronsoutoftheOthersimilardevicesareEPROM(sometimes
UVEPROM)andOTPROM(sometimesPROM).EPROM/UVEPROMlacksthestructuresthat
generatetheelectricalfieldforerasure.Thesedeviceshaveawindowontop,usuallycoveredbya
papersticker.Toerase,thestickerisremovedandthedeviceisexposedtointenseultravioletlightfor
3045minutes.TheonlydierencebetweenOTPROMandUVEPROMisthatOTPROMlackstheUV
windowthereisnowaytoerasethedata.AddingtheUVwindowtothedevicepackage
significantlyincreasescost,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.ForexampleifPROMwasusedforfirmwarethatneededupgradedevery6monthsor
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),flashmemory,
mosttypesofmagneticcomputerstoragedevices(e.g.harddisks,floppydiscsandmagnetictape),
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.
Thetermreentrantisusedtorefertosidewallprofilesofthenozzles,whereinexitdiametersofthe
nozzlesaresmallerthanentrancediametersofthenozzlessothatthesidewallsofthenozzlesarenot
perpendiculartoaplanedefinedbyanexitsurfaceofthenozzlemember.
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?
Globalvariablesarevariablesdefinedoutsideofanyfunction.Theirscopestartsatthepointwhere
theyaredefinedandlaststotheendofthefile.Theyhaveexternallinkage,whichmeansthatinother
sourcefiles,thesamenamereferstothesamelocationinmemory.
Staticglobalvariablesareprivatetothesourcefilewheretheyaredefinedanddonotconflictwith
othervariablesinothersourcefileswhichwouldhavethesamename.
40.HowtoaccessaGlobalvariablesinotherfiles?
Variablesdeclaredoutsideofablockarecalledglobalvariables.Globalvariableshaveprogram
scope,whichmeanstheycanbeaccessedeverywhereintheprogram,andtheyareonlydestroyed
whentheprogramends.
Hereisanexampleofdeclaringaglobalvariable:
1 intg_nX;//globalvariable
2
3 intmain()
4 {
5 intnY;//localvariablenY
6
7
8 //globalvarscanbeseeneverywhereinprogram
9 //sowecanchangetheirvalueshere
10
g_nX=5;
}//nYisdestroyedhere
Becauseglobalvariableshaveprogramscope,theycanbeusedacrossmultiplefiles.Inthesectionon
programswithmultiplefiles,youlearnedthatinordertouseafunctiondeclaredinanotherfile,you
havetouseaforwarddeclaration,oraheaderfile.
Similarly,inordertouseaglobalvariablethathasbeendeclaredinanotherfile,youhavetousea
forwarddeclarationoraheaderfile,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 //declarationofg_nValue
2 intg_nValue=5;
main.cpp:
1 //externtellsthecompilerthisvariableisdeclaredelsewhere
2 externintg_nValue;
3
4
5 intmain()
6 {
7 g_nValue=7;
8 return0;
}
Hereisanexampleofusingaheaderfileextern:
global.cpp:
1 //declarationofg_nValue
2 intg_nValue=5;
global.h:
1 #ifndefGLOBAL_H//headerguards
2 #defineGLOBAL_H
3
4 //externtellsthecompilerthisvariableisdeclaredelsewhere
5
6 externintg_nValue;
7
#endif
main.cpp:
1 #include"global.h"
2 intmain()
3 {
4 g_nValue=7;
5 return0;
6
}
Generallyspeaking,ifaglobalvariableisgoingtobeusedinmorethan2files,itsbettertousethe
headerfileapproach.Someprogrammersplaceallofaprogramsglobalvariablesinafilecalled
globals.cpp,andcreateaheaderfilenamedglobals.htobeincludedbyother.cppfilesthatneedto
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 intnValue=5;
2
3 intmain()
4 {
5 intnValue=7;//hidestheglobalnValuevariable
6
7 nValue++;//incrementslocalnValue,notglobalnValue
8 ::nValue;//decrementsglobalnValue,notlocalnValue
9 return0;
}//localnValueisdestroyed
However,havinglocalvariableswiththesamenameasglobalvariablesisusuallyarecipefor
trouble,andshouldbeavoidedwheneverpossible.UsingHungarianNotation,itiscommonto
declareglobalvariableswithag_prefix.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
lineofeverysinglefile!Inacomputerprogramwithhundredsoffilesandmillionsoflinesofcode,
youcanimaginehowlongthiswouldtake!
Second,globalvariablesaredangerousbecausetheirvaluescanbechangedbyanyfunctionthatis
called,andthereisnoeasywayfortheprogrammertoknowthatthiswillhappen.Considerthe
followingprogram:
1 //declareglobalvariable
2 intg_nMode=1;
3
4
5 voiddoSomething()
6 {
7 g_nMode=2;
8 }
9
10 intmain()
11 {
12
47 of 59 8/6/2013 4:17 PM
Automotive Interview Questions | AUTOMOTIVE BASICS http://automotivetechis.wordpress.com/automotive-interview-questions/
13 g_nMode=1;
14
15
doSomething();
16
17
18 //Programmerexpectsg_nModetobe1
19
//ButdoSomethingchangeditto2!
20
21
22 if(g_nMode==1)
23 cout<<"Nothreatdetected."<<endl;
24
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,watchdogtimerensuresthatifthefirstwatchdogtimerdoesnotreport
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.files.wordpress.com/2012/06
/untitled4.jpg)
43.Whatisthedierencebetween8bit16bitand32bitprocessor?
Dierentfamiliesofmicrosvaryintheircapabilities.Thenumberofbitsjustreferstothewidthofthe
datapipe,whichlimitstheprecisionofmath,althoughmanymicroswilleitheremulatehigherorder
mathorhavespecialHWthatcanperformhigherprecisionmathfunctions.
Thehistoricdierencehasbeenprice:8bitwascheapest,32bitwasexpensive.Thisisstilltruein
generally,butthepriceof16bitpartshavecomedownsignificantly.
Most8bitprocessorsareoldandrunonoldarchitectures,sotheytendtobeslower.Theyarealso
mademorecheaply,sincethatiswherethecompetitionisatthe8bitpoint,andthismakesthem
tendtowardsslowness.TheyalsotendtohavealowlimitonsupportedRAM/otherstorage,butthe
actualamountdependsonthefamily.
16bitprocessorstendtofocusonpriceaswell,butthereisalargerangeofpartsavailable,someof
whichhavefairlyhighperformanceandlargeamountsofonchipperipherals.Thesepartsusually
performfasterthan8bitpartsonmathwheretheprecisionisgreaterthan8bits,andtendtohave
moreaddressablememory.
32bitchipscompeteprimarilyonperformanceforanapplication.Thereisaconsiderablerangeof
32bitpartsavailable,eachtargetedatsomespecificapplication.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/
Typedefisusedtocreateanewnametoanalreadyexistingdatatype.Redefinethenamecreates
conflictwiththepreviousdeclaration.
eg:
typedefunsignedintUINT32
Macros[#define]isadirectsubstitutionofthetextbeforecomplingthewholecode.Inthegiven
example,itsjustatextualsubstitution.wherethereisaposibilityofredefiningthemacro
eg:
#definechPointerchar*
#undefchPointer
#definechPointerint*
Typedefareusedfordeclarationswhencomparewithmacro
typedefscancorrectlyencodepointertypes.whereas#DEFINESarejustreplacementsdonebythe
preprocessor.
Forexample,
1. typedefchar*String_t;
2. #defineString_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,
andfinallythefunctionreturnsavaluethatisassignedtoavariable(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)Afterinliningcompilercanalsoapplyintraproceduraloptmizationifspecified.Thisisthemost
importantone,inthiswaycompilercannowfocusondeadcodeelimination,cangivemorestresson
branchprediction,inductionvariableeliminationetc..
Disadvantages:
1)Mayincreasefunctionsizesothatitmaynotfitonthecache,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)Ifusedinheaderfile,itwillmakeyourheaderfilesizelargeandmayalsomakeitunreadable.
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
NotethatifFIRSTisdefined(whichitisintheabove)thevaluesofa,bandcarehardcodedtovalues
of2,6and4.Thiscansavealotoftimewhendevelopingsoftwareasitavoidstediouslytyping
everythingineachandeverytimeyourunyourroutine.WhenFIRSTisdefined,allthatispassedto
thecompileristhecodebetweenthe#ifdefandthe#else.Thecodebetweenthe#elseandthe#endifis
notseenbythecompiler.Itisasifitwereallacomment.
Onceyouhaveyourroutineworking,anddesiretoinserttheprintfandscanfs,allthatisrequiredis
togobackanddeletethethe#defineFIRST.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.InformationstoredonRSflipflops
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).TheIGblockcombinestheconfigurationwindowsoftheGenerator
blockintoonewindow;therefore,everythingcanbesetupinonespot.Inaddition,changescanbe
madewiththeIG.
WithoutCAPL,canwesimulatetheotherECUsCANMessagesexceptTestECUintheCAN
SimulationNetworkinCANoetoolwithoutusingIGorGblocks.
HowtochangethebaudrateinCANoewithoutchangingthecode?
Thebitratemaybechangedbyeitherchangingtheoscillatorfrequency,whichisusually
restrictedbytheprocessorrequirements,orbyspecifyingthelengthofthebitsegmentsintime
quantumandtheprescalervalue.
InCanoetool,wecanchangethebustimingregister0&1valuesforcorrectingthebaudrate.
InAutosar,wecanusepostbuildconfigurationforCANbaudratevalues.
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
Supportsreproducibletestrunsthatcanassistinuncoveringandtrackingdownhardtofind
problems.
Enablestestingwithlessriskofdestroyingthesystem
SIL:SILreferstothekindoftestingdonetovalidatethebehavioroftheCcodeusedinthe
controller.Thatcodecanbeautogeneratedfromthemodelusedinalgorithmdevelopment.
EmmeskayhasadeepunderstandingofSILtestingandautocodegenerationfromthemanySIL
projectswehaveperformedforourcustomers.
TestingandValidation
PlantmodeldevelopedinvehiclesimulationenvironmentisimportedtoSimulinkasalibrary.
Controlleristestedinloopwiththeplantfordierentroutesandspeedprofiles.
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
influencethebuslevels.AnErrorPassivetransmittercanstillinterruptitsownmessagebysendinga
passiveErrorFlag.Attention,ifoneReceiverisinerrorpassivemodenodataconsistencyis
guaranteedanymore.
Howtofindthebugincodeusingdebuggerifpointerispointingtoaillegalvalue?
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. SpiandI2Cdierence.?
2. WhatisUDSadvantages?
3. Whatiscrosscompiler
4. Unit/integration/alltestings.
5. Regressiontesting.
6. Testcasetypes.
7. Malloccalloc
8. FunctionpointersAdvantagewhereitisused?
HowmanycandatabasefilesarerequiredforCANNetworksimulationinCANoetool.
whatisthedierencebetweenCANalyzer,CANoeandCANapetools?
MentionthefewusesoftheCANoetool?
whatisapanelisCANoeToolanditsUse?
WhyCAPLscriptingisusedinCANoetool?
IsitpossibletosimulateotherECUsExceptTestECUwithoutCAPLScriptinginCANoetool?
whatispurposeofCCPprotocolwhichisalsousedinCANapetool?
EmbeddedDevelopmentDocuments:
Introduction_to_prog_embedded_systems(http://automotivetechis.files.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