Monday, December 21, 2015

30: "Smart Home," "Internet of Things," Blah, Blah

Cnet has equipped a house as a demo Smart Home. I recently read their bit about protecting the house from water main flooding. Their article mentioned a wifi-enabled solenoid valve which could be used shut off the input supply. The suggested device was listed as $400. That figure got my attention.

Last summer, I installed a Particle Photon-based system for my granddaughter's demonstration farm. The setup includes 2 soil moisture sensors and a solenoid-operated water valve. I initially installed a 1/2" plastic valve for irrigating the 100' x 30' hoop house. That turned out to be too small so I changed it for a brass 3/4" model.

Anyway, here's my version of how to protect a home from water damage caused by a pipe breaking, water heater leak, etc. Note: Wifi and Internet are assumed in all cases.

Cnet's device--

1. Wifi-enabled solenoid water valve, 1": $400
2. Pipe adapters: $30
3. Plummer to cut it into main service pipe: $150?
4. Wifi-enabled water sensor: $50?
5. Power supplies: 5v: $5, 12v: $15?
6. Controller for house: ?
Total: $650+

My way (version 1)--
1. Solenoid water valve 1": $40
2. Pipe adapters: $30
3. Plummer: $150
4. Water sensors: $5
5. Power supplies: 5v: $5, 12v: $15?
6. Particle Photon controller: $20
Total: $250

My way (version 2)--
1. Stepper motor to rotate existing house turn off valve 90 degrees: $40
2. Motor mounting bracket + 2 limit switches: $20
3. Plummer: (not needed)
4. Water sensors: $5
5. Power supplies: 5v: $5, 12v: $15?
6. Particle Photon controller: $20
Total: $110

Sunday, December 13, 2015

29: Portable Sensors

I have ideas for several of these. The one I'm building just now will provide temperature, humidity,  dew point and soil moisture readings from a flashlight-sized device. Here's the breadboard mess:


And this is my crude wooden enclosure (soil probe not shown):


I'm using an Arduino Nano and a DHT22 temperature/humidity sensor (etc.). The readout is to a 4 digit 7-segment LED. Power from a 9-volt battery. The cheap 4-digit LED takes all of the digital pins 2 through 12. So I have just one left for the DHT (unless I use TX and RX which leads to problems). The moisture probe uses analog, luckily.

My Sketch displays each reading for a second at a time, as in-- "F 74", "h 39", d 42", "S 11" (I can fudge those 4 letters in 7 segments).

I'd really like to find a source for enclosures so I don't have to waste time building crappy ones of my own. Any suggestions?
28: More About Secure Wires

Way back in my Raspberry Pi blog (http://dicks-raspberry-pi.blogspot.com) post 59 I discussed "Bare Conductive Electric Paint." I had hoped to be able to draw circuits on paper with the stuff. Well, not quite. But it was a sort of conductive glue (slow drying, not very strong).


Anyway, the stuff has stiffened up in the tube to where it won't come out the narrow spout anymore, but now I have a new use: sticking breadboard wires M-to-F or M-to-breadboard. Just dip the wire (M) end in the "paint" and insert as usual. And after 20 minutes the connection will be pretty secure AND the contact will be good. Also, since the glue isn't too strong, you can get it out if you need to make a change.

Note that wisely, most glue is insulating, not conductive -- probably a good idea.

Friday, November 6, 2015

26: A More Secure Breadboard Setup for Particle Photon or Arduino Nano
-- revised: Nov 25, 2015 --

I hate loose wires, also not fond of soldering. So, browsing Aliexpress I found 2 possibly useful devices: 8-wire screw terminal strips (I got 4) and a bunch of 2-wire spring clips.

Terminal Strip, Photon, Spring Clips

Anyway, I like both connectors. The screw strip is a tad over-kill. I probably won't run 220v through it. I particularly like the spring clips -- they are pretty strong. And flexible in number. And cheap: $1.30 for 10 pair. REVISED: I tried getting more than 1 wire clamped in a spring clip -- Sorry, not reliable (and not very useful, otherwise)!

I'll probably mount the whole setup on an about 8" square of 1/2" plywood, screwing the breadboard and connectors to the board. There should be room left for a 4-switch relay.

Monday, November 2, 2015

25: Particle Cloud vs. Daylight Savings Time

Clock time is important to my "live" Photon system (see posts 20, 23). Imagine my surprise in finding the time off by an hour on Nov. 1. Sloppy me. Particle Docs is explicit that the Time.zone() function does not adjust for Daylight Savings.

Lucky for me, I have a Linux/Raspberry Pi to back me up. Here's a little shell script that can correct the time in my Photon program:

thisF=your-function-name
photon=1234... # your Photon's ID
accessT=5678... # your access_token
a=`date | sed -n 's/.* .\([DS]T\).*/\1/p'`
if [ "$a" != "ST" ] ; # previous WAS "DT"
then
  v=-5  # Standard Time (value less than GMT)
 else
  v=-4  # Daylight Time
fi
# This can tell the Photon
curl https://api.particle.io/v1/devices/$photon/$thisF \
 -d access_token=$accessT -d "args=$v"

Unix/Linux have a scheduling program called cron. And each user can have a personal set of scheduled programs accessed by the crontab app.. If the above shell code is in a file called "set-tz" then this crontab entry will execute it every Sunday in October, November and March:

# min hr dom mo dow command
...
0 3 * 3,10,11 0 sh set-tz

Read it as: 
"at zero minutes after the hour, 
3am, 
any day-of-month, 
March, October, November, 
Sunday
Then execute set-tz."

Ugly, but looks isn't everything.

Friday, October 9, 2015

24: More Photons

I received 2 more Particle Photons this week. Seems like a bargain: $19 each plus $6 shipping, 12 day USPS delivery.

I had no trouble getting them setup using the iPhone App. I now have a total of 5 Particle devices: 1 Core and 4 Photons.

I succeeded in remote updating my live system without a hitch. Why not. Even when the Photon was 2 feet away the recompile/download was going through the cloud. So what's a hundred miles?

But this doesn't mean I have no complaints. Software development is a bear. Compiler error messages only mean that you have made a mistake. They rarely, if ever, point out where the mistake was. My advice: write your programs a bit at a time.

Luckily, source programs for "smart controllers" are generally short.

Wednesday, October 7, 2015

23: About My "Live" Photon System

I've had a blogspot "comment" (question) about how I implemented the Photon control system at my granddaughter's farm (see post 21). Well, it's kind of complicated.

The program on the Photon is written in C++. It was initially only 80 lines of code but has grown to over 200 lines. It will probably get longer still. It has 2 main parts: 1) In the "loop()" all of the sensors are recorded in a Particle.variable, and time readings from the "cloud" control the electric fence and make sure that the water is not on for too long; b) a Particle.function can be called to change relays or override timed events.

I wrote a PHP program for the Internet interface. It is fairly complicated and only works because my hosting service is Linux-based and permits execution of the "curl" command to communicate with the Photon. Many servers would not allow this.

I also have a Raspberry Pi running Linux. I use the "crontab" scheduling program to check the status of the Photon. It is this Pi that can send e-mails or text messages if something goes wrong (hoop house too hot or cold, power failure, etc.).

Of course, the Photon's location has to have reliable wifi/Internet service. I had to add a wifi amplifier for my "live" system.

Sunday, October 4, 2015

22: Name Change

I'm going to change the name of this blog to--

dicks-Photon-Arduino.blogspot.com

-- because it's mostly about my Particle Photons. Duh.

Friday, September 18, 2015

21: Battery Backup, Revised Again
updated 9/26

After my failures with the Adafruit Powerboost 1000 (post 16), I complained at an Adafruit forum. Their response as  that I should have used a Powerboost 1000C instead. Note the subtly added letter "C". So, gritting my teeth, I paid $19.99 (plus their pricey shipping) and tried again.


I let this setup run for over 24 hours powering either a Raspberry Pi (drawing about .4 amps) or a Particle Photon (drawing 1/8th as much) and both worked fine. I could disconnect external USB without the computers noticing but pulling the battery plug caused both processors to restart. Not nice but not a deal killer.

Note the input power LED in the image. If you aimed a photo sensor at it, your program could detect external power failure. You would  then have time to send out a text message and shut down "gracefully" whatever that means.

Update: The setup ran a Raspberry Pi for over 2 weeks.

Wednesday, September 16, 2015

20: I Installed a LIVE System!
(after 2+ years of messing around)

Two weeks ago I installed Particle Photon in my granddaughter's farm hoop house (they used to be called "green houses"). It is programmed to support 2 temperature sensors and 2 soil moisture sensors. It provides control of 2 switched devices: an electrified deer fence and a water valve for drip irrigation. Here's the smartphone web page image:

as of 10pm, September 15

Data comes from my Photon program via Particle's "cloud" interface. The electric fence is normally turned on and off by time-of-day (the cloud provides UNIX-like time functions). But that timing can be overridden by the web page above (password secured).

I originally planned to implement this using a Raspberry Pi but the $19 Photon's simple web interface trumped the Pi's many advantages (especially the mature software development environment).

However, the Pi is not all together out of the picture: a Pi-based cron task checks on the Photon every few minutes and sends text messages if anything has gone wrong.

The Photon, sensors, switches and wiring cost under $70. My control program in C++ is about 80 lines long.

Does anyone know of a reliable motor setup for safely rolling the sides of the hoop house up and down (to control inside temperature)?

Thursday, August 13, 2015

19: Solenoid Water Valves

My new mistakes:


1. The image above shows 2 seemingly identical .5 inch plastic valves. But the one on the right has tapered threads (about $10 from Adafruit). The left (cheaper) one did not. To get the brass fittings screwed on I had to carefully file down the end threads so I could get the adapters screwed on without butchering the plastic. Very time-consuming -- and irritating.

2. Also, why did I go cheap? For about $25 I could have a brass valve to go with the pair of $15 fittings. And the whole thing would likely have been more reliable.

Tuesday, August 4, 2015

18: Photon vs. Core

As advertised, the Particle Photon seems to play nicer with wifi. It connects quicker when plugged in and stays connected (my Core occasionally lost wifi and had to go through the startup mode again). My software development problems (clunkly build works, Particle Dev doesn't) haven't been fixed, at least for the Mac app.

BTW: I've gotten interested in Particle's cloud-provided Time functions. It's not like Raspberry Pi's crontab scheduling but you can program things to occur at particular times. There's Time.hour() for the current 24-hour clock hour, for instance. Easy access is available to day-of-week (e.g.) and all of the usual Unix/Linux functions -- accuracy refreshed from the cloud. Makes a Photon much more than a "smart controller."

A Particle advantage I hadn't thought of: I'm about to install a Photon system in a farm hoop house 100 miles away. If the running program needs modification I can do it from here!

Wednesday, July 22, 2015

17: Xmas in July -- I Received My 2 Particle Photons

Here's what you get for $19:
the Photon is 1.5" long
(they haven't totally erased the original "Spark" name yet)

See https://store.particle.io/?product=particle-photon for details. I've had the earlier $39 Core model for a few months. Supposedly the Photon can run the software I previously ported from Arduino. Also, in addition to being half the price the Photon is supposed to use the latest WIFI chip (more reliable?).

But there has been good news and the other.

Good news: The Core has been very reliable. Once I got it connected to my WIFI I've been able to communicate with it from anywhere. It's like an Arduino Mega but faster, more memory (but with fewer GPIO pins), the physical size is like an Arduino Nano and it has built in WIFI. Particle's "cloud" interface makes their "smart controllers" a lot smarter than an Arduino. I have my Core connected to the Web. I can read sensors and control relays from a simple web page.

Bad news: Documentation is sketchy -- well, you'd kind of expect that with something this new. Program development is painful. I started with their web browser interface: particle/build. Finding my coding mistakes was a challenge. On one 80 line C++ program I left off a semicolon on the next to last line. I got 72 lines of error messages; line 71 finally told me about my mistake. Once I got to 20-some source files having them up in the cloud became cumbersome. 

So I tried switching to "Particle Dev.app" programming where you keep your source file on your local disk. I could write a book about this but sufficient to say that since July 1 I have yet to be able to access a program compiled this way.

Also, I fear that Particle is skimping on their support force. At first, I got responses to my foolish problems/questions in a day. Lately (with changing to Dev.app) it can take a week or more.

* * *

I've been programming for 50-odd years. I should be used to this kind of thing.


Tuesday, June 30, 2015

16: Battery Backup
Post 11 corrected
** revised again 7/16/15 **

When I tested my battery backup circuit (post 11) I failed to let the systems run on both USB input and battery for long enough. Turns out with 5V/1A input from my USB hub the setup drains the battery. And when that happens the USB output drops to 4.10V. Not nice. However, USB input of 2.1 Amps seems to correct the problem.  Wrong again: 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).

Gory details at http://forums.adafruit.com/viewtopic.php?f=15&t=76014


Most USB hubs don't provide 2.1A outputs. So I ordered a 5-pack of 2.1A wall plugs. I'll let you know how they work long-term.

Saturday, June 13, 2015

15: Soil Moisture Sensor: Arduino and Particle Core
-- revised --

I programmed this first on an Arduino Nano. Pretty easy. My guesses at wiring did no damage. The "sunkee soil hygrometer" (probably meant "hydrometer") was mostly marked in Chinese. One tricky part: once you start the program the probe device is on all the time -- drawing current. I first considered turning it on & off with a transistor. But then I wondered, why not just use a digital pin. I don't know if this is as safe, but it's simple and it works. In addition to short patch wires, I tested this using a 50' CAT5 cable between the probe and the interface. It worked fine. See post 27 at http://dicks-raspberry-pi.blogspot.com/.

I had expected these things to be bigger. 
Probe points only about 2" long.
Adjustment screw only useful for digital (ON/OFF) output.

Here's my Particle Core code. The Core can be read anywhere wifi is available (if you know the codes). So the Core can be remote from my Raspberry Pi control program.

/* device: "sunkee soil hygrometer" [SP?]

2 wires from probe "YL" & "69" (?) to interface board 
  no-label<->(YL) & GND<->(69?)
4 wires out to Arduino: "VCC" "GND" "D0" "A0"

Arduino or Particle/Core -- just guessing:

VCC -- 5v (or 3.3) 
  Arduino 5v: analog range=1023:200 (10 bits), 
  Core: analog range=4095:2000 (12 bits)
GND -- GND
D0  -- unused: just on/off
A0  -- analog pin
*/
int soil = A3; // read the device
int power = D1; // turn power on just for the reading

void setup() {
    Spark.function("soil1", Soil); // Core-only function
    pinMode(soil, INPUT);
    pinMode(power, OUTPUT);
    digitalWrite(power, LOW);
}

void loop() {
    // not used
}

int Soil(String command) {
    digitalWrite(power, HIGH); // turn probe on
    delay(200); // let it settle?
    int raw = analogRead(soil); // high=dry, low=wet
    delay(200);
    digitalWrite(power, LOW); // turn probe off
    int read = map(raw,4095,2000, 0,20); 
    return read; // return reading between 0 & 20
}

Thursday, May 14, 2015

14: Spark is now Particle (?)

See
http://spark.cmail1.com/t/ViewEmail/t/2CCE5B6961CA5D4E/9BDBDA8F3EFB0BE0C67FD2F38AC4859C

They say 681 other trademarks created confusion. Maybe. Maybe someone offered to sue them. Still very interesting company.

(why not "webino" or "cloudino")

Sunday, May 3, 2015

13: LED Bar Graph

I bought 3 of these from All Electronics (as I recall). $.50 each.
I assumed these were a 1-piece item, but nope:
note the +/– markings
Each separated LED is dimly marked too:
Too bad they didn't build the ground-side resistors in. Otherwise, the 2 pins neatly fit in adjacent breadboard rows -- and make for tidy wiring.

Wednesday, April 29, 2015

12: Device Review
Apr 25, revised: May 2, Aug 1, Nov 25, 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 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 (radio frequency) read & write - A to R
  • 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

Tuesday, April 7, 2015

11: Uninterruptible Power (the other UPS) for Arduino, Spark Core or Raspberry Pi
* revised Apr 17, 2015 *

There seems to be precious little help on line for this even though it turned out to be pretty easy. I watched --

I got my parts from Adafruit (charger: $6, powerboost: $15, 1200mAh battery: $10, plus their irritating shipping charges).



I tested this with an Arduino Nano--
both external power and  battery (note red LED*)

And with my Spark Core--
just battery

You can connect/disconnect the battery any time. And this will work for Raspberry Pi just as well (REVISED: probably, if the system doesn't draw more than 1000mA -- see dicks-raspberry-pi.blogspot.com/).

Also REVISED: When I let the Spark run until the battery ran down there was a problem: The Powerboost didn't just quit cleanly. The boost/Spark stopped/restarted, stopped/restarted (voltage hiccups?). I suppose that when the boost stopped drawing current then the battery recovered a bit. Anyway: not nice. The Powerboost has an Enable pin (labeled (EN). Grounding that will stop things cold. Then how does it restart? What un-grounds the EN? See * note below. Kudos to Spark that the Core survived undamaged! Note: the Powerboost did not survive (Adafruit replaced it).

Considering the way that (non-hobby) "programable controllers" are used, I'd think that a UPS setup like this would be about Arduino Lesson 3!

___________
* If you aimed a photo resistor ($1) at the charger's red LED external power indicator then you could detect power failure and shutdown gently (but HOW and HOW-TO-RESTART?).

Tuesday, March 31, 2015

10: Spark Core Battery Drain

I don't have a meter on input but the 12,000mAh battery shown in the post 9 image is only down 25% after about 30 hours. The same battery will only run a Raspberry Pi model B (and similar devices) for about 24 hours.

Sunday, March 29, 2015

9: Spark Core/Imitation Arduino

I've managed to build a sketch for the Core that lights an LED, switches relays, reads a photo sensor and reads temperature from a TMP36. These activities are controlled from a Raspberry Pi and the results are posted on the Web. Here's a messy pic of the Spark setup powered by a battery.

(the cludged-up 9V flashlight (lower-left) is to prove the switch is working)

Here's the sketch:
int led = D0;
int relay1 = D7;
int relay2 = D6;
int photo = A0;
int tmp36 = A1;
int rval;
int r1state = 0;
int r2state = 0;

void setup()
{
    Spark.function("spark", getSpark);
    pinMode(led,OUTPUT);
    pinMode(photo, INPUT);
    pinMode(relay1, OUTPUT);
    digitalWrite(relay1, HIGH); // backwards for "normally closed" relay
    pinMode(relay2, OUTPUT);
    digitalWrite(relay2, HIGH);
    pinMode(tmp36pin, INPUT);
}

void loop() {
    // not used
}

int getSpark(String command)
{
    int raw, f;
    float v, c;
    
    int cmd = command.toInt();
   
    blink(cmd); // for my visible feedback
    switch(cmd) {
    case 1: // return photo sensor analog reading
        rval = analogRead(photo);
        return rval;
    case 2: // switch relay 1
        if(r1state == 0) {
            digitalWrite(relay1, LOW);
            r1state = 1;
        } else {
            digitalWrite(relay1, HIGH);
            r1state = 0;
        }
        return r1state;
    case 3: // switch relay 2
        if(r2state == 0) {
            digitalWrite(relay2, LOW);
            r2state = 1;
        } else {
            digitalWrite(relay2, HIGH);
            r2state = 0;
        }
        return r2state;
    case 4: // return TMP36 temperature in F
        raw = analogRead(tmp36);
        v = (raw * 3.3) / 4095;
        c = (v - 0.5) *100;
        f = (c * 9.0/5.0 + 32.0);
        return f;
    default:
        break;
    }
    return cmd;
}

void blink(int n)
{
    int i;
    
    for(i = 0; i < n; ++i) {
        digitalWrite(led, HIGH);
        delay(500);
        digitalWrite(led, LOW);
        delay(500);
    }
}

Monday, March 16, 2015

8: My Spark Core

This wasn't too painful. The $40 Core came in a cute box complete with cable and half-size breadboard (neither of which I needed).
Spark's web info is nicely finished and things work almost as smoothly. However, the idea that the Core is "Arduino compatible" is a stretch. First off, the processor is different; it's 4 times faster and has 4 times the memory, but fewer ports. The C Language programming syntax is the same but not the libraries. Also, a C "int" variable is 32 bits, not 16. Non-trivial Arduino sketches will not just plug-and-play. There's no Arduino-like app for my Mac. One programs from their www.spark.io/build web-based interface. Once you get the Core set up with your wifi & Internet (both required) the USB cable is mostly just for power. When you are ready to test a program you click the "flash" button and the source gets uploaded, compiled and downloaded. This takes longer than from the Arduino.app but for the smallish programs one usually writes for a "programmable controller" it's not a big deal.

Tuesday, March 10, 2015

7: A Compact, Secure Way to Mount a Nano
(modified 9/22/15)

I got a couple of these through Aliexpress. Without wires coming out the edges this thing is less than 1.5" wide.

Each Arduino pin is brought out to a screw-down connector. Screw the patch wires down and the whole thing is much more rugged than using a no-solder breadboard. The unit came in pieces -- 60 solder joints to complete it. Yuck. Testing them all was a trial.

Another mounting trick I'm interested in: use a 40-pin ZIF (zero insertion force) connector.

I'm not sure if this will work -- is it wide enough? But if the Nano fits with width to spare then you could put the Nano at one end and also clamp jumper wires out to sensors, etc. NOTE: Doesn't work!

Sunday, March 8, 2015

6: Question about RFID-522 Reader

I wanted to do the "unlock the door using an RFID chip" trick. So I got a device from Sainsmart.

http://www.sainsmart.com/arduino/arduino-components/sainsmart-mifare-rc522-card-read-antenna-rf-rfid-reader-ic-card-proximity-module.html

Besides the sensor the package handily included one-each RFID keyfob- and credit card-type test devices.  I downloaded a library and sample sketch from the Internet, wired up the device and -- it didn't work. I downloaded a different library and sketch -- also didn't work. I was trying to test using the keyfob. Then I accidentally tested using the card. Worked! It had always worked.

I complained to Sainsmart and they eventually sent me a whole 2nd setup (new device, new fob, new card). Both cards work, neither of the fobs are recognized.

Anyone understand this problem?

Here's my sketch:

/*  Nano pins:
  RST: Pin 9
  SS: Pin 10
  MOSI: Pin 11 
  MISO: Pin 12 
  SCK: Pin 13  
*/  
#include <SPI.h>  
#include <RFID.h>  
#define SS_PIN 10  
#define RST_PIN 9 

RFID rfid(SS_PIN,RST_PIN);  
int serNum[5];

void setup(){  
  Serial.begin(9600);  
  SPI.begin();  
  rfid.init();  
}  

void loop(){
  int i;
  
  if(rfid.isCard()) {  
    if(rfid.readCardSerial()) { 
      for(i = 0; i <= 4; ++i) {
        Serial.print(rfid.serNum[i]); Serial.print(" ");
      }
      Serial.println("");  
    } else {
      Serial.println("nr");
    }
  } else {
   Serial.println("-");
  } 
  rfid.halt();
  delay(1000);  
}   

Friday, March 6, 2015

5: Have You Heard of the Spark Core?

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

Saturday, February 28, 2015

4: More on Gas Sensors
* revised 3/2/15 *

Things I've learned since last post:
  1. The timing for letting the sensor heat up in my last post is wrong. I did 50 tries waiting 4 seconds between each. 50 is ok but 5 second wait is better.
  2. The usual web examples suggest that the 5v to heat up the sensor needs too much current for it to come from the Arduino 5v pin. So I tested both my MQ-4 and MQ-7 both ways -- with external source and from the 5v pin. Both ways worked with the following caveat: the base (heated up) values were higher (both MQs) with Arduino juice (30%-ish). So why bother with external? Wrong again! Seemingly any change on the current load on the Arduino's pins changes the warm-up and base readings from the MQs. Back to external 5v (Drat!).
I want to mount my project as a hand-held portable unit like the diagram below. But I'll need to do 2 things to make this work: a) put a switch on the 5v lines to the MQs (so as not draw both currents at once) and b) de-solder the actual sensors from their circuit boards so I can mount them as shown.


the size of a flashlight
Comments?

Wednesday, February 18, 2015

3: Gas Sensors

I purchased 2: an MQ-4 (methane) and MQ-7 (carbon monoxide/CO). I shopped around for wiring and code examples and then reworked it for my sensibilities.

The MQ-x's need to heat up before their readings stabilize so I chose to power them separately from the Nano. I stripped one end of a USB cable and soldered a jumper to the red and black wires (i.e., 5v & ground). The wiring is simple. There are 4 pins on my devices, labeled G, AO, DO & V.

Wiring:
  USB 5v to V
  USB ground to G
  Arduino pin A0 to AO

— the adjustment screw didn't seem to do much —


And here's a sketch:

// Works with MQ-4/methane & MQ-7/CO
// Power to sensor external (USB) 5v->V pin & GND->G pin; 
// AO pin to Arduino A0
const int LedPin = 6;
const int gasSensor = A0;
int sensorValue;
int baseValue;

void setup() {
  int i, val, last=-1;
  pinMode(LedPin, OUTPUT);
  Serial.begin(9600);
  // wait for sensor to warm up -- and value to stabilize
  for(i = 0; i < 50; ++i) { // a guess about waiting
    val = analogRead(gasSensor);
    // Debug only
    Serial.print(i);Serial.print(","); Serial.println(val);
    if(val == last) break;
    // blink LED to indicate sensor warm up
    digitalWrite(LedPin, HIGH);
    delay(100);
    digitalWrite(LedPin, LOW);
    delay(4000); // 4 seconds
    last = val;
  }
  baseValue = val + 10; // just a guess
}

void loop() {
  sensorValue = analogRead(gasSensor);
  Serial.println(sensorValue); // Debug
  if (sensorValue > baseValue) {
    digitalWrite(LedPin, HIGH); // I need to show multiple levels
  } else {
    digitalWrite(LedPin, LOW);
  }
  delay(1000);
}

I've also successfully (seemingly) programmed an RFID reader. My sensor came with 2 testing samples: a keyfob and a credit card. I copied different sketches from the Internet and nothing worked. It turned out that my code wasn't at fault. I just tested using the fob. When I finally tried the card my sketch worked. Bad fob! There is a lesson here somewhere.

Monday, February 16, 2015

2: How the Arduino "Sketch" Works (maybe)

For C or C++ programmers the hidden code behind the sketch probably works (or can be visualized) like this:

void main() {
setup();

while(1) {
    loop();
}

Of course this doesn't explain other stuff you can add -- like this:

//optional #include statements
//optional #define statements
//optional variable declarations

setup() {
//whatever
}

loop() {
//main code -- an exit() just reexecutes loop()
}

//optional user-written functions


Saturday, February 7, 2015

Post 1: The Reluctant Arduino Programmer

I sort of backed into Arduino. In April 2013, I got my first Raspberry Pi Model B. Since then I have spent a few hundred hours (many frustrating) learning about programming sensors on the Pi. See my other blog--


--where, even there, I wandered into the forest of Arduino (posts 54, 66 - 68, 70). Even though a 32k/16mhz Arduino has 1/30th (?) of the power of a Pi B+ (1/100th of a 2B?) and you have Linux, and can program in Python and Bash and have the services of Crontab -- even so there are things that are better done on a no-OS Arduino in C++. These include:
  1. Getting accurate readings from devices that have to be read in "real time."
  2. Analog is built in and easy to program (why not on the latest Pi?). Also PWM.
  3. What if you want to build something that fits in your hand and runs on a 9v battery?
  4. Also, it's easy to use Arduinos as Pi front-ends. You can extend sensors 16' with USB or a few hundred feet wirelessly with cheap RF.
  5. The program memory on an Arduino is not lost when power is removed. It's flash memory -- like flash drives. If you download a program now (called a "sketch") it will run again a year from now when you supply power. So you program and debug using USB from Mac/PC/Linux then disconnect. When you connect a battery you're back in business.

I probably should mention the programming side of this. While my only formal training in electricity was 10th grade Physics, I have been programming since 1961. And I was at Bell Labs when Unix and C language were invented. I've written thousands of lines of C over the years. No biggie.
Arduino Micro & Nano Models
plug directly into a breadboard!

Disclaimer: I've never had a regular Arduino Uno. I've had a Micro model from Adafruit (official unit with the infinity symbol, $25). And I've had several clones (does anyone know how many of these have been built?). I've paid anywhere from $17 down to $3 for the clones. The Micro and the 2 $3 ones "don't work." 

Don't you hate it when some friend tells you their computer "doesn't work." To be specific: the problem is that when I plug them in to a USB port on my Mac no device appears in the /dev (device) list. I think you'd find it hard to find this documented, but apparently every Arduino is supposed to have a unique device ID number burned in somewhere. Anyway, if the Mac can't find the device then it can't download code or get output back. The Arduino may be working but it's useless.

Here's the idea that got me into the Arduino--

My ill-conceived "E-Cane"

My electronic cane for the vision-impaired was a learning experience but it only worked part time -- and part time isn't close to good enough. Here's some reasons that my device didn't work:

  • I tried 5 different rangefinder devices and none of them were good enough. I finally settled on a Sharp active IR unit but it is not accurate enough (especially held at an angle) and has too wide a field. I think that for big bucks the right sort of device could be built -- but not with my budget.
  • The Arduino is billed as a "programmable controller" (not a "computer"). I learned that is too true. The first thing I programmed was the accelerometer (so I could tell what angle the user was holding the e-cane). But it turns out that the Arduino's 16mhz processor is too slow to read the rangefinder and the accelerometer in a reasonable length of time. So I dumped the accelerometer.
  • The vibrators I got from Adafruit turned out to be kind of feeble (stronger ones are called "cell phone vibrators). Another problem arises from the fact that the vibrators are really tiny electric motors with off balance rotors. I thought I could spin the devices for 100ms and 500ms and that a user could tell the difference. Not so. Once you start them spinning they stop when they feel like it. Later, I realized that I could use PWM (pulse width modulation) to make the vibrators communicate better.
New topic: I recently got something called a "Terminal Adapter" (for the Nano) from Aliexpress. It was a lot of soldering (60 wires) but it works great; no breadboard needed for simple wirings and device wires are screwed down tight.
Here's a minimal test setup

And here's the sketch:
int LedPin = 6; // a digital + PWM pin
int ct = 0;

void setup() {
  pinMode(LedPin, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  if(ct >= 250) ct = 0;
  ct += 10;
  Serial.println(ct);
  analogWrite(LedPin, ct); // vary brightness with PWM
  delay(200);
}