Raspberry Pi and Interfacing
Linux
Python
Interfaces
The Point
• Experiments o;en mean measuring and recording
data
– sense
– digi<ze
– communicate
– automate
– store
– analyze
– publish
– fame and glory?
Lecture 4: Pi/Python/Interface UCSD Phys 122 2
Focus on Accessible
• Oceans of possibili<es for data acquisi<on/interface
• Raspberry Pi is:
– cheap (you can have your own)
– cheap (so;ware is free)
– cheap (low-cost accoutrements, like ADC)
• Other RPi benefits:
– familiarizes with Linux & Python
• means Pi can run very advanced/sophis<cated code, if needed
– supports loads of modern interfaces
• I2C, SPI, serial, GPIO, USB
– can play “nice” with research-grade interfaces
• telnet, ssh, other network interfaces
Lecture 4: Pi/Python/Interface UCSD Phys 122 3
Linux (Unix) Environment
• Command-line interface (terminal session)
• Will want to find and work through tutorials
• Essen<al commands:
– cd (and meaning of ., ..), mkdir, ls (and ls -l), cp, rm,
mv, pwd, vi or nano, less, head, tail, cat, grep, wc
(word count), | (pipe), > (stuff into file), < (source from file),
chmod, passwd, exit, etc.
– familiarize yourself with at least these (and associated
arguments/flags)
– use “man” (manual) pages for details:
• man mkdir
• Mac computers have Unix founda<on, so prevalent OS
Lecture 4: Pi/Python/Interface UCSD Phys 122 4
Raspberry Pi Access
• Pi4 units in lab; one per bench; “headless”
• Access via ssh or puay on lab machines
• hostname: bench1, bench2, etc.
• username: bench1, bench2, etc. (matches unit/
bench)
• password: bench1, bench2, etc.
– temporary: suggest changing a;er you & partner establish
your bench (share/decide with partner)
– command: passwd
Lecture 4: Pi/Python/Interface UCSD Phys 122 5
Python Language
• Prevalent in Physics/Astro
• Interpreted (slower than compiled)
• Easy syntax (high level, readable)
• Excep<onally good at string parsing/handling
• Libraries provide powerful func<onality
– numpy: math on vectors/arrays
– scipy: special func<ons, op<miza<on
– matplotlib (pylab): plocng, a la MatLab
– boatloads of others (many included in standard
installa<on: math, sys, os, <me, re, as a start)
Lecture 4: Pi/Python/Interface UCSD Phys 122 6
Python Tutorials
• Finding your own resources, learn how to:
– run interac<vely to explore syntax; use dir() and help()
– use lists, tuples, dic<onaries; list comprehension
– perform math: import math; dir(math)
– create/invoke/run program (next slide)
– control flow: if/else; for/do/while
– format print statements: %s, %d, %5.2f, etc.
– use command line arguments: float(sys.argv[3]), e.g.
– read from file: open(); for line in file_handle; close()
– write to file: file_handle.write(formaaed_string)
• Example: Google: python list comprehension tutorial
Lecture 4: Pi/Python/Interface UCSD Phys 122 7
Example Python Crea<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 Python
import 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)
Lecture 4: Pi/Python/Interface UCSD Phys 122 8
Interfaces
• A moving target, as technology changes
– serial (RS-232), USB, I2C, SPI are common
• Raspberry Pi does these, plus GPIO (Gen. Purp. Input/Output)
– GPIB, CAMAC, VME/VXI, PCI cards (DAQ) for lab environ.
Lecture 4: Pi/Python/Interface UCSD Phys 122 9
Serial Communica<ons
• Most PCs have a DB9 male plug
for RS-232 serial asynchronous
communica<ons
– we’ll get to these defini<ons
later
– o;en COM1 on a PC
• In most cases, it is sufficient to
use a 2- or 3-wire connec<on
– ground (pin 5) and either or
both receive and transmit (pins
2 and 3)
• Other controls available, but
seldom used
• Data transmiaed one bit at a
<me, with protocols
establishing how one
represents data
• Slow-ish (most common is 9600
bits/sec)
Lecture 4: Pi/Python/Interface UCSD Phys 122 10
Time Is of the Essence
• If provided separate clock and data, the transmiaer gives the receiver <ming
on one signal, and data on another
• Requires two signals (clock and data): can be expensive (but I2C, SPI does this)
• Data values are arbitrary (no restric<ons)
• As distance and/or speed increase, clock/data skew destroys <ming
sample on
clock
rising edge
of clock
sample times
centered in data bits
data
time
Lecture 4: Pi/Python/Interface UCSD Phys 122 11
slide courtesy E. Michelsen
No Clock:
Do You Know Where Your Data Is?
transitions locate data
data
time
interpolated sample times (bit centers)
Lecture 4: Pi/Python/Interface UCSD Phys 122 12
slide courtesy E. Michelsen
Asynchronous: Up Close and Personal
• Asynchronous
– technical term meaning “whenever I feel like it”
• Start bit is always 0. Stop bit is always 1.
• The line “idles” between bytes in the “1” state.
• This guarantees a 1 to 0 transi<on at the start of every byte
• A;er the leading edge of the start bit, if you know the data rate, you
can find all the bits in the byte
transition
locates data one byte
idle idle
1
bit 0
bit 1
bit 2
bit 3
bit 4
bit 5
bit 6
bit 7
start
stop
0
time interpolated sample times (bit centers)
Lecture 4: Pi/Python/Interface UCSD Phys 122 13
slide courtesy E. Michelsen
Can We Talk?
ASCII “A” = 0x41
idle 9600, 8N1 idle
bit 0
bit 1
bit 2
bit 3
bit 4
bit 5
bit 6
bit 7
start
stop
1 bit @ 9600 bps = 1/9600th sec
• If we agree on 4 asynchronous communica<on parameters:
– Data rate: Speed at which bits are sent, in bits per seconds (bps) Note: LSB
– Number of data bits: data bits in each byte; usually 8 sent first
• old stuff o;en used 7
– Parity: An error detec<ng method: None, Even, Odd, Mark, Space
– Stop bits: number of stop bits on each byte; usually 1.
• Rarely 2 or (more rarely) 1.5: just a minimum wait <me: can be indefinite
idle 9600, 7E2 idle
stop 1
stop 2
parity
bit 0
bit 1
bit 2
bit 3
bit 4
bit 5
bit 6
start
Lecture 4: Pi/Python/Interface UCSD Phys 122 14
slide courtesy E. Michelsen
RS-232: most common implementa<on
• RS-232 is an electrical (physical) specifica<on for communica<on
– idle, or “mark” state is logic 1;
• -5 to −15 V (usually about −12 V) on transmit
• -3 to −25 V on receive
– “space” state is logic 0;
• +5 to +15 V (usually ~12 V) on transmit
• +3 to +25 V on receive
– the dead zone is from −3 V to +3 V (indeterminate state)
• Usually used in asynchronous mode, defined by parameters on prev. slide
– so idles at −12; start jumps to +12; stop bit at −12
– since each packet is framed by start/stop bits, guaranteed a transi<on at start
– parity (if used) works as follows:
• even parity guarantees an even number of ones in the train
• odd parity guarantees an odd number of ones in the train
• UART: Universal Asynchronous Receiver/Transmiaer
– common term/label for a serial interface
Lecture 4: Pi/Python/Interface UCSD Phys 122 15
GPIB (IEEE-488)
• An 8-bit parallel bus allowing up to 15 devices connected
to the same computer port
– addressing of each machine (either via menu or dip-switches)
determines who’s who
– can daisy-chain connectors, each cable 2 m or less in length
• Extensive handshaking controls the bus
– computer controls who can talk and who can listen
• Many test-and-measurement devices equipped with
GPIB
– common means of controlling an experiment: posi<oning
detectors, measuring or secng voltages/currents, etc.
• Can be reasonably fast (1 Mbit/sec)
Lecture 4: Pi/Python/Interface UCSD Phys 122 16
Data Acquisi<on
• A PCI-card for data acquisi<on is a
very handy thing
• The one pictured at right (Na<onal
Instruments PCI-6031E) has:
– 64 analog inputs, 16 bit
– 2 DACs, 16 bit analog outputs
– 8 digital input/output
– 100,000 samples per second
– on-board <mers, counters
• Breakout box/board recommended
Lecture 4: Pi/Python/Interface UCSD Phys 122 17
RPi Interface
• 40-pin header on side
of RPi
• serial is orange (UART)
• I2C is light blue
• SPI is purple
• GPIO is green
– and can also use any
pin labeled GPIOxx
Lecture 4: Pi/Python/Interface UCSD Phys 122 18
SPI: Serial Peripheral Interface
• 4 lines (plus ground reference, as always)
– clock (CLK)
– data “in” (MISO: master in, slave out)
– data “out” (MOSI: master out, slave in)
– chip enable (CE#_N: usually ac<ve low)
• RPi has two CE lines
• some<mes called chip select (CS) or slave select (SS)
• Synchronous Form
• Naming resolves ambiguity about data direc<on
– TX/RX always confusing: according to which device?
Lecture 4: Pi/Python/Interface UCSD Phys 122 19
SPI Scheme
Lecture 4: Pi/Python/Interface UCSD Phys 122 from sparkfun.com 20
Mul<ple Devices
from sparkfun.com
Device only listens when its CE/CS/SS line is pulled low
Lecture 4: Pi/Python/Interface UCSD Phys 122 21
Also Possible to Daisy Chain
from sparkfun.com
Each device passes message on to next; common for LED strings
Lecture 4: Pi/Python/Interface UCSD Phys 122 22
Example from LTC2141 (ADC) datasheet
Notes: MSB first; MOSI = SDI (slave data in); MISO = SDO (slave data out)
looks at SDI (MOSI) or SDO (MISO) on upward clock transi<on
R/W high means read; low (note bar) means write
first write address, then either read or write data
chip enable asserted low for whole exchange
Lecture 4: Pi/Python/Interface UCSD Phys 122 23
Example Register on LTC2141
To set register 4 to ABP and 2’s comp., would write 0x04, 0x05 over SPI
Lecture 4: Pi/Python/Interface UCSD Phys 122 24
A quick note on hexadecimal
Lecture 4: Pi/Python/Interface UCSD Phys 122 25
Hexadecimal, con<nued
• Once it is easy for you to recognize four bits at a
<me, 8 bits is trivial:
– 01100001 is 0x61
– 10011111 is 0x9f
• Can be handy because the ASCII code is built around
hex:
– ‘A’ is 0x41, ‘B’ is 0x42, …, ‘Z’ is 0x5a
– ‘a’ is 0x61, ‘b’ is 0x62, …, ‘z’ is 0x7a
– ‘^A’ (control-A) is 0x01, ‘^B’ is 0x02, ‘^Z’ is 0x1A
– ‘0’ is 0x30, ‘9’ is 0x39
Lecture 4: Pi/Python/Interface UCSD Phys 122 26
Core Python SPI Code
import spidev # module with SPI cmds
spi = spidev.SpiDev() # instantiate device
spi.open(0,0) # selects CE0
spi.max_speed_hz = 122000 # 122 kHz*
def readRegister(regAddr):
address = 0x80 | regAddr # sets read bit
resp = spi.xfer2([address,0x00]) # xfer2 keeps CE low
return 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 0x05
result = readTegister(0x04) # if want to confirm reg. 4 setting
* op<ons for speed are: 7629, 15200, 30500, 61000, 122000, 244000, 488000, 976000,
1953000, 3900000, 7800000, 15600000, 31200000, 62500000, 125000000
Lecture 4: Pi/Python/Interface UCSD Phys 122 27
I2C: Inter-Integrated Circuit
• Pronounced I-squared-C or I-two-C
• Two signal lines (plus ground):
– clock (SCL)
– data (SDA; bi-direc<onal)
– Starts when SDA pulled low while SCL s<ll high
– stoPs when SDA pulled high while SCL restored to high
– data read/valid while SCL high (updated when SCL low)
– data line can contain read/write and acknowledge bits
Lecture 4: Pi/Python/Interface UCSD Phys 122 28
A Real Example for Lab 3: ADS1015
• Texas Instr. ADS1015
– 12-bit ADC, 4 channels
– VDD 2.0 to 5.5 V
– I2C Interface
• Device address depends on
what ADDR connects to:
ADDR Pin to: Full Address (7 bit)
GND 1001000
VDD 1001001
SDA 1001010
SCL 1001011
Lecture 4: Pi/Python/Interface UCSD Phys 122 29
• Can configure inputs various ways using MUX (close two switches)
• Variable gain (range) via PGA (programmable gain amplifier)
• I2C for interface
• Op<onal comparator ac<on to control ALERT pin
Lecture 4: Pi/Python/Interface UCSD Phys 122 30
could be “runt”
Four frames (bytes plus R/W and acknowledge):
target address; register to access; then two bytes of data
Notes: first frame instructs whether read or write (here write)
ACK pulled low means device confirms communica<on
MSB first, LSB last
Lecture 4: Pi/Python/Interface UCSD Phys 122 31
could be “runt”
First write address register (2 frames);
Then re-address as read, and read 2 bytes
MSB first; ACK pulled low if confirmed comm.
Lecture 4: Pi/Python/Interface UCSD Phys 122 32
Register Mapping
• We’ll just care about first two registers (00 and 01)
• 12-bit conversion register (00) arranged in 2 bytes as:
– D11 D10 D9 D8 D7 D6 D5 D4 and D3 D2 D1 D0 0 0 0 0
• Configura<on register is preay busy…
Lecture 4: Pi/Python/Interface UCSD Phys 122 33
Configura<on Register
• ADS1015 datasheet takes 2 pages to detail op<ons
– controls Opera<ng State (e.g., start conversion)
– MUX: 4 single-ended or 2 differen<al measurements
– sets voltage range for conversion (Prog. Gain Amplifier)
– single shot or con<nuous MODE
– Data Rate (if con<nuous sampling)
– COMParator opera<on for controlling ALERT opera<on
Lecture 4: Pi/Python/Interface UCSD Phys 122 34
Example Python
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 values
i2cbus.write_i2c_block_data(ADDR,1,[0x85,0x83])
# read from conversion register (0) 2 bytes and combine
data = i2cbus.read_i2c_block_data(ADDR,0,2)
val_twos_comp = (data[0] << 4) + ((data[1] & 0xf0) >> 4)
Result will be single differen<al conversion of A0 minus A1 in ±2.048 V range
All the work is in figuring out how to manipulate the config register to get the
results you want (in single mode, each conversion needs a configure command)
Refer to ADS1015 datasheet for full details on register configura<on op<ons
Lecture 4: Pi/Python/Interface UCSD Phys 122 35
Result is in 2’s complement
• Binary representa<on for signed integers
– makes binary math easy/natural (single set of rules)
• Posi<ve numbers look “normal”
– 0000 0000 = 0; 0000 0001 = 1; 0100 1101 = 77
• Nega<ve numbers have the MSB “lit”, then other bits
inverted, then add 1
– Ex: −3; start with 0000 0011; MSB ! 1 and invert others
(1111 1100), then add 1: 1111 1101
– now −3 added to +3 in binary will give 1 0000 0000 (zero if
ignoring overflow bit)
Lecture 4: Pi/Python/Interface UCSD Phys 122 36
Recovering 2’s complement value
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
• Must specify number of bits in representa<on
– in previous slide, used 8; for ADS1015, it’s 12
• The if statement checks MSB
– << is le;-shi; by some # of places; & is bit-wise AND opera<on
• Example: 0001 0110 << 2 becomes 0101 1000
• Example: 0110 1101 & 1010 1010 becomes 0010 1000 (only 1 if both bits 1)
• When MSB is lit (not equal zero)
– subtract off 1 0000 0000 (in 8-bit example)
• Our −3 example: 1111 1101 is literally 253 in unsigned binary
– subtract 256 (1 0000 0000) and le; with -3
• Perhaps you see the “complement” aspect
– the “other” part of 2N, once the nega<ve part is removed
Lecture 4: Pi/Python/Interface UCSD Phys 122 37
Applica<on for Lab 3
• We’ll read mul<ple temperature sensors
– RTDs (resis<ve temperature devices)
– signal condi<oning (turn resistance into voltage)
– analog-to-digital conversion (ADS1015)
– interface to Raspberry Pi
– programming Python to collect and store data
Lecture 4: Pi/Python/Interface UCSD Phys 122 38
Temperature measurement
• A variety of ways to measure temperature
– thermistor
– RTD (Resis<ve Temperature Device)
– AD-590 (current propor<onal to temperature)
– thermocouple
• Both the thermistor and RTD are resis<ve devices
– thermistor not calibrated, nonlinear, cheap, sensi<ve
– pla<num RTDs accurate, calibrated, expensive
• We’ll use pla<num RTDs for this purpose
– small: very short <me constant
– accurate; no need to calibrate
– can measure with simple ohm-meter
– R = 1000.0 + 3.85×(T − 0°C)
• so 20°C would read 1077.0 Ω
• “tempco” of 0.385% per °C (3.85 Ω/°C)
Lecture 4: Pi/Python/Interface UCSD Phys 122 39
Problem: Measuring Resistance
• The ADC (ADS1015) reads a voltage, not a resistance
• How can we measure a resistance using the ADC?
– how do we do it right/well?
– what issues might arise?
Lecture 4: Pi/Python/Interface UCSD Phys 122 40
Current Source
• Provide stable 1.00 mA to RTD, so 1.00 kΩ ! 1.00 V
– a fine range for measuring using ADC
– if 5 V range, get approx. 1 mV resolu<on at 12 bits
• 1 mV is at 1 mA corresponds to 1 Ω change in RTD
• translates to about 0.25 degrees, and not limi<ng factor
• RTD calibra<on, and subtle gradients tend to be larger errors
Lecture 4: Pi/Python/Interface UCSD Phys 122 41
Implementa<on
• LM334 current source
– resistors configure current
output
• datasheet Figs 13 & 15
– diode performs temperature
compensa<on (hold close to
LM334) so current steady as
ambient temperature changes
– RTD aaached in series and
voltage measurement at top
end goes to ADC
Lecture 4: Pi/Python/Interface UCSD Phys 122 42
Inner Workings of the LM334
• VR held to ~64 mV
– across RSET gives ISET
– strong linear temp. dep.
– 214 µV × T(K)
Lecture 4: Pi/Python/Interface UCSD Phys 122 43
Meanwhile ISET/IBIAS Ra<o Well-Behaved
• At 1 mA, a ra<o of ~17
• Result of math is that:
– ISET = VR/RSET×n/(n−1)
– n is ra<o
– VR is 214 µV × T(K)
• about 64 mV at room T
– ISET = 227 µV × T(K)/RSET
– so to get 1 mA at 300 K:
• RSET wants to be 68 Ω
Lecture 4: Pi/Python/Interface UCSD Phys 122 44
Diode Compensa<on
• The “tempco” of the LM334 is 0.227 mV/C
– 0.33% per degree; RTD is 0.385% per degree
– same sign, so almost doubles dV/dT of ambient rise
• Typical diodes have a tempco about ten <mes higher, and
opposite sign (−2.5 mV/C)
• The resistor ra<o is roughly 10× to effect compensa<on
– see data sheet for associated calcula<ons
• Relies on similar temperature for both components
– therefore good to put close together, touching, even encase
Lecture 4: Pi/Python/Interface UCSD Phys 122 45
Lab 3 Flow
• Log on to Pi; reset group/bench password
• Mess around with Linux/Unix
• Mess around with Python
• Establish I2C communica<on to ADS1015
– including oscilloscope verifica<on
• Build breadboard RTD current source
• Make program to collect RTD data
• Expand to mul<ple RTD channels
– can breadboard or use pre-built modules
Lecture 4: Pi/Python/Interface UCSD Phys 122 46
Announcements
• If no Unix/Linux familiarity
– encouraged to look at Lab 3 before Wed.
– find tutorials, and explore essen<al commands listed earlier
– ideal if you can try on terminal
• Mac Terminal; can use lab Pi as well
• If no Python familiarity
– encouraged to look at Lab 3 before Wed.
– find tutorials, and learn to write and execute simple programs
– ideal if able to run Python interac<ve session and also try
execu<ng programs
• Mac Terminal; can use lab Pi as well
• Lab 3 will be combined with Lab 4 for single write-up,
due Oct. 30
Lecture 4: Pi/Python/Interface UCSD Phys 122 47