Monday, May 6, 2013

Return of the Arduino part 2: status indicators are your friends

The essence of user-friendliness is feedback. I won't be rivaling Apple with my little creation, but having more than zero indication that the IR receiver is actually picking up signal is probably wise. So the next step in the project was to mount some LEDs to the case to give me a bit of status indication.

A quick trip to Radio Shack netted me three red LEDs (2.6v, 28mA, 10mcd), one green LED (2.1v, 25mA, 6.3mcd), and a quad of 220-ohm resistors (and some 1K-ohm resistors). One thing I've learned during this process is to verify everything before busting out the permanent-connection hardware; before soldering or gluing anything, I bread-boarded the LEDs and used a slight modification on the Arduino "Fading" demo to confirm that all four LEDs would light. This turned out to be wise; my initial plan had been to use a 1K-ohm resistor between all four cathodes (in parallel) and ground, but I discovered that allowed too much back-current to leak across the LEDs---not desirable at all.

Breadboard. Arduino is connected by wires to four 220-ohm resistors, each leading to an LED, all leading to ground.
Final configuration for the LEDs and resistors on the testing breadboard.

Once I'd verified the configuration, it was time to get to work. Trimming the anode leads a bit on the LEDs, I soldered one resistor to each anode. I then grabbed my Dewalt and 3/16" bit again and bored four parallel holes in the upper half of the case, then glued the LEDs in place. Due to a slight mix-up on my part, the green LED ended up with its resistor on the cathode, but no harm seemed to be done. I soldered all the cathode leads (including the resistor lead from the green LED) into one, and left the anode leads to be connected to the Arduino.

I ran into a bit of a conundrum at this point: with the LEDs living on the top shell, I wanted some flexible wire with some nice, solid end plugs to connect the LEDs to the Arduino control pins, but nothing in my kit really fit the description. Fortunately, I discovered that Radio Shack sells a SideKick basic kit that includes what the kit calls "breadboard jumper wire." It turned out to be the perfect tool for the job if I cut them in half and soldered the loose wire to my LED leads.

With the jumper wires in place, I connected the LED anodes to Arduino pins 6, 9, 10, and 11, and the cathodes to one of the two GND pins. I then wrote a couple of short LED test functions:
// LED control library, by Mark T. Tomczak
// Public domain
// To use:
// * Call SetupLedControl with an array of LED inputs IDs
//   (-1 terminates the array as a sentinel value)
// * Call functions in the library to control the LEDs.

// Control LED firing patterns
// -1 used as sentinel value
int *g_led_control_leds;
int g_led_control_num_leds = 0;

// *leds is the arraay of LED pin IDs, terminated with a sentinel value of -1.
void SetupLedControl(int *leds) {
  g_led_control_leds = leds;
  g_led_control_num_leds = 0;
  while(*leds != -1) {
    g_led_control_num_leds++;
    pinMode(*leds, OUTPUT);
    leds++;     
  }
}

// Blink several times (off-on-off).
// - times: number of times to blink
// - flash_delay_millis: Number of milliseconds to wait
//   before toggling the light on or off. void FlashLights(int times, int flash_delay_millis) {
  for(int i=0; i < times; i++) {
    for(int i=0; i < g_led_control_num_leds; i++) {
      analogWrite(g_led_control_leds[i], 255);
    }
    delay(flash_delay_millis);
    for(int i=0; i < g_led_control_num_leds; i++) {
      analogWrite(g_led_control_leds[i], 0);
    }
    delay(flash_delay_millis);   
  }
}

// This is a fun little function that delays a specified
// number of milliseconds, while showing the time remaining as the
// intensity of several LEDs.
// 
// When all the time is remaining, the LEDs all glow at maximum brightness.
// Elapsing time is shown as the LEDs slowly going out one-by-one. void CountDown(long time_to_countdown_millis) {
  unsigned long start_time = millis();
  // TODO(mtomczak): Arduino millis() function rolls over to 0 after 
  // about fifty days. You should account for this rollover... 
  // possibly build a timer library with some structs to hold that state.

  for(
    long time_elapsed = 0;
    time_elapsed < time_to_countdown_millis;
    time_elapsed = (long)(millis() - start_time)) {
    float percent_remaining = (float)(time_to_countdown_millis - time_elapsed) / (float)(time_to_countdown_millis);
    float led_fraction = 1.0 / (float)(g_led_control_num_leds);
    for (int i=0; i < g_led_control_num_leds; i++) {
      // The logic is exciting here, but it basically boils down to:
      // * consider the time remaining to be divided into a series of "ranges"
      //   (one per LED).
      // * If the time remaining is more than my range, glow maximum intensity.
      // * If time remaining is less than my range, shut off completely.
      // * Otherwise, glow proportional to how much time is left within my
      //   range.
      int output = 255;
      if (percent_remaining < led_fraction * (float)(i + 1)) {
        if (percent_remaining < led_fraction * (float)(i)) {
          output = 0;
        } else { // percent remaining is in range led_fraction * (i, i+1)
          output = (int)((percent_remaining - (led_fraction * (float)(i))) * 255.0 / led_fraction);
        }
      }   
      
      analogWrite(g_led_control_leds[i], output);
    }    
  }
}

I combined this library with the recognition code from my Arduino IR bridge project so that it would blink twice and then count-down over five seconds when it recognized an IR pattern. Overall, I'm not unhappy with the results!

What I learned

  • This is the part of the project where the insulating properties of hot glue were especially helpful. I basically glued over the forest of wired-together cathodes so that they couldn't short against anything, and I'm pretty pleased with the results.
  • Pay more attention to output ratings on LEDs. There's a noticeable visual difference between the green LED and the much brighter red LEDs (I'm guessing that my eye is reacting logarithmically to the difference between 6.3mcd and 10mcd). If I wanted to back this part out and try again, I'd go with four red LEDs.
Part three will wrap things up by adding the IR emitter and the code to drive the entire project.

Sunday, May 5, 2013

Return of the Arduino part 1: mounting the controller and IR receiver

I've had an Arduino UNO board kicking around my house for about a year. My original plan was to create an input switcher for the TV that would run off the cable remote (it would maintain a bit of internal state and fire the commands to switch TV modes from the current one to the desired one instead of needing to fish around for the TV remote). This was pretty successful, and I published both the IR decoder and the input changer itself on GitHub. But I never got around to enclosing the project and making it "clean."

So this week, I finally purchased an enclosure and power supply for my UNO board. Trying it out, I immediately discovered that the enclosure doesn't really fit my Ethernet shield (which the reviews will tell you gladly; that's what I get for not reading the reviews before purchasing). Since I didn't need the shield, I shed it (I'll probably get another UNO to plug it into later).

Then, I got out my kit and got to work. It's been awhile since I had occasion to solder anything, and I've never done hot glue for an electronics project before. Overall, I'm not unhappy with the results.

Open Arduino enclosure, showing the Arduino board nested in position and the IR decoder glued in place.


I made a hole in the enclosure using a 3/16" bit on my Dewalt drill, angling it diagonally back-and-forth to get a good wide slot (I wanted to make sure the receiver had a nice, wide field-of-view to catch IR signals). I then seated the Arduino board in the enclosure and glued the IR sensor in place with my wife's glue gun (note to self: I've stolen my wife's glue gun and owe her a new one). My gluing technique is hellishly wasteful, but I figure I'll get better with practice. One thing I love about working with glue is that it doubles as an insulator; no more wiggling my fingers in between tiny wire runs to get the electrical tape on there!

Front face of Arduino enclosure, showing the IR decoder visible through the drilled slot.
IR decoder visible through the drilled slot in the side of the enclosure.


Once the glue solidified a bit, I did a quick soldering job and was all set. I wrapped the signal and power wires around the posts in the enclosure also and threw some hot glue on there for mechanical stability (I want to make sure any jostles the wires might take are being supported by the posts and not the Arduino's female pin coupler or the IR sensor's leads).

I then fished a sticker out as a finishing touch. :)

Back-face of enclosure, showing sticker depicting two Androids on skateboards.


I'm very happy with both this sensor and its range. I ran some quick tests with the full enclosure at different ranges using my old remote signal decoder program, and found it was able to sense a good distance away (about 15 feet; plenty for my needs).



What I learned

  • This IR sensor is more temperature-resistant than I'd feared it might be; I ran the soldering without any heat sinks, and no harm was done.
  • Hot glue is actually pretty safe to work with; I'd worried I would get burned, but discovered that it appears to shunt its heat pretty quickly as it transitions to a solid state. solid strands can be touched within a few seconds of being emitted from the nozzle (though blobs should be given about thirty seconds to a minute to gel cleanly; they change opacity a bit on solidification, which is convenient).
  • Hot glue is messy; spiderweb-strands everywhere, needed to go in with pliers to clean it up. Also, I'll be more careful in the future about letting the glue find its way into the seam of the enclosure itself; my enclosure no longer seats quite correctly because one blob of glue bubbled over the top and got into the joint.
Part 2 will discuss extending the software and adding status indicators.

Sunday, March 31, 2013

Ten-minute hack: Keep the snow off your windshield (just in time for spring!)

The most irritating thing about the morning weekday ritual in these northern lattitudes is scraping the show off my windshield. I'm already cold and cranky; having to do some manual labor to get the car ready to go is just icing on an anger-cake.

While I was watching TV with the family one night, a commercial came on for a windshield frost guard. I had to laugh a bit, as I said to myself "That's basically just a sheet you put over your windshield."

I decided to test that theory.

Preparation

Jersey-knit sheet. Red. Queen-size. It was on the top of the "Sheets we don't really want to put on the bed anymore" pile.

Ten-minute hack

I opened the car door and laid the sheet's short end across the top of the door frame, then shut the door.

Sheet is closed in along the top frame of the door.

Then, I stretched the sheet across, and did the same on the other side.

Sheet stretched fully across the windshield.
Add caption

It turns out my timing couldn't have been better, because we got a couple of inches that night.

Car is covered in snow. Neither sheet nor windshield are visible.
March 25... GROUNDHOG YOU ARE ON NOTICE.
However, I just peeled the sheet back and...

Car is still mostly snow-covered, but the sheet has been removed and the windshield is completely clear.
... all set!
I shook out the sheet, threw it in my trunk, dusted off the other windows and the flat surfaces, and drove away.

Final Thoughts

Overall, I'd call it a successful experiment.

Pros

  1. It was free (amortized against the cost of a sheet destined for the rag-pile).
  2. It worked great.
  3. If the sheet ever gets too grimy, it's machine-washable.

Cons

I still don't think I'd buy a dedicated windshield cover for this job, but here are some issues I can predict happening.
  1. Jersey knit wicks water. This could be an issue if you get a rain-then-freeze weather pattern; you may end up with sheet stuck to your windshield. A waterproof material would be preferable.
  2. Since the ends of the sheet are extending into the car, they could get a little grimy and carry that grime into your car (or wick water in), which could be a problem depending on your tolerance for that sort of thing. The ones that are sold for this purpose have some stiffness to them and bungee nylon that wrap around the rear-view mirrors; if I felt like doing more than a ten-minute hack, I could probably fabricate something equivalent with bent-out coat hangers and some rope.
  3. Even after shaking the solid snow out of the sheet, the wicking action had pulled a lot of water in, and I ended up with a soggy sheet in my trunk. My trunk doesn't care about wet stuff, but if yours does, you'll want a plastic bucket to keep the sheet in.
With luck, we shouldn't have any more snow this year (HAH!). But if we do, I'm ready.

Monday, March 18, 2013

Another Year of FIRST Robotics



The FIRST Robotics regional has wrapped up in Pittsburgh, PA. I didn't really have time to participate as a mentor or volunteer this year (although I got a chance to present for my company as a sponsor, which was really nice). But I did get a chance to watch a couple of rounds. One I caught really summed up why I love FIRST.

Tem 3955 (blue, center) built a robot that could climb the pyramid rung-by-rung by repeatedly extending a two-claw gripping arm and then hooking a lower grip onto the bar below, a bit like a rock climber. The machine was a beautiful thing to watch.

But in this match, they slipped; only one hook "bit" on the highest bar of the pyramid and they were left hanging. In that position, they're worth 20 points at the end of the match, but they'd be worth 10 points more if they could get the lower chassis above the middle bar. You can hear the crowd shouting "Pull yourself up!" But if they do and the chassis bumps the middle bar, they could tumble right off and lose all 20 points (and possibly damage their robot or a teammate's robot on impact).

Scoring for the climbing pyramid. Source: http://frc-manual.usfirst.org/viewItem/3#3

Rather than risk what they already had, they decided to hold on. And in the end, it proved to be the right choice; they won the round 69-55; the twenty points they earned were instrumental to their team's victory.


This is a machine that these students built themselves in six weeks, from scratch. But it's not about the machine; it's never really about the machine. It's about the moment-by-moment decisions made by the students on and off the field. I can imagine the pressure the three-student driving team felt trying to decide how to handle the situation; at the end of the day, the moment was in their hands alone, and it's their choice that will decide whether they win or lose.

Teamwork. Quick thinking. Focus. Strategy. And also control. Knowing how to do as much as you possibly can... And no more.

And no less.

This is why I keep coming back to FIRST.

Monday, December 24, 2012

Belphanior Home Automation System


I've been playing around with home automation as a hobby for quite a long time now. One thing I found frustrating was the lack of flexibility in the central controllers I've worked with. To that end, I'm pleased to introduce Belphanior, my own automation-oriented remote signalling and scripting system.

Belphanior is intended for a standard household setup (multiple computers and automaed systems behind a local intranet). Key to its design is a multi-process approach; the core of Belphanior is a communications protocol built atop HTTP and JSON, which allows a single "butler" process to coordinate and control multiple "servant" processes. This allows you to run the servants locally on the machines with the hardware that needs to be controlled. It's also designed to be self-documenting; "roles" (specific types of tasks servants can perform) are first and foremost human-readable, with the details of implementation left up to the creators of the servants. So an "output" role can be handled by a text-to-speech servant, a logger, a marquee-display controller, etc.

Belphanior's jumping-off point is at belphanior.net. There, you'll find a "getting started" guide and a list of the currently-implemented servants. Servants and the butler are available as open source under the MIT license, so if you wish to create your own, you are free to do so (and if you'd like to provide me a link to them, I'd be happy to post them on belphanior.net!).

A short list of things I've used Belphanior to do:

  • Turn the main lights off in the house at the end of the day (I'm terrible about leaving basement lights on when I go to bed).
  • Control Christmas tree lights and other seasonal home decorations to save power.
  • Drive the train under the Christmas tree every two hours (see "Making the Train Run On Time").
I'll be continuing to extend Belphanior and the home automation system as I go, and I'll be updating this blog with any fun developments.

Have fun, and happy hacking!

Thursday, December 20, 2012

Ten-minute Hack: Temporary Remote View

This one may not even require a whole ten minutes. I considered refraining from posting about it, but I've found it so useful in so many circumstances that I felt the need to share it.

While doing home automation work, I frequently find myself needing to control a process from one floor while observing it on another floor, or needing to observe events on multiple floors at once. For instance, I have a command that switches off all the lights in the house; I need to observe the basement and first floor simultaneously to verify it's worked. That's quite a bit of dashing up and down the stairs.

If you have two computers with embedded cameras (smartphone and desktop PC, laptop and tablet, smartphone and tablet), it's ridiculously simple these days to set up a simple video chat to remotely observe another room in the house. My tool of choice is Google+ Hangouts, but other applications with clients on all of your computers of choice would work just as well.

To set this up in Hangouts, all you need to do is start a hangout with nobody (I have an empty circle named "Nobody" for this purpose). Once the hangout is established on your first device, use the Google+ client on your second device and select your profile. You will see an entry for "hangout with 1 person." Join that hangout, and your two devices will be video-linked (you can add more if you so choose).

It's a pretty straightforward trick, but it's convenient if you have spare devices sitting around the home. In addition to using it to monitor home automation clients on different floors, I've used it to monitor a kitchen timer while I worked in a room too far from the kitchen to hear it (world's most expensive baby monitor, but I have a laptop and smartphone and no baby, so there you go!).

I hope you find this useful! Happy holidays.

Saturday, December 15, 2012

Making The Train Run On Time

I have a few INSTEON modules and a 2412N controller. I've been experimenting with home automation for awhile, and this year I thought I'd do something fun.

I unpacked the model train that goes under our family tree and connected the power box to an INSTEON lamp module. Using Belphanior, my not-quite-yet-fully-released home automation core, I wrote a short script that drives the train for a few seconds (timing is a little sloppy, as it takes several seconds for the 2412N to respond to HTTP requests from the 2412n servant, but it does the job).

"cycle train" script
"cycle train" script

With the script written, all I had to do was fire it every two hours. Fortunately, there is a Belphanior servant that can monitor an iCal-formatted calendar and notify the butler to run scripts in response to calendar events. I pulled up a Google Calendar that I keep for this purpose and populated it with a cycle of the train every two hours (except at night, to save power).

Belphanior calendar, showing "cycle train" command
Belphanior calendar, showing "cycle train" command


The result is shown below. I'm pretty satisfied with it; simple, but effective!