interfacing to external devices - mitweb.mit.edu/6.111/www/f2016/handouts/l11_external.pdf · •...

Post on 21-Jul-2020

1 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

10/18/16

1

InterfacingtoExternalDevicesNotesand/orReference6.111October18,2016

HugeAmountofSelf-ContainedDevices

• Sensors• A-to-Dconverters• D-to-A• Memory• Microcontrollers• Etc…

• Weneedability/fluencytoextractinfofromandworkwiththem

10/18/16

2

CaseStudy

• 9axisIMU(InertialMeasurementUnit)• Accelerometer• Gyroscope• Magnetometer

• OneoftheonlyrealMEMS(MicroElectroMechanical Systems)applicationsthathasgonefull-scale(othersmightbeTI’sDMD,gyroscopes,microphones,somemicrofluidics,Siresonators,Piezoelectrics fromInkjets,etc…)

Accelerometers

• FirstMEMSaccelerometer:1979• Positionofaproofmassiscapacitively sensedanddecodedtoprovideaccelerationdata

Proof MassSpringSpring

MeasureCapacitanceviaImpedanceDivider𝑎" → Δ𝑑

SEMoftwo-axisaccelerometer

𝑑

10/18/16

3

UsesofAccelerationMeasurements:• Accelerationcanbeusedtodetectmotion• (pedometer,dropdetection):

• Usegravityandtrigtofindorientation:

𝜃' = tan,-𝑎"𝑎.

−𝑎"

−𝑎.

𝑔

𝑎1 = 𝑎.2 + 𝑎'2 + 𝑎"2�

Accelerometerdirections+X,+Y,+Z

Chip

Problems• Accelerometershavehugeamountsofhigh-frequencynoise• Tofix,usuallyLowPassFiltertherawsignal• ThiscutsdownonfrequencyresponsethoughL

𝜃'[𝑛] = 𝜃'[𝑛 − 1]𝛽+ 1 − 𝛽 tan,-𝑎"[𝑛 − 1]𝑎.[𝑛 − 1]

0 < 𝛽 < 1

𝜃' Angleestimatearoundyaxis

FilterCoefficient𝑎.𝑎"

Xacceleration

zacceleration

10/18/16

4

BringinGyroscopes

• ProvideDirectAngularVelocitywhichwecanintegratetogetangle• Verylittlehigh-frequencynoise,butlotsoflowfrequencynoise (Gyrosdriftlikecrazy)

Gyroreadingsare“around”theaxistheyreferto(useright-hand

rule):time(seconds)

angle(arb.units)

Angularv

elocity

(arb.units)

GyroOperationProof Mass

SpringSpring

MeasureCapacitanceviaImpedanceDivider

Resonating

MeasureCapacitancevia

ImpedanceDivider

RotationofDevice

• ResonatingProofMass• ElectrostaticDrive• PiezoelectricDrive

• Turningout-of-plane:• Proof-massfightsturn• Detectdeviationviacapacitance

• Dothisforallthreeaxes

Changesincapacitancemeasuredatdifferentpoints

Scalenotaccurate/nordesigndetails

10/18/16

5

• BecauseofDrift(lowfrequencynoise/offset)youwanttoavoiddoingmuchlong-termintegration• Havingbetalessthanunityensuresanyanglethatcomesfromgyroreadingwilleventuallydisappear,butinshorttermitwilldominate• Dependingontimestep:

HowtouseGyroReadings:

𝜃' 𝑛 = 𝛽𝜃' 𝑛 − 1 + 𝑇𝑔'[𝑛 − 1]

0 < 𝛽 < 1 FilterCoefficient

𝑇 TimeStep

𝑔' Gyroyreading

𝛽 ≈ 0.95 startingpoint

Whattodo?

• Usingonlyaccelerometer,leavesusblindtomotion/changeintheshorttermbutfineinthelong-term

• Usingonlygyroscope,leavesusblindinthelongterm,butgoodintheshortterm

• Whattodo?

10/18/16

6

Mergethesignals

• ComplementaryFilter:

• CouldalsodoKalman Filter(LQE)ifdesired(orothers)

𝜃' 𝑛 = 𝛽 𝜃' 𝑛 − 1 + 𝑇𝑔'[𝑛 − 1] + 1 − 𝛽 tan,-𝑎"[𝑛 − 1]𝑎.[𝑛 − 1]

0 < 𝛽 < 1 FilterCoefficient

𝑇 TimeStep

𝑔' Gyroyreading 𝑎.𝑎"

Xacceleration

zacceleration𝛽 ≈ 0.95goodstartingpoint

HowtogetAccesstothesignalsinfirstplace?

• Someaccelerometersareanalogout(canthereforereadthemwithanA-to-Dconverter)(ADXL335,forexample)• Thesehavelimitedfunctionality…andalsoitisanalogsothere’sthewholenoiseissue....whichisnotnice• Mostflavorsofsensorsaredigital

10/18/16

7

MPU-9250• 3-axisAccelerometer(16-bitreadings)• 3-axisGyroscope(16-bitreadings)• 3-axisMagneticHallEffectSensor(Compass)(16bitreadings)• SPIorI2Ccommunication(!)…noanalogout• On-chipFilters(programmable)• On-chipprogrammableoffsets• On-chipprogrammablescale!• On-chipsensorfusionpossible(withquaternionoutput)!• Interrupt-out(forlow-powerapplications!)• On-chipsensorfusionandothercalculations(candoorientationmathon-chiporpedometry even)• Socheaptheyusuallyaren’tevencounterfeited!J

Board:$8.00fromEbayChip:$5.00inbulk

CommonDevice-DeviceCommunicationProtocols

• Parallel(notsomuchanymore)

• Serial(UART)(stillcommoninsomecommunicationandGPSdevices)

• SPI(SerialPeripheralInterface)verycommon

• I2C(Inter-IntegratedCircuitCommunication)verycommon

10/18/16

8

Serial(UART)• StandsforUniversalAsynchronousReceiverTransmitter• Requiresagreementahead-of-timebetweendevicesregardingthingslikeclockrate(BAUD),etc…• Twowirecommunication• Cannotreallyshare

• (everypairofdevicesneedsownpairoflines)• Dataratereally<115.2Kbps

TX/RX

RX/TX

Device 1 Device 2

SPI

• StandsforSerial-PeripheralInterface• FourWires:

• MOSI:Master-Out-Slave-In• MISO:Master-In-Slave-Out• SCK:Clock• CE/CS(ChipEnableorChipSelect)

• SCKremovesneedtoagreeaheadoftimeondatarate(fromUART)• HighDataRates:(1MHzupto~70MHzclock(bits))

MOSIMISOMaster Slave

SCKCE0/CS0

10/18/16

9

SPI

• CanshareMOSI/MISOBus• Additionofmultipleslavesrequiresadditionalselectwires• Hardware/firmwareforSPIisprettyeasytoimplement:• Wiresareuni-directional• Classic“duh”sortofapproachtodigitalcommunication,butveryrobust.

MOSIMISOMaster Slave1

SCKCE0/CS0

Slave2

CE1/CS1

i2C

• StandsforInter-IntegratedCircuitcommunication• Inventedin1980s• TwoWire,OneforClock,onefordata(bothdirections)• Usually100kHzor400kHzclock(newerversionsgoto3.4MHz)

SDA

SCL

Master Slave

10/18/16

10

Oni2CMultipleDevicesRequireSame#ofWires

SDA

SCL

Master Slave1

Slave2

• DevicescomewiththeirownIDnumbers(originallya7bitvaluebutmoremodernoneshave10bits)…allowspotentiallyupto2^7devicesor2^10onabus(theoreticallyanyways)

• ID’sarespecifiedatbuild,usuallyseveraltochoosefromandyouselectthembypullingexternalpinsHIorLOW

Moretostory(needpull-upresistors)

4.7kΩ

3.3V

SDA

SCL

Master Slave1

3.3V

4.7kΩ

• i2Cusesanopendrain• MeaningbothMasterandSlaveareeither:• LOW• High-Impedance

• Needexternalpull-upresistors

10/18/16

11

Tri-State

• inout cannotbeareg ever,ever…itisclosertoawire...usualwaytoworkwiththemisthefollowing:

inout sda;

reg sda_val;

assign thing = sda_val? 1’bz: 1’b0;

Inverilog…

Asaresult:

Mode Master Slave

MasterTransmit HiZ (HI) orLOW HiZ (listening)

Slave ACK/NACK HiZ (listening) HiZ (HI)orLOW

SlaveTransmit HiZ (listening) HiZ (HI)orLOW

MasterACK/NACK HiZ (HI)orLOW HiZ (listening)

SDAin

VGS

4.7kΩ

3.3V

SDA

inout sda;reg sda_val;assign sda = sda_val? 1’bz: 1’b0;

Wanna writetoSDA?

sda_val <= 0; //or 1 if desired :wq

Wanna readtoSDA?

sda_val <= 1;//wait clock cycle…some_reg <= sda; //read from input

10/18/16

12

i2COperation

• DataisconveyedonSDA(EitherfromMasterorSlavedependingonpointduringcommunication)• SCLis50%dutycycle• SDAgenerallychangesonfallingedgeofSCL(isn’trequired)• SDAsampledatrisingedgeofSCL• MasterisinchargeofsettingSCLfrequencyanddrivingit

MeaningsI:(Start,Stop,Sampling)

SCL:

SDA:

MasterClaimsBus(START)BypullingSDALOWwhileSCLisHIIdleState

SDAandSCLsitHI

DatafromSDAsampled@posedge ofSCL

Data/StateonSDAtransitions@negedge ofSCL*

*notspecifiedbutprobablyeasiestspottodo

MasterReleasesBus(STOP)BypullingSDAHIwhileSCLisHI

HI

LO

HI

LO

10/18/16

13

MeaningsIIAddress

• FirstthingsentbyMasteris7bitaddress(10bitinmoremoderni2C…hassomeleading11111’sinit..don’t worryaboutthat)

• Ifadeviceonthebuspossessesthataddress,itacknowledges(ACK/NACK=0)anditbecomestheslave

• Allotherdevices(otherthanMaster/Slave)willignoreuntilSTOPsignalappearslateron.

MeaningsIII(Read/WriteBit)

• Aftersendingaddress,aRead/WriteBitisspecifiedbyMasteronSDA:• IfWrite(0)isspecified,thenextbytewillbearegistertowriteto,andfollowingbyteswillbeinformationtowriteintothatregister• IfRead(1)isspecified,theSlavewillstartsendingdataout,withtheMasteracknowledgingaftereverybyte(untilitwantsdatatonotbesentanymore)

10/18/16

14

MeaningsIV(ACK/NACK)

• Afterevery8bits,itisthelistener’sjobtoacknowledgeornotacknowledgethedatajustsent(calledanACK/NACK)• TransmitterpullsSDAHIandlistensfornextreading(@posedge ofSCL):• IfLOW,thenreceiveracknowledgesdata• IfremainsHI,noacknowledgement

• Transmitter/Receiveractaccordingly

MeaningsV• ForMastertowritetoSlave:

• START• SendDeviceAddress(withWritebit)• Sendregisteryouwanttowriteto• Senddata…untilyou’resatisfied• STOP

• ForMastertoreadfromSlave:• START• SendDeviceAddress(withWritebit)• Sendregisteryouwanttoreadfrom• ReSTART communication• SendDeviceAddress(WithReadbit)• Readinbits• Afterevery8bits,itisMaster’sjobtoacknowledgeSlave…continuedacknowledgementleadstocontinueddataoutbySlave.

• Not-Acknowledgesays“nomoredatatoSlave”• STOPleadstoMasterceasingallcommunication

10/18/16

15

Implementingi2ConFPGAwithMPU9250:• Mademasteri2CcontrollerinVerilog• UsedMPU9250Datasheet:42pages(basicfunctionality,timingrequirements,etc…)• MPU9250RegisterMap:55pages

State-MachineImplementationofi2CMaster

• Continuouslyreads2bytesstartingatthe0x3Bregister(Xaccelerometerdata)• PrintoutvalueinhexinLEDs• 34States• Clockedat200kHz,andcreates100kHzSCL• ChangeSDAonfallingedgeofSCL• SampleSDAonrisingedgeofSCL

10/18/16

16

State-MachineImplementationofi2CMaster• Redundantstates(repeatedREAD/WRITE,ADDRESS,ACK/NACK,etc…)

• ARMmanualdescribes~20stateFSM

• Includedcodeonsiteforreference/startingpoint

• Diagram:onnextpageforreference

…200morelines

IDLE START1ADDRESS1

ADDRESS2

READWRITE1

REGISTER1

REGISTER2

ACKNACK1A

ACKNACK1C

IDLE

ACKNACK2AACKNACK2C

IDLE

STOP

READ2

READ1

START2

ADDRESS3

ADDRESS4

READWRITE2

ACKNACK3A

ACKNACK3C

IDLE

READ3

READ4ACK4

NACK

NACK

ACK

NACK

ACK

NACKACK

7x

7x8x

8x

8x

10/18/16

17

CommunicationPart

1 0 1 1 0 1 0 0 0 0 0 0 0 1 1 1 0 1 1 0 1 0 0 1 1 0 1 0 0 0 1 0 0 1 1 0 1 1 1 0 0

01010101010101010101010101010101010101110101010101010101010101010101010101010

SDA

SCL

VCC

GND

Nexys4MPU9250

…SCL

SDA

CommunicationPart

1 0 1 1 0 1 0 0 0 0 0 0 0 1 1 1 0 1 1 0 1 0 0 1 1 0 1 0 0 0 1 0 0 1 1 0 1 1 1 0 0

01010101010101010101010101010101010101110101010101010101010101010101010101010

SDA

SCL

VCC

GND

Nexys4 MPU9250

DeviceAddress(0x68)Write=0

Acknowledge=0

DeviceRegister(0x3B)

Acknowledge=0

DeviceAddress(0x68)

Read=1

DataReadInStart

…SCL

SDA

ReStart

10/18/16

18

CommunicationPart

1 0 1 1 0 1 0 0 0 0 0 0 0 1 1 1 0 1 1 0 1 0 0 1 1 0 1 0 0 0 1 0 0 1 1 0 1 1 1 0 0

01010101010101010101010101010101010101110101010101010101010101010101010101010

SDA

SCL

VCC

GND

Nexys4 MPU9250

…SCL

SDA

“Iclaimthisbus”

“Hey,0x68…”

“Iwanna tellyousomething”

“I’mhere.Soundsgood”

“Lookatyour0x6Bregister”

“OK”

“Differentthought”

“Hey,0x68…”

“Readtomefromwhereyou’relooking”

“Forsure”

“0x6D”

”More,please”

MPU9250(Slave)DialogNexys4(Master)Dialog

CommunicationinReal-Life: DatabeingsentfromMPU9250

TriggeredonleavingIDLEstate

SCL=Purple

SDA=Yellow

10/18/16

19

Running andreadingXacceleration:

16’hFD88=16’b1111_1101_1000_1000(2’scomplement)Flipbitstogetmagnitude:16’b0000_0010_0111_0111=-315Full-scale(default+/- 2g)-315/(2**15)*2g=-0.02gJmakessense

16’h4088=16’b0100_0000_1000_1000(2’scomplement)Leavebitstogetmagnitude:16’b0100_0000_1000_1000=+16520Full-scale(default+/- 2g)-16520/(2**15)*2=+1.01gJmakessense!

Horizontal: Vertical:

HOOKUP

Clock-Stretching(Coolpartofi2C!!!)

SCL:

• NormallyMasterdrivesSCL,butsinceMasterdrivesSCLhighbygoinghiZ,itleavestheoptionopenforSlavetostepinandpreventSCLfromgoinghighbysettingSCLLOW

MasterwantedtopullSCLHIbutslavepreventsbygoingLOW

(redneverhappens)

OnceSlavegoesHiZ again,MasterpicksbackuponSCL

• AllowsSlaveawaytobuytime/slowdownthings(ifitrequiresmultipleclockcyclestoprocessincomingdataand/orgenerateoutput)

😻

10/18/16

20

FinalThoughts…WhataboutSPIorSerial?

• Ifyoucanimplementi2C,theothersareeasier.• SPIisalsoalittlelessstandardized• Generallywithcommunicationprotocols,themorewires,theeasiertheprotocol/lessoverhead• SPI(fourwires)• SerialTX/RX(littlebitmorecomplicated,butnottoobad)

• Checkouttheexamplei2Ccodefromthislecture…seeifyoucanaddclock-stretching!(notrequired)

top related