Sunday, December 21, 2014

68: Arduino Ideas
(where the Pi is too big)
revised 8 Jan 2015

Don't get me wrong -- I'd rather work with the Pi but the general purpose way they are packaged makes them too big to hold in your hand (Gee. And 18 months ago I thought they were tiny).

So, in addition to experimenting with them as semi-smart sensor front-ends to a Raspberry Pi I have explored some hand held applications.

Here's my first try:

I thought this would be a nice helper device for the visually impaired -- a "white cane" without the stick. I have actually built & programmed one of these. But so far (and likely, forever) it's a bust.

Problems (least to most difficult):
1. The Arduino is too slow to include the accelerometer programming. After lots of tries, forget it. The user can tell the angle that she/he is holding the device.

2. The only buzzer/vibrators I could find (Adafruit: small, cheap) are actually tiny motors with unbalanced shafts. I had hoped that I could signal fairly small differences to the user (e.g.: 100ms buzz vs. 500ms). But, guess what, once you start these suckers spinning they stop when they feel like it. Disappointing, but not a fatal flaw (and I could always go to bluetooth audio). Revision: I just tried a 3rd wiring/programming scheme for the buzzers: using PWM I can signal 3 urgency levels with the vibrators.

3. I tried 5 distance/rangefinder devices: 3 ultrasonic, 2 active infrared, 1 laser. The overriding problem is that any of these gadgets can be fooled when held at an angle with the ground (the outgoing signal may be reflected instead of returned). Additionally, the laser only worked with the Raspberry Pi (used Pi's camera to measure pixel offset between the laser dot and the center of the camera sensor -- very accurate at 10'). As above, the laser dot can be reflected; also, a class III (i.e., safe) laser is blanked out in bright sunlight. All of the ultrasonics have too wide a beam of return. I settled for the 2nd IR device (Sharp-GP2Y0A02). It reads ok between 2' and 10'. But I get many goofy short returns. So I do 3 readings and choose the longest.

Anyway, my sample kind-of works most of the time. But even 99% of the time wouldn't be good enough.
Ok. It's ugly.

The only thing that would solve this would be a customized rangefinder just for my "e-cane" -- not in my price range. I could write a book about this experience.

Oh well. Onward. Here are 3 more ideas for hand-held devices:
Gas Detector: Turn it on. Press either button (carbon monoxide or natural gas/propane). After sensor warms up read result on the single digit display: 0 = clear, 9 = bad (buzzer sounds above 2).

The RFID devices are a pair. I need the reader to be able to test the detecter. The reader's 16x2 character display will show what was read -- presumably encoded. (Google "rfid hacking" if you're interested in [or paranoid on] the topic.)

The gas detectors and the RFID reader are all available from http://www.mpja.com/ for $10 or so each. An RFID detector can be home made.

My next projects!

Thursday, December 18, 2014

67: Extending My Pi
* revised 23 Dec 2014 *

In my last post I wrote about adding a front-end Arduino Nano to handle analog input. And that works fine but it doesn't do much for extending sensor distances. I.e., USB 2.0 is limited to 16' cables. So here's my next cut. I added another Nano and a pair of nRF24L01+ tranceivers.


I know, it's messy but the price isn't bad: the Nanos are $14 each and the pair of RF24s were under $10. And the "receiver" Nano can service multiple "senders." 

I used the maniacbug.github.io/RF24/ software. It works but documentation is lacking. I wasted 2 days getting a working setup and there are still mysteries. About par for the course. 

Dec 23: Below is a pic of my transmitting RF24 (Nano in background). With just the builtin antenna I got about 50' indoors (through a wall and my body) before loosing a packet. Had to retry every other packet at 100' indoors to outdoors through 2 walls and an evergreen. Through my body made it worse. Line-of-sight 200' is probably reasonable. But the RF24s with screw-on antennas seem worth it ($20/pair).
nRF24L01+

I have an idle Pi B+ with extra pins, so I'll try using it in place of the "receiver" Nano. The RF 24 uses 5 GPIOs plus 3.3v and ground. 


Saturday, November 15, 2014

66: Analog Input using an Arduino
- revised 11/18/14 -

After my frustration with the MCP3008 (post 65) I decided to try using an Arduino. I bought a new Nano from Sainsmart ($14). Here's the Arduino setup:

Note that the Nano plugs directly into the breadboard
(very handy)

I use the Arduino.app on my iMac to write and debug the Arduino program (over the USB cable). Then I move the cable to a USB port on my Pi. (Note: the Arduino uses Flash memory, so the program starts again.)

Here's the Arduino "sketch" (as programs are called) in C language:
// Rheostat has 3 pins L=GND, R=5v (or 3.3V), Mid to A1
// Readings connected to 3.3V: 0 to 730, to 5V: 0 to 1023
#define RheoPin 1
#define spl(x) Serial.println(x)

void setup() {
    Serial.begin(9600);
}

void loop() {
    int i, r;
  
    while(!Serial.available()) delay(100); // Wait for request
    while(Serial.available() && i < 10) {
          Serial.read(); // discard input
    }
    r = analogRead(RheoPin);
    spl(r); // Writes number as ASCII to the USB
}

Meanwhile, on the other end of the USB cable -- the Pi Python program:
import serial # I had to install "pySerial" for this
import time
import RPi.GPIO as GPIO
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)

ser = serial.Serial("/dev/ttyUSB0", baudrate=9600, timeout=1)
ser.open()

while True:
        ser.write("1") # Ask the Arduino for a reading
        time.sleep(.2)
        ct = ser.inWaiting()
        if ct > 0:
                s = ser.read(ct)
                i = int(s.rstrip()) # ASCII to Int
                print i
        time.sleep(.5)

There's good news and bad news about this approach:
GOOD: 
* No GPIO pins used (a USB port, instead).
* My Arduino program worked the first time.
* Because the Arduino only runs one thing at a time, results can be more accurate.
BAD:
* More complicated, two kinds of programming, etc.
* The cheap Nano still costs 3X the MCP3008 chip.
* The request-to-response turn-around is about 1 second, minimum.

Overall, I like using the Arduino. Better yet, the Pi model B+ should have had analog pins.

REVISED:
I have successfully added other sensors to the Arduino end of the setup: 
1. A photosensor.
2. An HC-SR04 rangefinder.
And I have checked out adding --
3. DS18B20 temperature and DHT22 temperature/humidity sensors (although they work fine on the Pi).
4. Output to a 2x16 LCD character display (saves 4 GPIOs on the Pi).

Saturday, November 8, 2014

65: Analog Devices

So, the RPi B+ has 14 more digital GPIO pins. Big deal.

From my perspective a few analog pins would have made a better "+" model. I have 3 Pi's and an Arduino Micro. Well, the Pi may have a nice OS but analog input is painful on the Pi and it is a chinch on the Arduino.

You can fake analog for devices like a photocell by programming a tight loop, e.g.:

# Python
import RPi.GPIO as GPIO, time, os      
GPIO.setmode(GPIO.BCM)
PHOTO_pin = 22 

def Ptime (pin):
        reading = 0
        GPIO.setup(pin, GPIO.OUT)
        GPIO.output(pin, GPIO.LOW)
        time.sleep(0.1)

        GPIO.setup(pin, GPIO.IN)
        while (GPIO.input(pin) == GPIO.LOW): # Eat the CPU!
                reading += 1
        return reading

 ## read by:
        print Ptime(PHOTO_pin)

Earlier, in Posts 50 and 54 I complained about the inherent inaccuracy of faking analog for an ultrasonic rangefinder (because of Linux scheduling other processes).  And I've noted that the DS18B20 temperature sensor (C language) code uses a lot of CPU cycles to achieve an analog output.

Supposedly, you only need only add am MCP3008 chip to the Pi and, voila, you can trade 4 GPIOs for 8 analog ports. Well, I haven't had much joy with that. I bought 2 chips from Adafruit (anyone besides me irritated by their exorbitant shipping fees?). I've downloaded 4 different sets of 3008 code and the first 3 didn't work for me.

Adafruit's wiring used BCM ports 18, 23, 24 and 25 -- all of which I was already using -- so I first tried the setup described at--

http://www.raspberrypi-spy.co.uk/2013/10/analogue-sensors-on-the-raspberry-pi-using-an-mcp3008/

--which used BCM 10, 9, 11 and 8 (ones I was not using). These are AKA as SP10 pins MOSI, MISO, SCLK AND CE0. This involves activating SPI and downloading stuff. I did this but (as I mentioned) it didn't work.

Finally, code that sort of works:
https://github.com/adafruit/Adafruit-Raspberry-Pi-Python-Code/blob/master/Adafruit_MCP3008/mcp3008.py

but my GPIO pins are:
SPICLK = 11
SPIMISO = 9
SPIMOSI = 10
SPICS = 8

MCP3008 CH0 photo sensor
 CH1 potentiometer
 CH2 - CH7 not connected

Trimmed down Python========

import RPi.GPIO as GPIO, time, os
GPIO.setmode(GPIO.BCM)

# read SPI data from MCP3008 chip, 8 possible adc's (0 thru 7)
def readadc(adcnum, clockpin, mosipin, misopin, cspin):
if ((adcnum > 7) or (adcnum < 0)):
return -1
GPIO.output(cspin, True)

GPIO.output(clockpin, False)  # start clock low
GPIO.output(cspin, False)     # bring CS low

commandout = adcnum
commandout |= 0x18  # start bit + single-ended bit
commandout <<= 3    # we only need to send 5 bits here
for i in range(5):
if (commandout & 0x80):
GPIO.output(mosipin, True)
else:
    GPIO.output(mosipin, False)
      commandout <<= 1
      GPIO.output(clockpin, True)
      GPIO.output(clockpin, False)

adcout = 0
# read in one empty bit, one null bit and 10 ADC bits
for i in range(12):
GPIO.output(clockpin, True)
GPIO.output(clockpin, False)
adcout <<= 1
if (GPIO.input(misopin)):
adcout |= 0x1

GPIO.output(cspin, True)

adcout /= 2       # first bit is 'null' so drop it
return adcout

# change these as desired
SPICLK = 11
SPIMISO = 9
SPIMOSI = 10
SPICS = 8

# set up the SPI interface pins 
GPIO.setup(SPICLK, GPIO.OUT)
GPIO.setup(SPIMISO, GPIO.IN)
GPIO.setup(SPIMOSI, GPIO.OUT)
GPIO.setup(SPICS, GPIO.OUT)

print " #0  #1  #2  #3  #4  #5  #6  #7"
print "-----------------------------------------------------"
while True:
print "|",
for adcnum in xrange(0, 8):
ret = readadc(adcnum, SPICLK, SPIMOSI, SPIMISO, SPICS)
print ret,"\t",
print "|"
time.sleep(2)

=================(sorry, columns won't line up)==================

$ sudo python mcp.py 
 #0   #1   #2   #3   #4   #5   #6   #7
------------------------------------------------------------
 992  0 3 4 2 2 0 0      dark, rheostat closed
 991 0 12 14 14 15 18 31 
 990 0 7 7 4 3 1
 990 0 3 7 8 9 10 22 
...
 983 269 4 4 1 1 0 0      rheostat opening
 982 269 8 11 11 13 14 26 
...
 983 1023 2 1 0 0 0 1     rheostat  way open
 985 1023 13 15 16 17 19 33 
...
 509 663 17 16 12 10 8 13   flashlight on photocell
 445 663 0 5 6 9 9 21 
...

====================================

Note the extraneous readings on the non-connected ports.

After all of this trouble you'd hope that the MCP3008 would save a lot of CPU time getting analog readings but my half-assed tests don't show much reduction (on the photocell, only).

Sunday, September 21, 2014

64: SSH Terminal Timeout

Back in post 48 (not numbered) I described cloning an SD card using rpi-clone. One of the problems I moaned about at that time was that the SSH session timed out part way through the lengthy copying process. This forced me to sit there while my 2nd try ran. I should have Googled "raspberry pi terminal timeout". As usual, there is a messy file in /etc cover this problem -- namely /etc/ssh/sshd_config.

And if you:

  sudo nano /etc/ssh/sshd_config

And strangely change the line:

  TCPKeepAlive yes

to

  TCPKeepAlive no

Then your SSH session won't time out. Hopefully.

Monday, July 21, 2014

63: Resistor Hindsight

When I realized that I'd need a variety of resistor values I bought a cheap assortment from Adafruit (that no longer appears in their on-line catalog). Here's a pic of that mess:
The only labeling that you get is the slip of paper listing the values by the number of each type in the assortment. Over time, I have penciled in the ohms numbers for ones that I looked up using the widget I installed on my Mac.

I have no idea how many hours I've spent peering though a magnifying glass trying to read the tiny colored bands. Anyway, I could have bought smarter.

Here's a possibility (haven't tried it, but labeled and for $8?):

https://www.sparkfun.com/products/10969

Thursday, July 17, 2014

62: Wiring an Opto-isolated Relay

I have 3 relay devices, an 8-switch and 2 2-switches. Here's an image of my latest from http://www.mpja.com/.

Note the convenient "ISO" labels

The picture shows that the jumpers on the lower pins have been removed. Anyway, I provide this because I've seen confusing wiring diagrams on the 'Net and some incorrect Fritzings, as well.

Tuesday, July 15, 2014

61: Philosophical thoughts about the gpio command

I think it's safe to say that the basic philosophy of UNIX (Linux) shell commands is that they do not maintain "state" information between one execution and another. (Info maintained by the shell while you are logged in doesn't break this rule -- your shell only exits when you log out). But gpio obviously ignores this convention. In my post #60 I gave these 2 examples:

$ gpio -g mode 7 in  # pin 7 is connected to an input
. . .
$ gpio -g read 7     # get a 0 or 1 from pin 7

Before I wrote my blog entry, I actually executed those 2 lines on my Pi. Then I quit SSH from my Mac (about 2 weeks ago). The Pi had not been rebooted since, so I logged in just now and repeated the gpio-read command. Surprise, surprise. It still worked (i.e., it remembered that pin 7 was "input").

A "sudo reboot" finally erased that rather dangerous information. I don't like this -- especially since gpio is a "setuid root" command. This is ugly and unnecessary. BTW: after the reboot the gpio-read command did not produce an error message -- it always  returned "1".

Advice? Better to operate relays in Python or C.

Comments?

Tuesday, July 1, 2014

60: Water Sensor

I wanted an alarm on my basement sump. My AC and de-humidifier drain into the sump which is usually seeps away on its own. But then it might not. Anyway, I checked the web and found--

http://pi.gate.ac.uk/pages/basics.html#flood-alarm

I'm not much good at interpreting wiring diagrams, but my 2nd try worked. Here transcribed to Fritzing.

A couple of notes: the 2 resistors (L to R) are 1K and 100K (in case the wires are shorted). Also, my first try didn't sense water: I had only stripped about 1/4" of the 22 gauge wire and the space between was also about 1/4". So I stripped back to bare another 1/4" and taped the copper ends only 1mm apart. Then it worked. 
At first I tested with an actual glass of water
but a little spit on my finger worked as well.
Note: that copper has started to tarnish within a day. 
How long before corrosion connects the wires?

The programming can be done in Linux shell.

Setup:
   gpio -g mode 7 in  # BCM # 7 is my water sensing input

Test:
   gpio -g read 7     # "0" == dry, "1" == wet

And the "-g" option means that you are using BCM pin numbering.

Here's a way-too-simple shell program:
============================
Water=0

gpio -g mode 7 in  # BCM pin 7 is INPUT
if [ $? -ne 0 ]
then
    echo Cannot assign pin 7
exit 1
fi

while true
do
    Water=`gpio -g read 7`
    if [ $Water -eq 1 ]
    then
        sleep 5 # might be a false reading
        Water=`gpio -g read 7`
        if [ $Water -eq 1 ] # 2nd wet reading
        then
            echo "Send dated email and/or text msg!"
            sleep 3000 # sleep a long time / don't nag
        fi
    else
        sleep 300 # or some such
    fi
done

Wednesday, June 25, 2014

59: Paint Your Own Circuit

I bought some Bare Conductive Electric Paint for 6 £. I envisioned drawing elaborate circuit boards (including multilayered!).


The device is about 4" long. It is also billed as "conductive glue." And it may be better for that than for drawing because to draw you have to keep squeezing the tube (like glue) -- and that makes it hard to draw a uniform line. Here's my trivial example:

The 3 images: 
1) poke holes in card stock and insert components
2) squeeze out conductive goop
3) wait 15 minutes for it to dry; add current

SO close!
(and for that price you could buy a breadboard)

I'm still hopeful about making circuits with a 3D printer.

Saturday, May 31, 2014

58: Hardware Hacker or Software Hacker?

I suspect that the Raspberry Pi crowd is mostly hardware savvy (and software naive). I could be wrong, of course. If you've followed this blog you know that I am just the opposite. The reason I bring this up is to recommend some software tricks that could make the things easier for Linux software beginners.

If you have the time you should start by Googling "linux quick reference" (or similar). The trouble with that approach is that you'll get a few thousand hits. So I'll make my own short list of topics you might check out:

Learn about--

-- the man command (on-line manual pages -- generally cryptic, but you can google more info)
-- directories (keep your "home directory" clean)
-- file permissions (chmod command)
-- the .profile file (add your own commands in your "~/bin" directory")
-- a test: what does the "~" character mean?
-- harder test: why won't the shell automatically execute a command in the current directory?
57: Rangefinder Devices, Distance Measuring, etc.

Well, I've tried 2 ultrasound devices (1 cheap, 1 expensive (returned)), an IR device and I have played with do-it-yourself using the Pi camera and a laser pointer. I apparently have unreasonable/unrealistic expectations for these sensors.

I want to make a sort of "electronic cane" (size of a D-cell flashlight, no stick) for the visually impaired -- something held in the user's hand that's angled downward at a point 10' or less ahead. I want the rangefinder to be able to be read several times a second and (most importantly) detect walking surface irregularities of 2" or less at 10'.

Since the current Pi package is too big to wrap your fingers around (something more compact coming?) I'm using an Arduino Micro (which happens to be good with analog outputs, too).

The rest of the gear:

  • the afore-mentioned rangefinder
  • an accelerometer to read angle
  • some sort of output to the user (currently 2 vibrating devices)
  • on/off switch and battery

Back to distance measuring:

  • Ultrasonic: basically, way too wide an angle of reception (but fast enough on the Arduino)
  • IR: problem with the angle to the surface, especially a reflective surface (i.e., water puddle)
  • Camera/laser pointer: (Google "Pi camera as rangefinder") Attractive on the Pi since I'd have control of the software BUT lots of problems:  1) no camera for Arduino (and it's not fast enough and not enough memory),  2) sunlight blots out return from a "class 1 laser" (one not dangerous to eyes) and  3) same reflection problems as IR.   

Maybe my project is doomed.

Wednesday, May 28, 2014

56: A Raspberry Pi-Controlled Video Wall

When I first noticed the Pi's HDMI connector I thought of using the system as a way to create a cheaper video wall. (Back in the 80s I worked on a 75-screen wall that cost millions.) Anyway, you can now buy a 40" 1080 TV for $300. Add one Pi for each TV and an extra Pi to control everything plus an ethernet switch. So you could have a 9-screen system of under $4000. And in the spirit of the Pi, someone has has done software and they are giving it away (for now?). See--

http://www.piwall.co.uk/

Sunday, May 4, 2014

55: My Portable Raspberry Pi

For demo purposes I've built a portable system. It lives in a 6" x 9" (cheap) Lexan box that's perforated with a bunch of holes for ventilation.

Not shown above:
1. An iPhone as an Internet hotspot
2. An iPad for SSH control

Also not shown: the wiring mess inside the box.

What the system can do:
1. It operates all of devices shown and can display results back on the iPad, on the 7-segment display or it can utter the output to the speaker (via text-to-voice).
2. It can take a still with the Pi camera and upload it to the Internet.

If I demo near a big TV I can mirror the iPad screen on it using my Apple TV.

The battery was meant for recharging a smart phone. It can run the Pi for most of a day. Irritatingly, it cannot charge and discharge at the same time. And with a 1 amp charger plug it takes most of a day to recharge.

Another important reason for the speaker: when connecting via the iPhone hotspot I'm not sure what the IP number will be (and it can't be "static" both at home and on the road) so, as the Pi boots up it speaks the current IP number which I then use in making the SSH connection. Messy, huh.
I need to get a speaker that fits inside the box

Thursday, April 24, 2014

Post 54: More about Ultrasonic Rangefinders (and Arduino)

Back in post 50, I complained about the background load variation of Linux causing me inaccurate rangefinder results. So I bought an Arduino Micro. Since I had worked in C language off and on for 20+ years, that part of the transition was no particular problem. And after a bit of trouble I got my HC-SR04 device yielding more consistent readings than I had gotten from the Pi.

I suppose many Raspberry Pi addicts started with an Arduino -- or maybe not. But there is a vast gap between them:
                                          Raspberry Pi        Arduino Micro
                     CPU speed        700MHz              16MHz
     avail. program memory       200+mb              32k (flash RAM)
                      file system       gigabytes             0
             operating system        Linux                  i/o support, boot loader

And the programming environment exists exclusively on a host computer. On my iMac it's the Arduino.app -- which connects via USB micro plug. This connection provides power, downloader, data-in, data-out and a pseudo console. It all "seems" pretty smooth. Arduino source programs are called "sketches." And they are kept track of conveniently on my Mac. My main problem is that program memory is flash RAM. It (necessarily) persists whether or not power is maintained. Maybe it's my setup (Arduino.app / Arduino Micro) but when I compile and download a new sketch this often fails: download is supposed to do a reset (there is also a button) so the new program can take over, but this doesn't always work. Things hang in "downloading" and other problems. Irritating, but not impossible.


But this is supposed to be a Raspberry Pi blog. 


But No. 2: there are lots of systems that involve Arduinos slaved (wired or wireless) to a Pi.


Wednesday, April 16, 2014

53: I Try the "Prototyping Pi" Shield

As I grew tired of breadboard clutter and pulled out wires, I fell for Adafruit's $16 shield. Here's a pic of my still-messy setup:
The good bit: those screwed-down wires are going to stay put! The adjacent sockets are nice and tight, too.

Small complaints: it would be convenient to have extra screw (or insertion) connectors for GND, 3.3v and 5v. Also, When I screwed patch wires into the out-facing connectors the Pi footprint gets big.

Bigger complaint: Note the drawn-on red arrow and dotted line in the photo: That's the Pi camera ribbon cable. The dotted line indicates the approximate location of the camera socket beneath the shield. Before I added the shield the camera worked. But not after. As you can see, the camera is offset from the motherboard plug. Pushing the shield down twisted the ribbon and scratched off a few ribbon wires. Luckily, I have a spare cable but I'm not risking it with the Prototyping Pi. It's back to ye olde breadboard for me.

Two other thoughts:
1. Before I ever ordered the Pi camera I suspected that that cable was going to be trouble.

2. I take no pleasure in soldering. I would like a better breadboard where adding a new wire doesn't cause two previous wires to be loosened or pulled out. Any of you familiar with ZIF connectors?
ZIF standing for "zero insertion force." PCs used to come with these things so the enterprising could trade up chips when they inevitably got faster, denser or cheaper. ZIFs have fallen out of favor now that manufacturers have realized that upgrading chips diminished computer sales. But I digress.

What I'd like is a ZIF-like breadboard. The little lever above is in the open position. Once the chip was plugged in you you merely push the lever down and, voila, you have a reliable, semi-permanent circuit. Now, my perfected breadboard couldn't be just one big ZIF. Here's an off-the-cuff example:
What do you think?


Monday, April 14, 2014

52: Another Mistake of Mine

Back in post 49 I complained that the breadboard T-connector that I ordered from mpja.com was wired backwards in relation to the breadboard rails. But that was only because I plugged it into the wrong end of the breadboard. The two ends are not symmetrical in relation to the positive and ground rails. So here is a picture of it plugged in correctly:


So, it's a pretty good deal after all. Except for my comments in post 45.

Monday, March 17, 2014

51: Raspberry Pi Audio Out

I had a little battery powered Bluetooth speaker that also had a 3.5mm "Line In" jack. I foolishly expected that to work with the audio out jack on the Pi. But it didn't and I learned quickly that the details of Linux audio are arcane and nasty. So I just bought an earphone plug speaker from Radio Shack for $20. The Auvio brand rechargeable unit works fine for my purposes -- and has a builtin volume dial.

To go with it, I downloaded the "festival" text-to-speech software. It's crude but ok in a 1980s sort of way.

Saturday, March 15, 2014

50: Programming an Ultrasonic Rangefinder
-- revised --

I got the device below from mpja.com.

And I followed wiring and programming advice from--

http://www.raspberrypi-spy.co.uk/2012/12/ultrasonic-distance-measurement-using-python-part-1/

Running their sample program gave consistent results (within 5cm at 5m, within 1cm at 3m). But that was with no load on the Pi. When I ran my 10,000-place pi calculation (code listed in an early post) in the background, I got wildly longer readings -- 5m went to 7m.

Here's my mod of pi-spy code:
import time
import RPi.GPIO as GPIO

GPIO.setmode(GPIO.BCM)

GPIO_TRIGGER = 8
GPIO_ECHO = 7

#print "Ultrasonic Measurement"
GPIO.setwarnings(False) #
# Set pins as output and input
GPIO.setup(GPIO_TRIGGER,GPIO.OUT)  # Trigger
GPIO.setup(GPIO_ECHO,GPIO.IN)      # Echo

# Set trigger to False (Low)
GPIO.output(GPIO_TRIGGER, False)

# Allow module to settle
time.sleep(0.5)

# Send 10us pulse to trigger
GPIO.output(GPIO_TRIGGER, True)
time.sleep(0.00001)
GPIO.output(GPIO_TRIGGER, False)
start = time.time()
while GPIO.input(GPIO_ECHO)==0:
  start = time.time()

while GPIO.input(GPIO_ECHO)==1:
  stop = time.time()

# Calculate pulse length
elapsed = stop-start

# Distance pulse travelled in that time is time
# multiplied by the speed of sound (cm/s)
distance = elapsed * 34000

# That was the distance there and back so halve the value
distance = distance / 2

print "Distance : %.1f cm" % distance

As you can see, the two while loops make this a cpu hog. I suppose I could make 3 readings and keep the shortest one.

Comments?

Added 12/16:

I have tried modifying the process priority of the rangefinder.py script. I tried the Unix/Linux nice(1) command. It was named "nice" because a non-super-user can only lower priority, not raise it. Anyway, didn't help.

I tried the code at--
http://www.raspberrypi-spy.co.uk/2012/12/ultrasonic-distance-measurement-using-python-part-2/

Also, inconsistent. So I finally changed the python script above to do 3 readings and only keep the lowest. That worked pretty well (within 2cm at 2m). But (reasonably) accurate back-to-back readings will be 2 seconds apart. Not much help for a vision-impaired person checking for the next curb.

What I really need is for the ECHO pin to cause an interrupt (instead of the code looping)!




Sunday, February 16, 2014

Post 49: Another Problem with the  mpja Breadboard T-connector
(see post 45)

So, since I'd gone to the trouble of identifying the pin-outs, I decided to use the connector. It's a wonder I didn't burn out my Raspberry Pi!
As you can see from the image above, the connections to the breadboard power rails are reversed from every one of the 4 breadboards I own (including the one that came with the T-connector). I (foolishly) assumed that the T plug would connect Ground to Blue and voltage to Red. Nope. It's backwards. So nothing I tried worked. I wasted a couple hours and luckily I didn't harm my Pi.

Friday, February 14, 2014

48: Clone (or back up) your Raspberry Pi SD card
modified 2/7/2018

I've recently bought my 2nd Pi. This led me to try to make a copy of my Pi-1's SD card. I've been backing up that SD card by moving it to an SD reader plugged into my iMac (by USB). There, I used the Terminal "dd" command to make a literal 16gb copy of the card. When I screwed up the card (stupidly changed a GPIO connection while the Pi was powered up and running) I successfully fixed the SD from the iMac back up. But, in this case, I was copying from and to the same SD card.

When I tried to do the same thing to a different 16bg card it didn't work. The 2 cards did not have exactly the same number of data blocks -- off by 1(?).

After trying that a couple useless times, I went looking for something different. And this is it:

https://github.com/billw2/rpi-clone

This is a different approach.  rpi-clone is a long-ish shell command that runs on the Pi and copies your working SD content to the second card (I moved my USB reader to the Pi).

Advantages:
1. It worked!
2. I didn't have to shutdown the Pi or move its SD card.
3. It was faster than the literal 16gb copy.
4. It can do partial updates to an existing card copy.

Actual rpi-clone command (assuming you named it rpi-clone.sh);

% sudo sh rpi-clone [ -f ] sda

(Assuming that a list (ls command) of /dev/sd* listed "sda")

The only problem I had was that I ran it via the Mac Terminal "ssh" interface. The first time I tried rpi-clone I left it (took 25 minutes) and before I returned ssh had timed out my connection to the Pi -- and that aborted the last question from rpi-clone. The 2nd try, I stuck around.

One further advantage of rpi-clone: The last thing that the command does is unmount the SD copy. But if the copy is for a new Pi system you'll want to make a few changes first. For example: you can change /etc/hostname and /etc/network/interfaces. In another Terminal window you can --

cd /mnt/clone/etc # that's where the new card is mounted
nano hostname # change the name?
...
nano network/interfaces 
...

etc.

Note all of the above has to be run with sudo. Be careful!

Oh, and congrats to Bill Wilson for writing rpi-clone.

Sunday, February 9, 2014

About the DS18B20 Temperature Sensors
{Revised!}

I bought my first one from Adafruit, I followed their wiring plan, and I copied their Python source code. But since the .py program just executes Shell commands I wonder why is Python needed at all? Hers's a .sh file that seems to work just as well:

if [ ! -d /sys/bus/w1/devices ]; then
sudo modprobe w1-gpio
sudo modprobe w1-therm
fi
a=`cat /sys/bus/w1/devices/28num-a/w1_slave` 
b=`expr "$a" : ".*YES.*t=\([0-9][0-9]*\)"`
len=${#b}
if [ $len -ge 2 ]; then
f=`expr $b \* 18 / 10000 + 32` # Note: expr only handles integers
echo $f
else
echo "DS18B20 Read Error"
fi

The above seems to work every time I've tried it. The "28num-a" bit above has to match the unique serial number of your device.

A weakness of the expr command (I wrote the original version in 1975) is that it doesn't do fractional numbers. So instead of--

expr $b \* 1.8 / 1000 + 32


You have to multiply by 18 and divide by 10000 to display Fahrenheit.

The heart of the mystery, though: the Adafruit wiring layout shows GPIO pin 4 connected to the DS's data wire but there is no reference to pin 4 in the code above. Since I want to connect 3 DS18B20s to my Pi, do they each take another pin? Or does the code in "w1-therm" only support a single device?

{Since no one answered my question, I found out for myself: You can read several devices with the modprobe software.}



Another worry: those 2 "modprobe" statements obviously leave something running. You can find it by executing the terminal command "ps -ax" -- and here's the culprit process:

 2980 ?        S     16:05 [w1_bus_master1]

That thing is a relative CPU hog; 16 minutes in about a week. 

Thursday, February 6, 2014

Pi to Human Communication

If you have a Pi set up to monitor sensors then you will want to notify someone when things go (potentially) wrong. Assuming your Pi has Internet access (DSL, cable, cellular 3G/4G hotspot modem) you can program it to send out alerts from the Linux Shell, like so:

E-mail:
echo "Warning: Temp below 35F" | mail -s Temp person@some-mail.com

SMS (text message):
echo "Warning: Temp below 35F" | mail cell-phone-number@gateway-name.com

To get the text message to work you have to know what carrier serves the phone number. There's a list at--

  http://www.sweetnam.eu/index.php/List_of_Internet_to_SMS_gateways

Note: In terms of speed, both the e-mail and the text got to me in under 60 seconds. But people are probably more alert to texts.

Tuesday, February 4, 2014

Irritation with the mpja breadboard I mentioned (touted?) in the previous post

Here's a photo of the T-connector:
The RED and BLUE notations are all mine. I had to buzz all the pins out to identify them (well, the left side row was guess-able, I suppose). No help from the supplier, though. This isn't the only mystery, though. The cabling is non-obvious, too.
The T-connector end of the ribbon is keyed -- but not the Pi end! Luckily, I tested the circuit all the way to the other end of the ribbon. Maybe you can make out the dim "2" (upside down) on the Pi end (meaning even-numbered pin side). I never would have guessed that cable twist.

"Other than that, how did you like the play, Mrs. Lincoln."