View
39
Download
0
Category
Preview:
Citation preview
RaspberryPiandInterfacing
Linux
PythonInterfaces
ThePoint
• Experimentso;enmeanmeasuringandrecordingdata– sense– digi<ze– communicate
– automate– store– analyze– publish– fameandglory?
Lecture4:Pi/Python/Interface UCSDPhys122 2
FocusonAccessible
• Oceansofpossibili<esfordataacquisi<on/interface• RaspberryPiis:
– cheap(youcanhaveyourown)– cheap(so;wareisfree)– cheap(low-costaccoutrements,likeADC)
• OtherRPibenefits:– familiarizeswithLinux&Python
• meansPicanrunveryadvanced/sophis<catedcode,ifneeded
– supportsloadsofmoderninterfaces• I2C,SPI,serial,GPIO,USB
– canplay“nice”withresearch-gradeinterfaces• telnet,ssh,othernetworkinterfaces
Lecture4:Pi/Python/Interface UCSDPhys122 3
Linux(Unix)Environment
• Command-lineinterface(terminalsession)• Willwanttofindandworkthroughtutorials• Essen<alcommands:
– cd(andmeaningof.,..),mkdir,ls(andls -l),cp,rm,mv,pwd,viornano,less,head,tail,cat,grep, wc(wordcount),|(pipe),>(stuffintofile),<(sourcefromfile),chmod,passwd,exit,etc.
– familiarizeyourselfwithatleastthese(andassociatedarguments/flags)
– use“man”(manual)pagesfordetails:• man mkdir
• MaccomputershaveUnixfounda<on,soprevalentOS
Lecture4:Pi/Python/Interface UCSDPhys122 4
RaspberryPiAccess
• Pi4unitsinlab;oneperbench;“headless”• Accessviasshorpuayonlabmachines• hostname:bench1,bench2,etc.• username:bench1,bench2,etc.(matchesunit/bench)
• password:bench1,bench2,etc.– temporary:suggestchanginga;eryou&partnerestablishyourbench(share/decidewithpartner)
– command:passwd
Lecture4:Pi/Python/Interface UCSDPhys122 5
PythonLanguage
• PrevalentinPhysics/Astro• Interpreted(slowerthancompiled)• Easysyntax(highlevel,readable)• Excep<onallygoodatstringparsing/handling• Librariesprovidepowerfulfunc<onality
– numpy:mathonvectors/arrays– scipy:specialfunc<ons,op<miza<on– matplotlib(pylab):plocng,alaMatLab– boatloadsofothers(manyincludedinstandardinstalla<on:math,sys,os,<me,re,asastart)
Lecture4:Pi/Python/Interface UCSDPhys122 6
PythonTutorials
• Findingyourownresources,learnhowto:– runinterac<velytoexploresyntax;usedir()andhelp()– uselists,tuples,dic<onaries;listcomprehension– performmath:import math;dir(math)– create/invoke/runprogram(nextslide)– controlflow:if/else;for/do/while– formatprintstatements:%s,%d,%5.2f,etc.– usecommandlinearguments:float(sys.argv[3]),e.g.– readfromfile:open();for line in file_handle;close()– writetofile:file_handle.write(formaaed_string)
• Example:Google:pythonlistcomprehensiontutorial
Lecture4:Pi/Python/Interface UCSDPhys122 7
ExamplePythonCrea<on/Execu<on
$ mkdir sandbox (create place to mess around)$ cd sandbox (navigate into directory)$ vi test.py (or edit using nano, emacs, etc)#!/usr/bin/env python #top line of file; invoke Pythonimport sys #so we can use command line arg.name = sys.argv[1] #not checking to verify exist.print “Hello, %s” % name #formats personalized output(save and quit)$ chmod +x test.py (do once: make file executable)$ ./test.py Tom (run with ./ and incl. argument)Hello, Tom (output)$ (prompt)
Lecture4:Pi/Python/Interface UCSDPhys122 8
Interfaces
• Amovingtarget,astechnologychanges– serial(RS-232),USB,I2C,SPIarecommon
• RaspberryPidoesthese,plusGPIO(Gen.Purp.Input/Output)– GPIB,CAMAC,VME/VXI,PCIcards(DAQ)forlabenviron.
Lecture4:Pi/Python/Interface UCSDPhys122 9
SerialCommunica<ons• MostPCshaveaDB9maleplug
forRS-232serialasynchronouscommunica<ons– we’llgettothesedefini<ons
later– o;enCOM1onaPC
• Inmostcases,itissufficienttousea2-or3-wireconnec<on– ground(pin5)andeitheror
bothreceiveandtransmit(pins2and3)
• Othercontrolsavailable,butseldomused
• Datatransmiaedonebitata<me,withprotocolsestablishinghowonerepresentsdata
• Slow-ish(mostcommonis9600bits/sec)
Lecture4:Pi/Python/Interface UCSDPhys122 10
Lecture 4: Pi/Python/Interface UCSD Phys 122 11
TimeIsoftheEssence• Ifprovidedseparateclockanddata,thetransmiaergivesthereceiver<ming
ononesignal,anddataonanother• Requirestwosignals(clockanddata):canbeexpensive(butI2C,SPIdoesthis)
• Datavaluesarearbitrary(norestric<ons)
• Asdistanceand/orspeedincrease,clock/dataskewdestroys<ming
time
sample times centered in data bits
data
cl
ock sample on
rising edge of clock
slidecourtesyE.Michelsen
Lecture 4: Pi/Python/Interface UCSD Phys 122 12
NoClock:DoYouKnowWhereYourDataIs?
interpolated sample times (bit centers)
transitions locate data
time
data
slidecourtesyE.Michelsen
Lecture 4: Pi/Python/Interface UCSD Phys 122 13
Asynchronous:UpCloseandPersonal• Asynchronous
– technicaltermmeaning“wheneverIfeellikeit”
• Startbitisalways0.Stopbitisalways1.
• Theline“idles”betweenbytesinthe“1”state.
• Thisguaranteesa1to0transi<onatthestartofeverybyte• A;ertheleadingedgeofthestartbit,ifyouknowthedatarate,you
canfindallthebitsinthebyte
interpolated sample times (bit centers)
transition locates data
time
star
t 1
0
bit 0
bit 1
bit 2
bit 3
bit 4
bit 5
bit 6
bit 7
stop
idle idle one byte
slidecourtesyE.Michelsen
Lecture 4: Pi/Python/Interface UCSD Phys 122 14
CanWeTalk?
• Ifweagreeon4asynchronouscommunica<onparameters:– Datarate:Speedatwhichbitsaresent,inbitsperseconds(bps)– Numberofdatabits:databitsineachbyte;usually8
• oldstuffo;enused7– Parity:Anerrordetec<ngmethod:None,Even,Odd,Mark,Space
– Stopbits:numberofstopbitsoneachbyte;usually1.• Rarely2or(morerarely)1.5:justaminimumwait<me:canbeindefinite
star
t
bit 0
bit 1
bit 2
bit 3
bit 4
bit 5
bit 6
parit
y
stop
1
idle idle 9600, 7E2
star
t
bit 0
bit 1
bit 2
bit 3
bit 4
bit 5
bit 6
bit 7
stop
idle idle ASCII “A” = 0x41
9600, 8N1
1 bit @ 9600 bps = 1/9600th sec
stop
2
slidecourtesyE.Michelsen
Note:LSBsentfirst
Lecture 4: Pi/Python/Interface UCSD Phys 122 15
RS-232:mostcommonimplementa<on• RS-232isanelectrical(physical)specifica<onforcommunica<on
– idle,or“mark”stateislogic1;• -5to−15V(usuallyabout−12V)ontransmit• -3to−25Vonreceive
– “space”stateislogic0;• +5to+15V(usually~12V)ontransmit• +3to+25Vonreceive
– thedeadzoneisfrom−3Vto+3V(indeterminatestate)• Usuallyusedinasynchronousmode,definedbyparametersonprev.slide
– soidlesat−12;startjumpsto+12;stopbitat−12– sinceeachpacketisframedbystart/stopbits,guaranteedatransi<onatstart– parity(ifused)worksasfollows:
• evenparityguaranteesanevennumberofonesinthetrain• oddparityguaranteesanoddnumberofonesinthetrain
• UART:UniversalAsynchronousReceiver/Transmiaer– commonterm/labelforaserialinterface
Lecture 4: Pi/Python/Interface UCSD Phys 122 16
GPIB(IEEE-488)
• An8-bitparallelbusallowingupto15devicesconnectedtothesamecomputerport– addressingofeachmachine(eitherviamenuordip-switches)
determineswho’swho– candaisy-chainconnectors,eachcable2morlessinlength
• Extensivehandshakingcontrolsthebus– computercontrolswhocantalkandwhocanlisten
• Manytest-and-measurementdevicesequippedwithGPIB– commonmeansofcontrollinganexperiment:posi<oning
detectors,measuringorsecngvoltages/currents,etc.• Canbereasonablyfast(1Mbit/sec)
Lecture 4: Pi/Python/Interface UCSD Phys 122 17
DataAcquisi<on• APCI-cardfordataacquisi<onisa
veryhandything
• Theonepicturedatright(Na<onalInstrumentsPCI-6031E)has:– 64analoginputs,16bit– 2DACs,16bitanalogoutputs– 8digitalinput/output– 100,000samplespersecond– on-board<mers,counters
• Breakoutbox/boardrecommended
RPiInterface
• 40-pinheaderonsideofRPi
• serialisorange(UART)• I2Cislightblue• SPIispurple• GPIOisgreen
– andcanalsouseanypinlabeledGPIOxx
Lecture4:Pi/Python/Interface UCSDPhys122 18
SPI:SerialPeripheralInterface
• 4lines(plusgroundreference,asalways)– clock(CLK)– data“in”(MISO:masterin,slaveout)
– data“out”(MOSI:masterout,slavein)– chipenable(CE#_N:usuallyac<velow)
• RPihastwoCElines• some<mescalledchipselect(CS)orslaveselect(SS)
• SynchronousForm
• Namingresolvesambiguityaboutdatadirec<on– TX/RXalwaysconfusing:accordingtowhichdevice?
Lecture4:Pi/Python/Interface UCSDPhys122 19
SPIScheme
Lecture4:Pi/Python/Interface UCSDPhys122 20fromsparkfun.com
Mul<pleDevices
Lecture4:Pi/Python/Interface UCSDPhys122 21
fromsparkfun.com
DeviceonlylistenswhenitsCE/CS/SSlineispulledlow
AlsoPossibletoDaisyChain
Lecture4:Pi/Python/Interface UCSDPhys122 22
Eachdevicepassesmessageontonext;commonforLEDstrings
fromsparkfun.com
ExamplefromLTC2141(ADC)datasheet
Lecture4:Pi/Python/Interface UCSDPhys122 23
Notes: MSBfirst;MOSI=SDI(slavedatain);MISO=SDO(slavedataout) looksatSDI(MOSI)orSDO(MISO)onupwardclocktransi<on R/Whighmeansread;low(notebar)meanswrite firstwriteaddress,theneitherreadorwritedata chipenableassertedlowforwholeexchange
ExampleRegisteronLTC2141
Lecture4:Pi/Python/Interface UCSDPhys122 24
Tosetregister4toABPand2’scomp.,wouldwrite0x04,0x05overSPI
Lecture 4: Pi/Python/Interface UCSD Phys 122 25
Aquicknoteonhexadecimal
Lecture 4: Pi/Python/Interface UCSD Phys 122 26
Hexadecimal,con<nued
• Onceitiseasyforyoutorecognizefourbitsata<me,8bitsistrivial:– 01100001is0x61– 10011111is0x9f
• CanbehandybecausetheASCIIcodeisbuiltaroundhex:– ‘A’is0x41,‘B’is0x42,…,‘Z’is0x5a– ‘a’is0x61,‘b’is0x62,…,‘z’is0x7a– ‘^A’(control-A)is0x01,‘^B’is0x02,‘^Z’is0x1A– ‘0’is0x30,‘9’is0x39
CorePythonSPICode
Lecture4:Pi/Python/Interface UCSDPhys122 27
import spidev # module with SPI cmds
spi = spidev.SpiDev() # instantiate devicespi.open(0,0) # selects CE0spi.max_speed_hz = 122000 # 122 kHz*
def readRegister(regAddr):address = 0x80 | regAddr # sets read bitresp = spi.xfer2([address,0x00]) # xfer2 keeps CE lowreturn resp[1] # result is in second byte
def writeRegister(regAddr,data):spi.xfer2([regAddr,data]) # simply write (write bit low)
writeRegister(0x04,0x05) # sets register 4 to 0x05result = readTegister(0x04) # if want to confirm reg. 4 setting
*op<onsforspeedare:7629,15200,30500,61000,122000,244000,488000,976000,1953000,3900000,7800000,15600000,31200000,62500000,125000000
I2C:Inter-IntegratedCircuit• PronouncedI-squared-CorI-two-C• Twosignallines(plusground):
– clock(SCL)– data(SDA;bi-direc<onal)
– StartswhenSDApulledlowwhileSCLs<llhigh– stoPswhenSDApulledhighwhileSCLrestoredtohigh– dataread/validwhileSCLhigh(updatedwhenSCLlow)– datalinecancontainread/writeandacknowledgebits
Lecture4:Pi/Python/Interface UCSDPhys122 28
ARealExampleforLab3:ADS1015
• TexasInstr.ADS1015– 12-bitADC,4channels– VDD2.0to5.5V
– I2CInterface• DeviceaddressdependsonwhatADDRconnectsto:
Lecture4:Pi/Python/Interface UCSDPhys122 29
ADDRPinto: FullAddress(7bit)
GND 1001000
VDD 1001001
SDA 1001010
SCL 1001011
Lecture4:Pi/Python/Interface UCSDPhys122 30
• CanconfigureinputsvariouswaysusingMUX(closetwoswitches)• Variablegain(range)viaPGA(programmablegainamplifier)• I2Cforinterface• Op<onalcomparatorac<ontocontrolALERTpin
Lecture4:Pi/Python/Interface UCSDPhys122 31
Fourframes(bytesplusR/Wandacknowledge):targetaddress;registertoaccess;thentwobytesofdata
Notes: firstframeinstructswhetherreadorwrite(herewrite) ACKpulledlowmeansdeviceconfirmscommunica<on MSBfirst,LSBlast
couldbe“runt”
Lecture4:Pi/Python/Interface UCSDPhys122 32
Firstwriteaddressregister(2frames);Thenre-addressasread,andread2bytes
MSBfirst;ACKpulledlowifconfirmedcomm.
couldbe“runt”
RegisterMapping
• We’lljustcareaboutfirsttworegisters(00and01)
• 12-bitconversionregister(00)arrangedin2bytesas:– D11D10D9D8D7D6D5D4andD3D2D1D00000
• Configura<onregisterispreaybusy…
Lecture4:Pi/Python/Interface UCSDPhys122 33
Configura<onRegister
• ADS1015datasheettakes2pagestodetailop<ons– controlsOpera<ngState(e.g.,startconversion)– MUX:4single-endedor2differen<almeasurements– setsvoltagerangeforconversion(Prog.GainAmplifier)– singleshotorcon<nuousMODE– DataRate(ifcon<nuoussampling)– COMParatoropera<onforcontrollingALERTopera<on
Lecture4:Pi/Python/Interface UCSDPhys122 34
ExamplePython
Lecture4:Pi/Python/Interface UCSDPhys122 35
import smbus # module for i2c
i2cbus = smbus.SMBus(1) # instantiate: can name whatever
ADDR = 0x48 # default 1001000 if ADDR->GND
# write to config register (1) default valuesi2cbus.write_i2c_block_data(ADDR,1,[0x85,0x83])
# read from conversion register (0) 2 bytes and combinedata = i2cbus.read_i2c_block_data(ADDR,0,2)val_twos_comp = (data[0] << 4) + ((data[1] & 0xf0) >> 4)
Resultwillbesingledifferen<alconversionofA0minusA1in±2.048Vrange
Alltheworkisinfiguringouthowtomanipulatetheconfigregistertogettheresultsyouwant(insinglemode,eachconversionneedsaconfigurecommand)
RefertoADS1015datasheetforfulldetailsonregisterconfigura<onop<ons
Resultisin2’scomplement
• Binaryrepresenta<onforsignedintegers– makesbinarymatheasy/natural(singlesetofrules)
• Posi<venumberslook“normal”– 00000000=0;00000001=1;01001101=77
• Nega<venumbershavetheMSB“lit”,thenotherbitsinverted,thenadd1– Ex:−3;startwith00000011;MSB!1andinvertothers(11111100),thenadd1:11111101
– now−3addedto+3inbinarywillgive100000000(zeroifignoringoverflowbit)
Lecture4:Pi/Python/Interface UCSDPhys122 36
Recovering2’scomplementvalue
• Mustspecifynumberofbitsinrepresenta<on– inpreviousslide,used8;forADS1015,it’s12
• TheifstatementchecksMSB– <<isle;-shi;bysome#ofplaces;&isbit-wiseANDopera<on
• Example:00010110<<2becomes01011000• Example:01101101&10101010becomes00101000(only1ifbothbits1)
• WhenMSBislit(notequalzero)– subtractoff100000000(in8-bitexample)
• Our−3example:11111101isliterally253inunsignedbinary– subtract256(100000000)andle;with-3
• Perhapsyouseethe“complement”aspect– the“other”partof2N,oncethenega<vepartisremoved
Lecture4:Pi/Python/Interface UCSDPhys122 37
def twos(val,bits): # bits in represent. if (val & (1 << (bits - 1))) != 0: # check if MSB=1 val = val - (1 << bits) # subtract 2^bits return val
Applica<onforLab3
• We’llreadmul<pletemperaturesensors– RTDs(resis<vetemperaturedevices)– signalcondi<oning(turnresistanceintovoltage)– analog-to-digitalconversion(ADS1015)– interfacetoRaspberryPi– programmingPythontocollectandstoredata
Lecture4:Pi/Python/Interface UCSDPhys122 38
Lecture 4: Pi/Python/Interface UCSD Phys 122 39
Temperaturemeasurement• Avarietyofwaystomeasuretemperature
– thermistor– RTD(Resis<veTemperatureDevice)– AD-590(currentpropor<onaltotemperature)– thermocouple
• BoththethermistorandRTDareresis<vedevices– thermistornotcalibrated,nonlinear,cheap,sensi<ve– pla<numRTDsaccurate,calibrated,expensive
• We’llusepla<numRTDsforthispurpose– small:veryshort<meconstant– accurate;noneedtocalibrate– canmeasurewithsimpleohm-meter– R=1000.0+3.85×(T−0°C)
• so20°Cwouldread1077.0Ω• “tempco”of0.385%per°C(3.85Ω/°C)
Problem:MeasuringResistance
• TheADC(ADS1015)readsavoltage,notaresistance• HowcanwemeasurearesistanceusingtheADC?
– howdowedoitright/well?– whatissuesmightarise?
Lecture4:Pi/Python/Interface UCSDPhys122 40
CurrentSource
• Providestable1.00mAtoRTD,so1.00kΩ!1.00V– afinerangeformeasuringusingADC– if5Vrange,getapprox.1mVresolu<onat12bits
• 1mVisat1mAcorrespondsto1ΩchangeinRTD
• translatestoabout0.25degrees,andnotlimi<ngfactor• RTDcalibra<on,andsubtlegradientstendtobelargererrors
Lecture4:Pi/Python/Interface UCSDPhys122 41
Implementa<on
• LM334currentsource– resistorsconfigurecurrentoutput
• datasheetFigs13&15– diodeperformstemperaturecompensa<on(holdclosetoLM334)socurrentsteadyasambienttemperaturechanges
– RTDaaachedinseriesandvoltagemeasurementattopendgoestoADC
Lecture4:Pi/Python/Interface UCSDPhys122 42
InnerWorkingsoftheLM334
• VRheldto~64mV– acrossRSETgivesISET– stronglineartemp.dep.
– 214µV×T(K)
Lecture4:Pi/Python/Interface UCSDPhys122 43
MeanwhileISET/IBIASRa<oWell-Behaved
• At1mA,ara<oof~17
• Resultofmathisthat:– ISET=VR/RSET×n/(n−1)– nisra<o– VRis214µV×T(K)
• about64mVatroomT
– ISET=227µV×T(K)/RSET– sotoget1mAat300K:
• RSETwantstobe68Ω
Lecture4:Pi/Python/Interface UCSDPhys122 44
DiodeCompensa<on
• The“tempco”oftheLM334is0.227mV/C– 0.33%perdegree;RTDis0.385%perdegree– samesign,soalmostdoublesdV/dTofambientrise
• Typicaldiodeshaveatempcoaboutten<meshigher,andoppositesign(−2.5mV/C)
• Theresistorra<oisroughly10×toeffectcompensa<on– seedatasheetforassociatedcalcula<ons
• Reliesonsimilartemperatureforbothcomponents– thereforegoodtoputclosetogether,touching,evenencase
Lecture4:Pi/Python/Interface UCSDPhys122 45
Lab3Flow
• LogontoPi;resetgroup/benchpassword• MessaroundwithLinux/Unix• MessaroundwithPython• EstablishI2Ccommunica<ontoADS1015
– includingoscilloscopeverifica<on• BuildbreadboardRTDcurrentsource• MakeprogramtocollectRTDdata
• Expandtomul<pleRTDchannels– canbreadboardorusepre-builtmodules
Lecture4:Pi/Python/Interface UCSDPhys122 46
Announcements
• IfnoUnix/Linuxfamiliarity– encouragedtolookatLab3beforeWed.– findtutorials,andexploreessen<alcommandslistedearlier– idealifyoucantryonterminal
• MacTerminal;canuselabPiaswell
• IfnoPythonfamiliarity– encouragedtolookatLab3beforeWed.– findtutorials,andlearntowriteandexecutesimpleprograms– idealifabletorunPythoninterac<vesessionandalsotry
execu<ngprograms• MacTerminal;canuselabPiaswell
• Lab3willbecombinedwithLab4forsinglewrite-up,dueOct.30
Lecture4:Pi/Python/Interface UCSDPhys122 47
Recommended