Thursday, July 23, 2015

84: Adding a Small Monitor

I'm installing an Rpi away from my iMac and SSH. So I bought a cheap keyboard and a 7" 1024x600 HDMI monitor.  To make this work, you first need to make the following change:

% sudo nano /boot/config.txt
(delete the "#" from this line)
#disable_overscan=1

(delete the "#" and change 1280 to 1024)
#framebuffer_width=1280
(delete the "#" and change 720 to 600)
#framebuffer_height=720

(press CTRL/o, type y, press CTRL/x)
% sudo reboot

I then needed to enlarge the console font size from 6x16 pixels to something I could read. I did it like this:


When you log in to Linux (or Unix) a file named ".profile" is executed by the shell. To make the little screen readable I edited the .profile file and added the following line at the end:
setfont /usr/share/consolefonts/Uni3-Terminus28x14.pst.gz
(another reboot)
The 14x28 pixel font works for me. There many (hundreds of) fonts. If you like a bit smaller try 24x12 or bigger 32x16.


Tuesday, June 30, 2015

83: Battery Backup Correction
** revised 7/16/15 **

See http://dicks-arduino-nano.blogspot.com/, post 16.

As I am wont to do, I posted without enough testing. Hopefully, corrected now. I'm surprised (shocked?) at how little interest there is in this topic. Anyway, the setup pictured only works if the USB out draws less than 500mV. None of my Nano test setups take this little -- nor does my Particle Core. So regardless of 5V USB input the the system fails when the battery runs down (USB output drops to 4.1V).


Saturday, June 13, 2015

82: Soil Moisture Sensor

These things need analog. So I'll read it through the ether (wifi) from a Particle Core (like Arduino Mega with built-in Cloud access). See my Arduino/Particle blog post 15.



Saturday, April 25, 2015

81: Let's Review
Apr 25, revised: May 2, Aug 1, Nov 18, 2015

Devices I've wired/programmed* for the Raspberry Pi, Arduino and Spark Core (now Particle Photon)
  • LEDs (everyone starts with these) - RAS
  • Push buttons - RA
  • PIR motion detector - R
  • Magnetic door sensor - RAS
  • Photosensor RAS
  • DS18B20 temperature sensor - RAS
  • DHT22 temperature/humidity sensor - RAS
  • TMP36 temperature sensor - AS
  • Raspberry Pi camera (B/W conversion, timelapse, security cam) - R
  • Relay Switches - RS
  • Water (moisture) sensor - R
  • Soil moisture sensor - AS
  • Water valve/solenoid control - RS
  • Rangefinder: ultrasonic, IR (several models) - RA
  • Speakers - RA
  • CO gas sensor - A
  • Natural gas/propane sensor - A
  • Mini vibrating motors - A
  • Pi - Arduino Com over USB - A to R
  • RF read & write - A
  • RFID sensor - AS
  • 16x2 LCD text device - RA
  • 7-segment clock device - R
To make the above work--
  • resistors, capacitors, diodes, transistors, 
  • Darlington array - R 
  • I2C (MPC2308) - RS 
  • MPC3008 (analog) - R
  • PWM - A
  • Backup battery setup - RAS
  • Also: Internet upload/download, email, text message - RS
* Programmed in Python, C, C++, Linux Shell, Crontab


Saturday, April 18, 2015

80: More on My UPS Battery Setup

I have tested the setup shown in post 79 (explained better in my Arduino blog post 11: dicks-arduino-nano-travails.blogspot.com).

First, I tried it with an Arduino Nano (most expendable). Worked.

Then, my Spark Core setup. Worked, too. I let the battery run down on this test. I'm not sure how long that took (+2 hours?) and I had not recharged the battery after trying it with the Nano. Then something nasty happened: the Powerboost 1000 sort of hiccuped off and on powering the Spark back on for a second each time. Good old Spark survived this but I wouldn't bet on a Pi doing as well. Also, the Powerboost was fried (Adafruit replaced it).

Finally, on a Raspberry Pi B (rev 2) with a fair number of GPIO pins connected including a WIFI dongle, a Pi-powered relay switch and a 7-segment clock display. I let it go nearly an hour then the Pi stopped running while the Powerboost still showed its green "powered" LED. Hummmm.

This is what I want for my Pi setups:

1. Detect fail (eg: by reading photosensor pointed at extern power light on Lipo charger).

2. Send out email and text msg warnings to humans (if internet-connected):
    "Power fail. Shutting DOWN! date/time".

3. In Linux: kill my running processes (especially anything writing files):
   % pgrep -u pi | sudo xargs kill -9 (for user "pi").

4. Linux: % sync; sync; sleep 5

5. Shut off 5v power from battery before voltage drops but so the system will restart when external power is restored.

Suggestions? Will the "Pi Juice" (see Kickstarter) do all of this?

Tuesday, April 7, 2015

79: I built a UPS (uninterruptible power supply/battery backup)

Under $35. Works with Raspberry Pi, Arduino, etc. I'm surprised UPS (reasonable price/size) isn't a hot topic in this (computer geek?) world.


Not difficult! Details at my Arduino blog, post 11--


Sunday, March 29, 2015

78: Controlling my Spark Core Wirelessly over the Internet

My Raspberry Pi can now read sensors and switch relays on my Spark and post results to a Web page! Details at --

http://dicks-arduino-nano.blogspot.com/


Battery powered Spark Core

Tuesday, March 24, 2015

77: More About* Time Lapse with the Pi Camera

For my last example (post 71) I used the timing/counting features of the raspistill command to record my image sequence. But this time I want to capture a JPEG per minute from sunrise to sunset. Here's the shell program I wrote:

ct=0
hr=`date +%H` # just the hour
while [ "$hr" -ge "07" ] && [ "$hr" -le "20" ] ; #e.g.: 7am to 8pm
do
  ct=`expr $ct + 1`
  num=`expr 0000$ct : '.*\(....\)$'`
  raspistill -w 1280 -h 720 -t 1 -o i${num}.jpg
  sleep 60
  hr=`date +%H`
done

The 2nd expr command makes sure that the $num variable is a zero-filled 4-digit number (required in the convert-to-movie step). Also, about 1975 I wrote the original UNIX expr command -- so I like to use it.

_______
* Did you know that when millions of English words were checked, the first (most common) 130 were all one syllable. The first two-syllable word was "about." Does that mean something? Trust me, "exactly" was way, way down the list.

Monday, March 16, 2015

76: Raspberry Pi to Spark Core

It wasn't too painful. I have successfully sent a command to the Spark and gotten data back. My Core is sitting a foot from the Pi but it could be anywhere there's Internet. Details at my Arduino site:


Spark Core in its cute box

Friday, March 6, 2015

75: A New Way to Connect an RPI?

Spark Core: Where have I been? Sounds like what I've been looking for. See--


I ordered one. Let you know.

Tuesday, February 24, 2015

74: Raspberry Pi B 2 and "Real Time"

Many posts ago (50 & 54) I complained that the otherwise convenient Linux multiprocessing overhead could screw up getting time-critical readings from certain sensors. I don't have a Pi 2 yet but with a quad processor that problem may be history. I'll let you know when I find out.

Saturday, February 7, 2015

72: Raspberry Pi 2 as a "PC"

So if you already have a monitor (HDMI or DVI -- forget others), USB keyboard & mouse and $100 you can have a desktop Linux that is now (with the new ARM7) very responsive. Still no Adobe Flash support but otherwise...

What do you need?

* Pi 2 $35 (?)
* 16gb micro SD $25
* Wifi USB plug $15
* Powered USB hub (more ports + power for the Pi) $20
* HDMI cable $5 (or HDMI to DVI: $25)
* Case for Pi $10 (and up)

Most of the apps PC or Mac users are used to will be available with Linux, but with different names & they will be quirky. Here's an analogy with hiking trail difficulty: out East where it's fairly flat they use these terms--

1. Easy
2. Easy/Moderate
3. Moderate
4. Moderate/Difficult
5. Difficult

Changing to Linux has to be a 2.5, at least.

Comments?

Sunday, January 18, 2015

71: My Pi as a Time Lapse Camera

I used raspistill taking 1 still per minute. Moved the JPEGs to my Mac and turned it into MP4 at 10fps. 450 minutes crunched to 45 seconds.

The .mov clip below is seriously down-sampled.


Noon to Sunset
Nothing much happening.

This command on the Pi took the stills:

  raspistill -w 1280 -h 720 -tl 60000 -o i%04d.jpg -t 28000000

(Having to time everything in milliseconds is tiresome.)

On my iMac this converted the stills to MP4/10 frames-per-second:

  ffmpeg -r 10 -i i%04d.jpg clip.mp4

I could have done this step on the Pi but it would have taken a lot longer. BTW: the video quality from this step was very good -- not like the above.

Saturday, January 10, 2015

70: PWM -- Another Reason to Front-end Your Pi with an Arduino

I just discovered the joys of Arduino PWM (pulse width modulation). Easy on my Nano, except for 1 GPIO pin is's a nasty kludge on the Pi. Ha! (I listed USB-connected source code for Pi and Arduino back in Post 66.)

BTW: PWM is useful for things like dimming LEDs. In my case, I wanted a user to notice differences in output of mini-motor vibrators (e.g., from Adafruit). You have 256 output levels: 0=none(OFF), 127=half, 255=full(ON).

P.S.: While Pi prices are pretty standardized, Arduino prices are all over the place. I've noted Internet-listed Nanos (my favorite model) at anywhere from over $30 down to $3.30 (no cable, soldering required, delivery from China).

Thursday, January 1, 2015

69: To Catch a Thief
(Raspberry Pi Security System)

My daughter's dog is an inveterate thief of any food left within even implausible reach. The previous time we dog-sat for him he managed to steal over a dozen home-made cookies. So I decided to catch him in the act using my Pi+camera+Python program. I have a (fairly) portable Pi system:
Notes on the configuration:
  • The 12,000mAh battery will power the Pi for about 10 hours. Unfortunately the battery can either charge or discharge but not both at once. Otherwise it would make a very nice UPS (uninterruptable power supply).
  • As shown, it has LED output, PIR and Pi camera input and a 7-segment display. On the side there is a Cat5 socket (provides 8 wires for remote sensors) and a pair of relay switches.
  • I use the speaker for text-to-speech output.
Anyway, I baited the kitchen counter with a piece of meat and set the porta-Pi aimed at the counter. On my first attempt my program just used the camera to detect motion. About once per second the Pi can take a grayscale 120x90 pixel image which the program compares pixel-by-pixel with the previous image. When more than an arbitrary number if pixels have changed by more than an arbitrary difference then the program takes a full-res image and saves it to the SD card filesystem.

This first test failed for 2 reasons: a) the dog ignored the bait; b) while we were away for about 3 hours the sun went under a cloud and back out about 100 times and my dumb program decided that each such change was "motion."

So, for my second try I added the PIR device -- logic as follows:

    IF the PIR detects motion AND the 2 camera images differ THEN store the high-res image.

This attempt failed too: at  a distance of about 12' the PIR didn't notice the 30-pound white dog (but he stole the meat).

I need a better motion detector.

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).