All posts by Neil

The Random Grant

The Webber Family Foundation makes grants to 501(c)(3) organizations focused on education. We started with a broad definition of “education” but that quickly led to a problem: too many organizations competing for a limited grant budget. Even after filtering out “bad” requests, and selecting for “best in class”, the aggregate amount requested was often four times (or more) the size of our overall grant making budget.

At that point the decision process became essentially random. For every grant we approved there were three other grants we denied, with no really good reason for denying them. They met all our criteria. They were best in class organizations. There was nothing wrong with them other than simple arithmetic: we didn’t have enough money. This felt unfair to grant seekers; we put them (and our staff) through all the work to get to that point and then said no to 75% of them for no reason they could control.

To fix that, we narrowed our focus to some very specific areas of the education universe, which in effect ruled out many programs in advance and reduced the pool of requests to a size that better matched our available budget. This ended the oversubscription problem but of course sent many generally good and deserving educational organizations into exile from our Foundation.

I wanted to find some way to still allow for the occasional grant in education areas outside our narrow focus but without reintroducing the “oversubscription leads to random decision making” problem. My solution? Explicitly random decision making!

It works like this: Of course we still allocate the bulk of our grant making budget to our standard, deliberate, detailed decision process. But we set aside a smaller piece of the pie for something we call Random Grants. In applying for a Random Grant an organization only writes a one-paragraph description telling us what they would do with the money. They can send it in by email. That’s it; almost anything (educational) goes. Occasionally staff will have a question or two and follow up with the Random Grant applicant but usually just the one-paragraph request is all we go by (the most common follow-up would be to see the IRS determination letter if we aren’t already certain of the organization’s 501c3 status). Random Grant request sizes can be any amount up to $10K.

We accumulate the Random Grant requests and twice a year, at a Board meeting, we award them… RANDOMLY!

It works like this: Staff briefly reviews each request with the Board so that Board members may object to any particular request if they feel there is something amiss. In practice no request has ever yet been thrown out this way. Then staff numbers the requests 1 through N; this time around we had eight requests so they were numbered 1 through 8.

I then go to www.random.org which, conveniently, has a random number generation interface right on its home page:

rn

In the above capture I have already filled in the Min/Max with 1 and 8 as we had eight requests this time. Then while everyone watches I push the GENERATE button and whichever number comes up becomes the first Random Grant that we approve. It’s just exactly that simple!

So, yes, the Random Grant is usually quite oversubscribed, and, yes, that makes the decisions random. In fact they are explicitly random!

If we have more money left in the budget after awarding one Random Grant we do the process again, but this time only including any remaining grants that “fit” within the remaining dollars. We keep doing that until the amount of money left is less than any of the Random Grant requests. This method provides some incentive for organizations to not necessarily ask us for the maximum amount we allow in this process ($10K) because smaller requests will usually get multiple chances to win a grant.

Since the inception of this concept in 2012 we have made $198,500 of Random Grants. The feedback we’ve gotten from applicants has been positive. Of course how could it not be – it gives them a chance to compete for grant money they otherwise wouldn’t even have a shot at, and it’s a simple, lightweight process with an easily-understood yes/no mechanism.

To prevent the list of grant requests from continuously increasing over time we have a rule that once you apply, whether you win or lose, you cannot apply again for two more Random Grant cycles (which means approximately one year since we do this twice a year). That helps keep the applicant list size under control and also allows a wider variety of organizations to have a decent shot.

It’s probably not for everyone, but I do encourage other grant making organizations to consider this as a way to allow for some amount of “outside the lines” grants. I can understand an objection that if you believe your grant making criteria are good criteria, extending them randomly makes no sense. My counter would be that no criteria are ever perfect; thus I think having some nominal amount of random variance in the grant portfolio is a good idea.

 

Nov 5 update on Christmas Light Project

Up until today I prototyped my circuit on a breadboard; today I moved it to a perf board and soldered everything up. It still works!

Here’s a shot of the perf board:

perfboard

It’s just a reimplementation of the same circuit I had already breadboarded (and described in the prior post) except that I did go ahead and update Rg to 330Ω:

mosfet-v2

The eight infrared emitters will be remotely located out by each light strand I’m controlling. The long wires between those remote IR emitters and this board will be hooked up to the terminals as shown, generally with two wires connecting to all but the outer terminals. This is because each LED has two wires but one of them needs to be connected to the next LED in the series arrangement.

The GND goes to the Arduino ground as well as the ground of the external 12.6V power supply. The plus side of that power supply connects at the lower left and the signal from Arduino pin 3 which goes (via resistor Rg) to the MOSFET gate terminal connects at “G”.

The screw terminals I’m using come in two-terminal chunks but they can also snap together to form larger banks. They are very handy to have for projects like this.

Since this whole thing fit on one half of the perf board I can implement the second copy of this circuit on the other half in the same way.

I connected everything up and was happy to learn that my amateur soldering prowess didn’t screw anything up (and especially didn’t fry the MOSFET during soldering).

SOFTWARE

From a previous project I had some code implementing a simple JSON POST interface on an Arduino (with ethernet shield) allowing remote access to digital I/O. That code is up on github.

I took that code and modified it to accept POST requests of JSON to control sending IR codes using the IRRemote library.

The JSON it accepts looks like this:

{ "codes": [ ircode-dictionaries ], "repeat": n }

An ircode-dictionary looks like:

{ "code": 16718565, "bits": 32, "protocol": "NEC" }

The thing I’m controlling takes 32-bit IR codes via the NEC protocol; as I wrote earlier I determined this using the IRRemote library and an IR receiver/decoder in the usual way. The above code will make the LED string RED for example.

You can optionally add a “delay” element to an ircode-dictionary; it specifies a delay, in microseconds, to wait after sending the code. Although the NEC protocol allows for fairly tightly-repeated IR codes, the box I’m controlling doesn’t respond reliably unless you have about 150000usec (150 milliseconds) of delay between two consecutive IR commands. I haven’t tried to refine this number; I just know that 150 milliseconds works and 50 milliseconds doesn’t, so the true limit is presumably somewhere in between. I made the server supply a 150 millisecond delay by default unless you override that with the “delay” parameter.

You can specify multiple ircode-dictionaries in one POST; the main limitation is that there isn’t much ram (a whopping 2K!) on an Arduino so the maximum POST size my code can accept isn’t much. At the moment I have it defined as 350 characters. Still, that’s enough to allow you to do some interesting things. Only the first ircode-dictionary has to have the protocol and the bits specified; those values become the default for subsequent ircode-dictionaries in the same POST. Similarly for delay, if it’s been specified.

Given all that, we can make the LEDs rotate through RED GREEN and BLUE like this:

{ "codes" : [
    { "code": 16718565, 
      "protocol": "NEC", "bits": 32 },
    { "code": 16751205 },
    { "code": 16753245 } ],
  "repeat": 10 }

You have to be careful with the “repeat” because the Arduino server is non-responsive during the execution of all this. It’s probably best to set a “repeat” value that limits the cycle to 5-10 seconds at most (if you use the “repeat” at all even) and then use looping in your script or program driving the Arduino instead.

I wrote a python script using the Requests library to send POST requests to my Arduino.  The Requests library makes it dead-simple to do stuff like this; here’s the key portions of my python code for driving my Arduino (beware of / apologies for wordpress messing up indentation and line breaks):

def sendcodes(url, code_dicts, repn=1):
    topdict = {"codes": code_dicts}
    if repn > 1:
        topdict["repeat"] = repn
    js = json.dumps(topdict, 
                  separators=(',', ':'))
    result = requests.post(url, data=js)
    return result


# send NEC codes. Each argument should either be
# a simple code or a tuple: (code, delay)
def sendNEC(url, *codes, repn=1):
    a = []
    for x in codes:
        try:
            a.append({'code': x[0], 
                     'delay': x[1]})
        except TypeError:
            a.append({'code': x})
    return sendcodes(url, [{'protocol': 'NEC', 'bits': 32, **a[0]}] + a[1:], repn=repn)

I squeezed out extra spaces using the “separators” argument in the JSON conversion, just because of space limitations on the Arduino and thus not wanting to waste any of the limitation on unnecessary white space. For the same reason I only send the “repeat” element if the repeat is more than just one.

Here are some simple examples showing the LED colors changing under control of all this magic.

For the last one (“seizure”) I backed away far enough so the R/G/B LEDs could blend as they will when seen up on my house. The result looks a little bluish but I think that’s an artifact of the video. In any case I think my neighbors will enjoy that one.

INSTALLATION

While I’ve been working on electronics and software, we’ve also been installing the lights on the house. Don’t worry, I won’t actually light them up until after Thanksgiving, respecting proper tradition — but this year I need to prototype and check things out early.

Here’s a picture of some the LEDs running around one part of my roof line:

img_6581

The LED strand is attached to the roof simply by magnets, as the fascia is metal and magnetic. This is going to make it easy to put up and take down each year, though storing it requires some finesse to prevent it from become a magnetic mess. Each magnet has a zip-tie attachment stuck onto it and then is zip-tied to the LED strand. At night this seems pretty bright, I’m looking forward to getting the whole project up and running soon!

Arduino LED IR remote control multiplier

More progress on my house LED Christmas decoration project.

If you haven’t read the prior post about my Christmas lights go read it now.

My LED strands can be controlled by an IR remote. I built a simple IR detector circuit with an Arduino and used the IRRemote library to determine the IR hex codes I needed to mimic this hand-held remote controller. Given that, I have this problem statement:

Problem statement: Control up to 16 identical IR-commanded devices in unison. Each IR command sent must hit 16 devices simultaneously. The devices are physically separated but within “wires can be run to them” distance.

Previously I prototyped a trivial, always-on, circuit of multiple IR emitters in series. That was just a way to learn some of the key parameters I needed to know, such as the forward voltage drop of the IR emitters.

In this next step I’m hooking up a MOSFET to control that series circuit so they can be turned on and off to actually send the hex codes. I also did some more calculations and tests to optimize the circuit values. My result, shown below, can drive 8 IR emitters from one Arduino output:
ex1

You may wish to click on that picture to expand it to full size / full resolution.

The MOSFET is a “logic level” N-channel Power MOSFET from International Rectifier, part number IRLB8721. It can handle far more voltage and power than necessary in this circuit. I picked it because it was easy to find (e.g., Adafruit sells them) and, more importantly, it turns on at a “logic level” of Vgs = 4.5V at the Gate G. The Arduino output pins supply 5V so this will work well for controlling the MOSFET from an Arduino output pin.

Ignoring all the resistors for a moment, the operation of this circuit is pretty simple. When Arduino pin 3 is low (0V) the MOSFET is off and no current can flow from the Drain (D) to the Source (S). Therefore the IR emitter LEDs are off as they have no connection to circuit ground. When Arduino pin 3 is high (5V) the MOSFET turns on and current can flow from D to S, connecting the ground side of the series of IR emitters and allowing current to flow through them and turn them on.

Now when my IRRemote-driven software modulates Arduino output pin 3 and drives it high/low in an IR code pattern, the MOSFET turns the series of 8 emitters on and off accordingly. Their power is coming from an external wall wart supply, not the Arduino. The voltage of that supply is labelled Vx = 12.6V in the diagram.

My wall wart was unregulated and its output voltage varies according to load. It actually says “9V” on it but supplies 13.9 volts completely unloaded and “less than 13.9 volts” under various loads. My prototype circuit gave me an idea what this approximate unregulated voltage would be — around 12.6 volts with about 40mA of load. I used that “about 12.6 volts” guess to pick some resistance values and build this circuit and then measured the results and tweaked accordingly.

Note to self: Next project use a zener diode voltage regulator. Though in this project none of the values are critical; the primary constraint is to keep the current through the IR emitters between 20mA and 100mA. That’s a huge range and it really doesn’t matter where inside that range I end up because the emitters are literally taped right onto the receivers so the power they run at is irrelevant. This is a case of “anything in that wide range is good enough” even though it’s kind of a hack.

To test some values I attached the Gate G directly to +5V so the MOSFET would simply always be on and then measured the “as loaded” Vx value. I then adjusted the resistor values accordingly. There’s some circularity here because changing resistance values changes the current, which can change the IR emitter voltage drops, and thus can circularly affect the resistance calculation. But in practice it just doesn’t matter since, as already explained, if I just get close and don’t exceed any maximum values I’ve got something that works just fine for this application (once again note to self: use a regulated supply next time).

So, with that test I found Vx = 12.6V as shown in the diagram. The voltage drop across all 8 IR emitters was 10.1V leaving 2.5V to be dropped across current-limiting resistor R1.

The current flowing through the IR emitters (and the DS portion of the MOSFET) is thus

I = (12.6V – 10.1) / R1

I picked R1 = 56Ω to get a current flow (computed) of about 45mA.

NOTE: I haven’t yet built the second copy of this circuit. Since I have more than 8 devices to control I will build a second copy of this circuit and hook it up to the same Vx supply and the same Arduino pin 3 output. It’s possible that the current draw for the second copy of the circuit will lower the supply voltage below 12.6V. I plan to measure that but, as already noted, so long as the resulting current flow through all the LEDs remains above 20mA this really won’t matter. If necessary I will come back and recalculate new R1 values with the full 16 IR emitter loads. Expect at least one more post on this topic with all that verified.

Resistor Rg protects the Arduino output pin from excessive current draw when the MOSFET transitions from off to on. When the MOSFET is off and Arduino pin first rises to 5V, the Gate input G acts somewhat like a capacitor between G and S. This is just inherent in how MOSFETs work. This means DC current will flow for a brief instant between G and S until the MOSFET accumulates enough charge and blocks further DC current flow “somewhat like a capacitor between G and S“. This is all part of the transition of the MOSFET from the OFF state (very high resistance between D and S) to the ON state (very low resistance D to S). To keep that brief current spike below the Arduino max pin output of 40mA, I choose Rg at 220Ω which leads to this calculation for the current draw when G and S are momentarily (effectively) shorted:

Ig = 5V / 220Ω = 23mA

That 23mA (which is within the 40mA limit) will only be drawn for a brief fraction of a second as the MOSFET charges. During the instant of time the 23mA is flowing the resistor will dissipate:

W = I^2 * R = (0.023 * 0.023) * 220 = 116mW

I’m using a 1/4W resistor which is more than enough to tolerate this approximate 1/8W (that happens for a short period anyway).

It is worth pointing out that I have some uncertainty around this topic; truth be told when I first built this circuit I had no Rg in there and my Arduino did not blow up. I assume this is because the effective capacitor between G and S charges so quickly that a very brief instantaneous current spike doesn’t have enough time to fry the Arduino. There may be other complex reasons the Arduino did not fry. Regardless, it seems like a bad practice to let that current spike happen so I added the Rg resistor to the circuit as soon as I had read about the capacitance effect.

As I’m writing this I realized this will lead to a 46mA spike being drawn when I hook up the second copy of this circuit (against an Arduino recommendation of 40mA max), because there will be two MOSFET gates hooked up to the single pin 3 output. Honestly this didn’t occur to me until just now as I’m writing up this posting (one benefit of writing this stuff up!).  So I’ll likely go back and bump Rg up to 330Ω which reduces that current to 15mA for one circuit, 30mA for two, and also slightly alters the calculation below (but not in any way that changes anything important).

The other resistor, Rgs, ensures that the gate G will be pulled down to ground even if the Arduino is turned off. Sometimes this is called a gate bleed resistor because it also serves to discharge the effective capacitor charge between G and S (discussed above) during a transition from ON to OFF. In our application the Arduino can actively sink current so Rgs isn’t needed for bleeding the capacitor. Regardless, it’s another “good practice” to put this in there and, as noted, it ensures the gate will be at ground potential if the Arduino happens to be off.

l picked a value large enough to ensure that the voltage appearing at G will still exceed 4.5V as the two resistors Rg and Rgs form a voltage divider between the Arduino output pin (when it is high at 5V) and ground:

Vgs = 5V * (Rgs / (Rgs + Rg)) = 4.94V

which is still plenty to trigger the gate (if Rg is increased to 330Ω this still works out to 4.9V). When the Arduino output pin is high there is a current flowing through these two resistors of:

I = 5V / (Rgs + Rg) = 0.2mA

i.e., one fifth of a milliamp, nothing to be concerned about.

Still to do:

  • Build the second copy of this circuit
  • Reverify the unregulated wall-wart voltage level when driving both circuits; possibly update R1.
  • Change Rg to 330Ω “on general principles” to ensure the instantaneous draw remains under 40mA during MOSFET turn-on transition.
  • [optional] learn more about what that instantaneous draw really is to get a better handle on future Rg for future projects.

Christmas Light Project – IR control prototype

I have a new plan for my house christmas lights this year, involving roughly a quarter mile of RGB LEDs. I bought 12 individually-controllable segments and plan to daisy-chain them to outline the entire perimeter of my roofline.

Each segment (i.e., roughly 1/12th of my display) has an individual controller that can make the segment be Red, Green, Blue, or any combination (the R, G, and B values can be set individually). The control is for the entire strand; I do not have a quarter-mile of directly addressible individual LEDs (perhaps that will be a future project).

The controllers come with an IR remote that lets you set the color you want. Of course what I want is to set all 12 strands to the same color at the same time and have them change in unison periodically, so I need a computer controlled IR emitter and some programming.

I’ve already captured the necessary IR codes using an Arduino setup and the excellent IRremote  library. I’ve also extended my Arduino Digital I/O Web Server code to accept more types of JSON POST requests to emit IR codes (also via IRremote). So now I have a server on my network that I can POST JSON to and have it emit the proper codes to control these LED strings. Woohoo!

The next problem is I need to drive 12 IR LEDs. I can’t drive them all from one output of the Arduino. I could conceivably simply hook them up to 12 different outputs and just do twelve JSON POST requests every time I want to change the light colors. There might be a way to reduce that to, say, 6 different outputs by daisy chaining two LEDs per Arduino output. There isn’t enough voltage available to drive very many LEDs though and I didn’t want to go down the path of serial/parallel arrangements when I could do something else more complicated and (conceptually) more fun.

So, instead I’m making a separate circuit to drive the LEDs themselves. First I wanted to prototype the circuit concept. I had several 9V adapters laying around, so I planned this circuit based on a 9V supply:

5leds

If you work this out the current flow will be about 64mA (smack in the middle of the acceptable range of 20-100) and the 47 Ohm resistor will dissipate 200mW. A small 1/4W resistor will be fine.

This oversimplified circuit is “always on”; the actual plan was then to add a MOSFET to control the circuit, and given the MOSFET input characteristics I could easily drive three MOSFETs from one Arduino output. Problem solved!

So I grabbed a 9V adapter I had laying about; I have many of these from prior dead bits of technology (throw away the gizmo; keep the adapter). Just to be sure I decided to measure the output of the device:

img_6499

Says 9V but…

img_6501

reads higher. I like my analog meter, but now I felt it was necessary to break out the digital and get an easier-to-determine number that appears to be more accurate than it probably is (haha):img_6503

Yup, 13.9 volts. I checked several of my other “9V” adapters and found the same thing. The reason for this would fill a whole posting unto itself; here’s one write-up if you are interested in more details: Unregulated power supplies

So, back to the spreadsheet to recalculate. The good news is that now I can easily put 8 IR emitters in series and the new calculations look like this:

  • Supply Voltage: 13.9V
  • Pullup Resistor: 82Ω
  • Calculated current: 52mA (assuming Vf of 1.2V per emitter)
  • Power through resistor: 0.225W assuming Vf of 1.2V. A quarter watt resistor will still be ok.

So, time to break out 8 IR emitter LEDs, an 82Ω resistor and do some testing:

img_6510

Eight LEDs connected in series with an 82Ω resistor.

Hooked this up to the “9V” (13.9V) power supply and…

Well, how can we tell if it works? First thing is no blue smoke came out of anything, so that’s good. Second thing: some digital cameras can see IR (because some don’t do a sufficient job of filtering it out). My phone camera (iPhone 6) can’t see IR, but I had an old Canon Powershot that can. Here’s what it looks like through that camera:

img_6507This is pretty cool. To the naked eye you can’t see anything, but with the camera you can see the IR emitters lit up. So, everything is working, no blue smoke is coming out anywhere and nothing smells like it is burning. So far so good.

I went to measure a few parameters just to verify everything. First off, the power supply voltage dropped to 12.6 under this load. That’s not entirely surprising (and probably somewhat related to why it read 13.9 unloaded). In fact it’s actually helpful, as it pretty dramatically reduces the power dissipated in the pullup resistor (because the entire voltage reduction of 1.3V from 13.9 to 12.6 is “seen” entirely by the resistor as the LEDs have a somewhat-fixed voltage drop across them). The new calculations work out like this:

  • Supply Voltage: 12.6V
  • Pullup Resistor: 82Ω
  • Calculated current: 37mA (assuming Vf of 1.2 per emitter)
  • Power through resistor: 0.110W

I took my meter and verified that each LED was operating at Vf = 1.2V. This is a little tricky to figure out a priori because it depends on the current flow. At 100mA the data sheet says Vf will be 1.5V; at 20mA the data sheet says Vf will be 1.2V and there is a graph showing you how the values vary at intermediate current levels. The tricky part with all this is that the current flow circularly depends on Vf. Figuring this out from the data sheet is beyond my EE pay grade but I just assumed system would come to a self-imposed equilibrium, which in this case turns out to be 1.2V per emitter and total current flow (calculated) at 37mA.

Indeed, if you really care about the LED brightness you should be using a fixed-current driver circuit that would let you control the exact amount of current; versus the “whatever it turns out to be is good enough for me” method I’m using with this simple passive circuit. In fact you can get things called “LED drivers” that are designed to do exactly that. However, in my application it doesn’t matter. The emitters are happy with anywhere from 20mA to 100mA and I don’t really care how bright they are because they will ultimately be taped up right next to the receiver on the LED strip controller.

Finally, I broke out my analog meter again (because my digital meter won’t do this – WTF?!) and measured the current flow just to be sure I had understood everything correctly:

img_6508

We’re on the 0-25 scale here so the mid-tick between 0 and 5 is 25mA and each subsequent smaller tick is 5mA. It looks like we’re reading about 34mA (the picture isn’t straight on to the meter alas) which is well within expected variation/tolerance from the calculated value.

It works!

Next step will be adding in the MOSFET to control this so the emitters can be blinked by the IRremote code to control the actual LED strings. Stay tuned for a future report.

 

Motorola MC68020 Processor Board from 1987

In 1987 a company I worked for (Epoch Systems; it no longer exists) designed and built this custom 68020-based processor board for a file server. I did the Unix port (4.2bsd from vax) for this system.

Ep1a

A few notes for the hard core nerds. Bring up the full resolution version to see some of these details. Note: when downloading the full picture, the preview comes up quickly (and is blurry); wait for the full download.

  • The main processor (MC68020) is bottom center-right.
  • To the right of that is the memory management unit: XC68851. That’s supposed to be “MC” not “XC” but we were building these boards before Motorola released the final MMU chips so some of our early boards were built with the “experimental” MMU chips. I believe these made it into the field at customer sites but I’m not sure.
  • There was a separate dedicated I/O processor and that’s the second MC68020 top left.
  • The board was part of a custom NFS fileserver, which used optical jukeboxes and supported a whopping 30GB of storage in the base configuration; expandable up to 150GB. We called this “Infinite Storage” (really!)
  • The yellow arrow stickies in various places point to areas where ECOs were done (bug fixes; this board is serial #6)
  • The processor cycle was 25MHz, which was fast at the time, and the board is an early example of surface mount technology. The engineers were debating whether to use surface mount or not, but in the end that was the only way they could cram all that stuff onto the “small” form factor board. I think there were 12 layers of traces in the printed circuit board but I don’t remember for certain.

Traffic Light shows … Numerous is still dead

A while ago I built a simple visual display for the current Austin-area air quality index: http://neilwebber.com/notes/2015/10/24/traffic-light-shows-air-quality-index/

The light was green for good AQI, yellow for medium, and red for bad air quality. For the AQI data I leveraged a “metric” that I had already developed using the Numerous service. Being a hard core nerd I also covered the case where the Numerous server could not be contacted; the display is red and yellow for that.

As you can see here, the error handling code works. Numerous shut down operations permanently on May 1, 2016 and my traffic light display is now simply a reminder of their demise. 🙁

Numerous is down

 

Making a simple systemd file for Raspberry Pi jessie

I wanted to write a systemd service file for a daemon I wanted started automatically at boot on my Raspberry Pi running Debian Jessie.

This used to be a lot simpler in the old hardcore Unix days. Well, no, actually, it’s simpler now. But figuring out how to do it was anything but simple and took me the better part of a day. Maybe I’m just bad at google, but I couldn’t find a simple “just do THIS” recipe; all I could find was hopelessly detailed and complex descriptions of systemd stuff that exceeded my newbie level of understanding and exceeded my geezer level of interest in reading lots of stuff.

So, here, in the hope that someone else will find this via google someday and find it useful, is how to do it. Or, at least, one way that works.

Step 1: Make a clown.service file

Assume you want /usr/local/bin/clown started at boot time, with the arguments: -name bozo

Make a file in /lib/systemd/system, called “clown.service”. Whatever you call this file (the “clown” part in this example) becomes the name of the service. Here’s what you need in the file:

[Unit]
Description=Clown server for jessie
After=network.target

[Service]
Type=simple
ExecStart=/usr/local/bin/clown -name bozo
Restart=always

[Install]
WantedBy=multi-user.target

The key things you may need to change (besides the obvious command name and arguments) are the Type and the Restart entries.

Type=simple says your program doesn’t fork (i.e., needs to be “daemonized” by systemd). There are other options; look these up in the systemd documentation yourself if you have a more complex scenario.

Restart=always says that any time the program exits it should be started right back up again. This is exactly what I needed as my program isn’t supposed to die, but if it does I want it started again. The systemd program implements throttles on how often this happens in case things have gone haywire.

The [Install] section tells it to run the service whenever the system is in multi-user mode, and the After= part up top tells it not to start the service until the network is up.

Step 2: Tell systemd about this file

It’s not enough to just drop this file into the /lib/systemd/system directory. You also need to execute this command (just once, ever, for a new service file):

% sudo systemctl enable clown.service

You need to do that as root (hence the sudo, or just be root). You’ll get a message about it creating some symbolic links, which is good.

And … that’s it.  Reboot and pray!

User Interface Rant

I have one of these:

bttnm

You get it from these guys: https://bt.tn/

It is, in fact, the simplest internet user interface in the world. It’s just a big red button with WiFi. Without doing any programming you can set it up to send an email, a text, tweet, interface with IFTTT/Zapier, etc. And if you are a programmer it has a REST API and can do web hooks. So, basically, you can use this button for almost anything.

It’s simple. It’s pretty (it’s Scandinavian). It works. It’s awesome.

Except now we get to the rant. The configuration interface.

Like most devices of this nature, you configure it by surfing to the device, which brings up the chicken-and-egg problem of how you tell the device what WiFi network (and password) to use. Bttn uses a fairly common approach (Chromecast also does this) of having the device itself be an access point with a custom WiFi network “bttnconf” in this case.

So, to configure it, you power it up in configuration mode (hold button down while inserting batteries), set your computer onto the bttnconf WiFi network, and surf to the device which is always the “.1” IP address on the local network it establishes (in particular, it is 192.168.0.1).

Rant: and then you see this:

bttn2

which, besides being rather techie and obscure looking (in contrast to the beauty of the physical button), ISN’T THE CONFIGURATION INTERFACE YOU WANT/NEED.

Nope. The home page of the button is some internal configuration page (looks like you are configuring the bttnconf WiFi itself).

The page you need to surf instead is:

192.168.0.1/bttn

Why? Why?? Sure, when I read the instructions the first time (months ago) I “got it right”. But now I needed to redo the configuration, and I thought I remembered how to do it. Power up while holding down the button. Check. See bttnconf WiFi network. Check. Surf to the device.

Not check. Confusion.

In my case, because I was already having problems with the button, this caused me to file a trouble ticket with their support, who very politely reminded me that surfing to 192.168.0.1/ was wrong and that I needed to surf to 192.168.0.1/bttn

Doh!

and then I got the expected, graphically-oriented,interface for filling in my WiFi network name and password.

Shouldn’t the home page of the device be the nice interface, and the internal configuration page be at /config or something like that? Shouldn’t the config page also have a link “If you are trying to set up your button click HERE” or something like that?

Kind of disappointing given all the “design” (meaning appearance/UI) that went into the overall product.

Traffic Light shows Air Quality Index

I recently saw this project: Traffic Light Shows Internet Status at the “WTH” (whiskey tango hotel) website and decided it would be fun to build. So here we go.

I found the same traffic light available on Amazon: http://smile.amazon.com/gp/product/B00IX73BGW

I decided (of course) to make a few changes to the project:

  • I used a BeagleBone Black (BBB), simply because it was something I had sitting in the “random leftover stuff” bin. It’s the same idea as a Raspberry Pi – it’s a small inexpensive box running Linux.
  • I completely redid the internal wiring of my toy traffic light to separate out each LED connection individually (six wires total) whereas WTH implemented his project leaving the original common anode wiring intact (4 wires total coming out of the traffic light). I’d like to say I rewired for a particularly good reason but I didn’t really; I just did it during debugging because I was confused. But, as a result, I am presenting an alternate implementation of the circuitry.
  • I hooked my traffic light up to Numerous (of course) and it is currently displaying my Austin Air Quality Index metric. It displays the red light for bad air quality, yellow for moderate, and green for good.

Modifying the Traffic Light

As WTH did, I opened the base of the light (four screws) and removed the small circuit board inside by cutting its connections.

I then opened the back of the traffic light itself (another four screws). The original connections look like this:

2015-10-21 19.24.29

 

Schematically, the light is wired like this:

 

original-led copy

Notice how they oriented the LEDs to make the common-anode setup easier to wire.

I cut all these connections, took a cat5 cable, separated out three pairs (6 wires) and brought the individual anode/cathode connections from each LED out of the traffic light. Beware software engineers with soldering irons! But it seemed to work out ok.

To help me keep track of what was going on, I was careful to set up this color code:

  • Brown – anode (positive) side of the red LED
  • Brown/white – cathode (negative) side of the red LED
  • Orange – yellow LED anode
  • Orange/white – yellow LED cathode
  • Green – green LED anode
  • Green/white – green LED cathode

Obviously the color choices don’t matter – but if you do rewire your entire light make sure you keep track of which ones are the anodes and cathodes in some methodical manner.

The LEDs need to be wired in series with a resistor (for current-limiting) and connected to the BBB. On the BBB I used GPIO outputs 1-16, 1-17, and 1-18, which are also known in the /sys/class/gpio filesystem as gpio48, gpio49, and gpio50. The BBB has three GPIO chips; chip 0 occupies gpio0..gpio31, so each input/output on GPIO chip 1 is numbered as “n + 32”. Thus GPIO 1-16 is known as “gpio48” in the /sys/class/gpio filesystem.

The pins for gpio48, 49, and 50 are on connector P9 as shown here:

p89

You’ll also need to make a GND connection, which can be common across all three LEDs. I connected it all up according to this schematic:

gpio-led

The BBB GPIO outputs only supply 3.3V whereas the design used by WTH supplies 5V. 3.3V is still enough to light the LEDs but the calculation for the total amount of current (which determines brightness) will be different. The fixed voltage drop across an LED varies by color, but using 1.9V as an approximate average value the amperage calculation for 470Ω looks like this:

(3.3V – 1.9V) / 470Ω = approximately 3ma

This is within the current that the BBB can supply on these particular output pins. The corresponding current flow from the Pi at 5V is:

(5V – 1.9V) / 470Ω = 6.6ma

I decided to try 470Ω and see if it was bright enough for my purposes; it was. If you want to try experimenting you could reduce the 470Ω resistor. Be careful not to overdrive the LED nor overdraw the GPIO outputs.

I stuck with 470Ω as I already mentioned; this has the added advantage of my trivial little circuit board still being ok if I move it to a Pi at 5V.

Controlling the lights

Now to write some software. While I was changing everything else about the WTH approach, I decided to also just use the /sys/class/gpio “special text files” to control the outputs. To do this first you have to “export” the pins you want to control this way. At the shell you do this:

    root# echo 48 > /sys/class/gpio/export
    root# echo 49 > /sys/class/gpio/export
    root# echo 50 > /sys/class/gpio/export

which tells the kernel you’ll be using the filesystem interface for pins 48, 49, and 50. You only have to do this once per boot (assuming no one ever unexports them after you export them).

Then you have to set their direction. You can also give an initial setting (high or low) at the same time:

    root# GP=/sys/class/gpio
    root# echo high > $GP/gpio48/direction
    root# echo high > $GP/gpio49/direction
    root# echo high > $GP/gpio50/direction

At this point you turn an individual GPIO on or off like this:

    root# GP=/sys/class/gpio
    root# echo 1 > $GP/gpio48/value

Writing 1 turns it on; writing 0 turns it off.

I wrote python code to do exactly this. Note that you have to be prepared for the export requests to fail if the pins have already been exported by a previous run. My code for setting up the pins looks like this:

gp = '/sys/class/gpio'
gpdir = gp + '/gpio{}/direction'

pins = {'red':'48', 'yellow':'49', 'green':'50' }

for color in pins:
  try:
    with open(gp + '/export', 'w') as f:
      f.write(pins[color] + '\n')
    with open(gpdir.format(pins[color]), 'w') as dirf:
      dirf.write('high\n')
  except OSError:
    pass

If you want, you could check the OSError and make sure that if something fails it was because the export was already done a previous time. But pragmatically this suffices.

I wrote a python function to turn an individual light on or off:

gpio_v = gp + '/gpio{}/value'

# call with, for example:
#    color == 'red' 
#    onoff == 1
# to turn on the red LED
def light_onoff(color, onoff):
  with open(gpio_v.format(pins[color]), 'w') as f:
    f.write('{}\n'.format(onoff))

# convenience function:
def alllightsoff():
  light_onoff('red', 0)
  light_onoff('yellow', 0)
  light_onoff('green', 0)

Now that we have the basic tools for manipulating the lights, we’re ready for the final code.

Connecting to Numerous

I used my Numerous class library (https://github.com/outofmbufs/Nappy and/or “pip install numerous”) to get the value of a metric I wanted to display; in this case I am reading my Austin Air Quality Index . This is a public metric, anyone who wants to read it is permitted to do so.

The government defines an AQI value of 50 or less as “Good”, a value of 51 to 100 as “moderate”, and values above 100 as various increasing levels of “bad”. I’m displaying those on my light with the obvious mapping to red/yellow/green. The code for doing this looks approximately like this (simplified for presentation here):

import numerous
m = numerous.NumerousMetric('7896524241619416448')

try:
  q = m.read()
except numerous.NumerousError:
  q = -1

alllightsoff()
if q == -1:
  light_onoff('red', 1)
  light_onoff('yellow', 1)
elif q < 51:
  light_onoff('green', 1)
elif q < 101:
  light_onoff('yellow', 1)
else:
  light_onoff('red', 1)

Notice that if there was an error talking to the Numerous server I display both a red and yellow light simultaneously.

The actual code loops around this, reading from Numerous once every three minutes to get any new values.

Bells and Whistles

Right after I get a (possibly) new value from Numerous I run a loop that “rolls” the traffic lights, rapidly looping green, yellow, red, green, yellow, red, etc. This lets you know that the system is working and also turned out to be a cool looking effect. The code for doing this looks like this:

alllightsoff()
dt = 0.03
for i in range(30):
  light_onoff('green', 1)
  time.sleep(dt)
  light_onoff('green', 0)
  time.sleep(dt)
  light_onoff('yellow', 1)
  time.sleep(dt)
  light_onoff('yellow', 0)
  time.sleep(dt)
  light_onoff('red', 1)
  time.sleep(dt)
  light_onoff('red', 0)
  time.sleep(dt)

# ... now update the light based on Numerous

It almost looks visually as if the lights are “spinning” and finally settling on whatever the new value dictates.

In addition to rolling the lights when updating from Numerous, every thirty seconds I blink whichever light happens to be turned on as another way for you to know that the system is still alive and well.

The Actual Code

For presentation purposes here I’ve simplified the code snippets shown in the discussion and edited them to make it fit the screen better. The full source code I am running for my traffic light is here.

Buttoning it all back up

The cat5 wire I used fits very well into the tube/base of the toy traffic light. I did drill a hole in the side of the plastic base so that the light could stand up and the wire could come out through the side of the base. I did this by hand using a pin vise starting with a small bit and basically reaming the hole gradually larger with increasing bit sizes. I’m not 100% sure if that amount of care was necessary, but it worked.

I also wedged some hex nuts into the (now unused/disconnected) battery compartment in the base to weight the traffic light better. I really want to go get some better lead weights for this but for now the hex nuts seem to work reasonably well at keeping the light upright despite the new leverage point from the cable sticking out of the base.

My “circuit” which consists of a whopping three resistors is sitting on a tiny project breadboard that I just double-sticky-taped to the top of the BBB case. The whole thing *almost* fit inside the case; I’m tempted to just hand-solder and hand-construct a small assembly that can in fact be jammed into the case leaving nothing but the cat5 wire coming out of the case and running to the traffic light.

Here’s the result – before I was able to add some cable dressing/management:

done

Air quality was good ( < 50) at the time this picture was taken.

Geeking out even more with Pythagoras and Lego triangles

In case my previous musings on lego triangles weren’t geeky enough for you, here’s some more.

60 degree 3-7-8 / 5-7-8 math

In my prior note I pointed out that you could construct an exact 60 degree angle with a 3-7-8 or 5-7-8 construction, such as this one:

378d60eq91-1024x668

The blue technic beam is the “7” unit leg. Building this within an 8-8-8 equilateral triangle helps convince us that the angle opposite the 7 unit beam is a 60 degree angle.

In the prior post I wrote “This construction is probably demonstrating some deep mathematical relationship between the 3-7-8 60 degree construction and the 5-7-8 construction; perhaps someone will point it out to me and I’ll add it back into this note.”

Well I’ve worked it out for myself.

Review: Trigonometry says that if we know sides a, b, and c and we want to know the angle B opposite side b, we can start with the law of cosines:

b^2 = a^2 + c^2 – 2*a*c * cos B

In the case where angle B is 60 degrees, cosine(60) is exactly 1/2, so this formula becomes:

b^2 = a^2 + c^2 – a*c

Now we can see why (a,b,c) = (3,7,8) forms a 60 degree angle opposite the 7 side:

7^2 = 3^2 + 8^2 – (3*8)
49 = 9 + 64 – 24

The numbers work; (3,7,8) is consistent with that equation and therefore the angle opposite the b side is a 60 degree angle.

It follows from this that if (a, b, c) is a solution then (c – a, b, c) is also a solution. To see this, work the substitution of c-a for a through the equation.

Thus once we know (3,7,8) has the 60 degree angle in it we could find (x, 7, 8) where:

x = c – a
x = 8 – 3

which gets us the (5, 7, 8) solution.

Some other integer solution pairs to this are:

  • (5, 19, 21) and (16, 19, 21)
  • (7, 13, 15) and (8, 13, 15)
  • (11, 31, 35) and (24, 31, 35)

That last pair is huge but might be useful if divided in two using half-unit construction.

I built a nice looking 5,7,8 connection inside a 9-9-9 equilataral, all built using system bricks just as a demo.

5-7-8 inside equilateral; top view
5-7-8 inside equilateral; top view
5-7-8 inside equilateral; bottom view
5-7-8 inside equilateral; bottom view

I had to use “pylons” (visible in the bottom view) to make this work because, as usually happens with the system brick triangle constructions, the adjacent studs will interfere unless you build up using a pylon/riser construction.

Other Fractional Construction Techniques

Lego CAD tools that make use of the LDraw system define brick geometry in units called LDU (an “LDraw Unit” I suppose). A standard system brick is 24 LDU high and the stud-to-stud (or hole-to-hole in technic) spacing is 20LDU. So far we have been talking about constructions using an integer number of holes (20LDU) or half-holes (10LDU).

Because of the 24:20 (6:5) ratio of stud-spacing vs brick height, turning bricks on their side gives offsets other than just integers and halves. Bricks on their sides is called SNOT: “Studs Not On Top” http://www.brickwiki.info/wiki/SNOT_techniques

This allows resolution down to 4LDU for offsets, corresponding to 0.2 of the stud-to-stud distance. By using system bricks (with technic holes as required) we open up many more angle possibilities, including some new Pythagorean triples such as:

(6.6, 11.2, 13)

Of course, that triple was already “available” as an integer construction, with the original Pythagorean triple being an enormous (33,56,65). It could be reduced to (16.5, 28, 32.5) using half-unit construction, but the SNOT techniques allow us to realize that particular construction this way:

sn1

It may be easier to see this in an LDraw:

p2800

I left the pins out of this rendering just for clarity so you could see all the holes.

Look at the vertical element in more detail:

p2800-atd

This shows the general technique for achieving fractional distance at 0.2 resolutions. Every “system” brick laid on its side adds 24 LDU (or 1.2 “holes”) to the distance. As with the technic beams you have to be mindful of the +1 factor because what matters is the center-to-center distance. So it takes a stack of four system bricks on their side to add a total of three times the height of a single system brick. The net of this construction is that the vertical segment is 6.6 units in length. The math for the other part of the construction works similarly.

Recap: Complete Pythagorean Triangle List

Taking all these techniques together, here is the complete list of Pythagorean Triangles you can make with the maximum dimension being less than 25 (there are more above that point), and the angle you get for the hypotenuse. The table is sorted by angle A, the smaller angle of the two non-right angles (the other angle is always 90 – A).

Table without using any SNOT techniques:

 4.5   20 20.5   12.680
   7   24   25   16.260
   6 17.5 18.5   18.925
   5   12   13   22.620
   8   15   17   28.072
   3    4    5   36.870
  10 10.5 14.5   43.603

Table including SNOT triangles:

 2.6 16.8   17    8.797
 4.5   20 20.5   12.680
 3.2 12.6   13   14.250
   7   24   25   16.260   
    ... SNOT version: 2.8, 9.6, 10
   6 17.5 18.5   18.925
 8.8 23.4   25   20.610
   5   12   13   22.620
 7.2 15.4   17   25.058
   8   15   17   28.072
 6.6 11.2   13   30.510
   3    4    5   36.870
  10 10.5 14.5   43.603

Of course you can scale entries in the table. So, for example. you could make the SNOT version of (7,24,25) at (5.6, 19.2, 20) though at that point you probably might as well make it using the integer (7,24,25) construction.