Saturday, August 27, 2011

It Works! Remote Controlled Irrigation via Arduino

Success! I can now remotely turn on my sprinkler zones via my Arduino-powered web server.

The picture does not do justice to the amazing amount of wiring nuts I used to make this work. I think there are nearly a dozen of them holding all the wires together.



I did not manage to hook the Toro controller's 24-volt power supply into my rig. Sharp-eyed readers might be able to spot the two 9V batteries I clipped into my valve control circuits as a temporary power supply.

Anyway, it works! Awesome! Now to write the native Android controller app...

Edit: I have since torn down this setup so that I can mount my Arduino hardware on something a little more substantial (and less flammable) than cardboard. Stay tuned...

Friday, August 19, 2011

Google Authorship with Blogger

In the last couple of weeks, I have taken an interest in Google's attempt to register authorship for articles published on the web. This initiative allows web authors to essentially claim ownership of a particular piece of content that they publish.

I think this a great way to recognize folks who are serious about the content they publish on the web and a way to help folks looking for good content to find it faster. I'm all in for that. Now, how to get it working?

Caution: This process is a bit fiddly using Blogger, which is ironic 'cause it's a Google web property, right? I have sent some feedback to the Googlers who will hopefully make this easier in the future. If you are not comfortable editing raw html, I recommend you wait until the "register my authorship" option (or whatever they call it) is implemented in Blogger. Also, the solution is not suitable for a multiple-author blog. Fair warning. If you manage to get it working in that scenario, please leave a comment as to how you accomplished it.

How to Plug into Authorship with Blogger

There are a few steps you need to complete to get authorship set up:
  1. Setup a Google Profile (you don't have to be on Google+ to do this). If you are on Blogger, you probably already have one.
  2. Add your Blogger site to your Links list. Make sure you:
    • Click the This page is specifically about me option.
    • Set the visibility of the Links list to Anyone on the web.
  3. For each page of your blog, make sure there is a link to your Google Profile, and make sure the anchor text starts or ends with "+". (See specific instructions for Blogger in the next section.)
  4. Test your implementation using this page.
  5. Fill out this form for the Googlers.
  6. Wait.
  7. Wait.
  8. Wait some more.
  9. Obsessively run Google searches on your blog posts.
  10. Finally see your mug next to a search result, declare success and drink a celebratory beverage of your choice.

Add a Google+ Profile Link to Your Blogger Byline

Here's how I changed my byline to include a link to my Google+ profile. You have to manually edit your Blogger template to do this.
  1. Log into Blogger
  2. Go to your blog dashboard and click Design > Edit HTML)
  3. In the Edit HTML page, go down to the Edit Template section and make sure you click on the Expand Widget Templates option on the top right of the edit box.
  4. In the edit box, find the section containing a div with class='post-footer-line post-footer-line-1'
  5. Wrap the <data:post.author/> tag with an "a" tag containing a url to your Google Profile, followed by "?rel=author":
    ...
        <div class='post-footer'>
        <div class='post-footer-line post-footer-line-1'><span class='post-author vcard'>
            <b:if cond='data:top.showAuthor'>
              <data:top.authorLabel/>
              <span class='fn'>
                <a href='https://plus.google.com/103507786235300238642?rel=author'>
                +<data:post.author/></a>
              </span>
            </b:if>
          </span> <span class='post-timestamp'>
          ...
    
  6. Also, you need to put a "+" at the beginning or end of the anchor text for Google to accept this as a valid author reference. (No, that "+" is not a typo; It's required.)

Props to the Kevin & Amanda blog for providing the blogger signature template tips that lead to this solution.

Further Thoughts

As a writer, I think this a great initiative for content producers to get credit for their contributions to the sea of knowledge that is the interweb. I think it also has the potential to help folks looking for information to sort out the real sources of information from the increasing numbers of republishers, SEO hackers and link farmers out there.

If that describes you, then hey, I realize we all need to make a living, but ask yourselves; are you actually contributing any new value to this great interweb thing we all share? If not, then maybe it's time to rethink your strategy.

Wednesday, August 10, 2011

Arduino Remote Control Irrigation Rig Update

Last night I tried hooking up my Arduino irrigation remote control rig to all three of the SeeedStudios Relay Shield I bought a while ago. Now here's a nice hack:



I took a piece of cardboard and some unused 1/8 inch rivets, poked the non-rivet end into the cardboard and set the Relay Shield on top of them using the mounting holes. Not a good long term solution, obviously, but it kept the boards from sliding a round while I was wiring everything up.

This project is going to need a much more solid base because the wires for the irrigation system are pretty heavy. I'm thinking about getting a nice, thick sheet of clear acrylic for mounting. I will also have to go find a screw terminal block and use that in between the relay boards and the irrigation wire. Fun! And, I also need to figure out how to get an ethernet connection into my garage where the current irrigation controller lives. Heh.

Arduino Pin Use Limitations: Pin 10, 13

I have a total of 12 relays I can control with the Relay Shields, and I was hoping to use pins 2 to 13 for that purpose. Well, trying that didn't go so well. Apparently the Arduino Ethernet Shield lays claim to pin 10 and so I cannot use it for output. Also, pin 13 (which is connected to the ADK board's LED) gets flashed a lot during program uploads. So, if I connect one of my relays to pin 13, it gets opened and closed dozens of times a second while I'm uploading a new Arduino program. That's going to cause unwanted wear and tear on the relay and possibly overheat it as I noticed when connecting the relays to pin 0 and 1.

So now I'm down to using only 10 relays of my 12. That's more than enough for my project, and if I really need them the ADK lot's more digital outputs. I was hoping to be able to control twelve relays with just the pins available on a Arduino Uno though. Maybe I can use the analog pins to control the relays?


Monday, August 8, 2011

Deleting Files from Android SDCard

Today I needed to delete a bunch of files off of my phone because some rogue test program I was running generated several hundred image files in the root of my SDCard. Here is program I wrote to get rid of them:

package com.example.android.filemanagement;

import java.io.File;
import java.io.FilenameFilter;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;


public class FileCleanupActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

       Button b = (Button) findViewById(R.id.go);
        b.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {

				// Delete those files!
		        Iterator it = listFiles().iterator();
		        while (it.hasNext()){
		        	it.next().delete();
		        }
				
			}
        });
        
        TextView tv = (TextView) findViewById(R.id.file_list);
        
        StringBuffer sb = new StringBuffer();
        Iterator it = listFiles().iterator();
        while (it.hasNext()){
        	sb.append(it.next().getName() + "\n");
        }
        
        tv.setText(sb.toString());
    }
    
    private static List listFiles(){
    	
    	File[] files = Environment.getExternalStorageDirectory()
    					.listFiles(new ExtensionFilter("jpg"));
    	
    	return Arrays.asList(files);
    }
}

class ExtensionFilter implements FilenameFilter {

	private String ext;
	
	public ExtensionFilter(String ext){
		this.ext = "."+ext;
	}
	
	@Override
	public boolean accept(File dir, String filename) {
		return filename.endsWith(ext);
	}
	
}

Friday, August 5, 2011

Uris and Intents and Cameras, Oh My! - Android Development

For the last couple of days, I've been hacking on the Android camera API functions. Specifically, I've been trying to invoke the camera with an Intent (new Intent(MediaStore.ACTION_IMAGE_CAPTURE);), rather than building out my own preview and capture function.

The main stumbling block has been how to pass file location to the Intent so that the Camera function saves images where I want them to go, rather than the default location (/mnt/sdcard/DCIM/Camera/ I believe). I've looked all over the internet for how to do this properly. After getting some expert advice, this is the best solution I found:

private static Uri getImageFileUri(){

     // Create a storage directory for the images
     // To be safe(er), you should check that the SDCard is mounted
     // using Environment.getExternalStorageState() before doing this
     
     File imagePath = new File(Environment.getExternalStoragePublicDirectory(
                                Environment.DIRECTORY_PICTURES), "CameraTest");
     if (! imagePath.exists()){
      if (! imagePath.mkdirs()){
       Log.d("CameraTestIntent", "failed to create directory");
       return null;
      }
     }
     
     // Create an image file name
     String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
     image = new File(image.getPath() + File.separator +
                        "IMG_"+ timeStamp + ".jpg");

     // Create an File Uri
     return Uri.fromFile(image);
    }

The key appears to be not to use ContentResolver (e.g.,
getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);) to generate a Uri, because this means the Camera app will just save the image in the default location with a default name.

The above solution saves the image in a shared location so other applications (like Gallery) can access it. Files saved to this location also will not be deleted when your application is uninstalled. If you want your image files to be not easily visible to the user and removed when your app is uninstalled, call your application's Context object to create the image path:

     File imagePath = context.getExternalFilesDirectory(
                         Environment.DIRECTORY_PICTURES);

You don't need the "CameraTest" bit in this case, because the imagePath will be specific to your application: /mnt/sdcard/Android/data/<app_package>/Pictures/

Monday, August 1, 2011

Web Relay Test Arduino Sketch

I wrote this Arduino sketch to test firing the relays on 2 of my Seeed Studio Relay Shields. Shield 1 is connected to digital pins 2 to 5 and Shield #2 is connected to digital pins 6 to 9.

This sketch enables all those pins for output and then turns them on and off for half a second (500 milliseconds) in sequence.

#include <SPI.h>
#include <Ethernet.h>


byte mac[] = { 0x90, 0xA2, 0xDA, 0x00, 0x50, 0xA0 };    //physical mac address
byte ip[] = { 192, 168, 1, 177 };   // ip in lan
byte gateway[] = { 192, 168, 1, 1 };   // internet access via router
byte subnet[] = { 255, 255, 255, 0 };                   //subnet mask
Server server(80);                                      //server port
byte sampledata=50;            //some sample data - outputs 2 (ascii = 50 DEC)            

String readString = String(30); //string for fetching data from address

void setup(){
//start Ethernet
Ethernet.begin(mac, ip, gateway, subnet);

//Set pins 2 through 9 to output
for (int i = 2; i <= 9; i++){
  pinMode(i, OUTPUT);  
}

//enable serial data print  
  Serial.begin(9600);
}
void loop(){
// Create a client connection
Client client = server.available();
  if (client) {
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        //read char by char HTTP request
        if (readString.length() < 30) {
          //store characters to string
          readString.concat(c);
        }  
        //output chars to serial port
        Serial.print(c);
        //if HTTP request has ended
        if (c == '\n') {
          if(readString.indexOf("test=all") > -1) {

httpReply(client);

// cycle through pins 2 to 9
for (int i = 2; i <= 9; i++){
               Serial.print("Writing pin ");
               Serial.print(i);
               Serial.println(" HIGH");
               digitalWrite(i, HIGH);    // set the LED on
               delay(500);
               Serial.print("Writing pin ");
               Serial.print(i);
               Serial.println(" LOW");
               digitalWrite(i, LOW);
               delay(500);
             }
          }
          //clearing string for next read
          readString="";
          //stopping client
          client.stop();
        }
      }
    }
  }
}

void httpReply(Client client){
  client.println("HTTP/1.1 200 OK");
  client.println("Content-Type: text/html");
  client.println();
  client.println("{\"status\" : \"executing\" , \"cmd\" : \"test=all\"}");
  client.stop();
}
This code is loosely derived from code by Mareika Giacobbi of nerdydog.it for his Domotic Home project.

ADK + Ethernet Shield + 2 Relay Shields = Almost Working Prototype

Here is the current iteration of my Arduino Irrigation Controller rig:


I now have 2 of the 3 Relay Shields connected to the ADK with Ethernet. Did I say connected? It's a bit fragile to say the least. Don't breathe on it! Those green wires going into the middle of the Relay PCBs are basically held their by the tension of the wires wanting to straighten out.

I really wish the Seeeduino guys had put on those extra long headers and pins on these Relay Shields like on the Arduino Ethernet Shield. It's basically impossible to attach them to the Arduino board or the Ethernet Shield because these huge freakin' pins from the screw terminals extend 2mm out the bottom of the board (and cause shorts against tall components, if you're not careful).

Now I'm waiting on some parts from AdaFruit so I can connect the 3rd Relay Shield and create a more reliable connections to the first two boards. But, where am I going to put Relay Shield #3? Hmmm...

One other thing that confuses/frustrated me with the Relay Shields is that they cannot run off USB power (5v), you have to plug them into their own 9v power supply, or plug the Arduino into a 9v+ power supply and route the Arduino's 9v pin (not the 5v pin) and ground to the Relay Shields. That's a bit annoying. The important thing, though, is that it works. On to the next stage.

Pin 0 and 1: Don't Use for Output!

Oh, and one other thing: If you are thinking of using digital pin 1 and pin 2 to control the Relay Shields: Don't. I tried using them in an earlier version of this prototype and saw some worrying behavior. Namely, when uploading a sketch to the Arduino board, pins 1 and 2 flash on and off very quickly which turns on the connected relays on and off very quickly and makes them rather hot. I didn't have a catastrophic failure; the relays still work, but that'll be the last time I try using pin 1 and 2 for anything other than TX and RX.