Give your Linux box the power to control real-world events with an inexpensive microcontroller from Parallax, a Python program and some serial port magic.
Cats love toys. Our cats, Cotton and Tulip, slowly have taken over our house with their little plastic doo-dads—ping-pong balls, furry mice, bells, springs and things to scratch. The cats are rarely bored. On the weekends, my wife and I oblige the kittens by tossing their toys around the house, flinging strings and jingling bells. We scratch their backs and feed them treats. They're both in love with these little stinky fish treats; all we need to do is shake the can, and they stop whatever they're doing and dash to the kitchen. Their English lexicon now includes their names and the words good and treats.
Monday through Friday, nine to five, however, the cats are responsible for their own entertainment. While we're away, we're sure the cats have a good time with their toys. Our rugs almost always are moved around, ping-pong balls end up in water dishes and fur covers our chairs. The only real difference between the weekday and the weekend is our presence and the lack of treats.
We have to work, but that doesn't mean our cats should have to go without stinky little fish, right? Why should our economic necessities have a negative effect on their treat times? Isn't it our responsibility to build them an Internet-enabled, Linux-based, cat-feeding device?
Where do we start? Three ingredients are key to our Linux-based Internet cat feeder: logic on the system, a way to talk to a device and a device to talk to. I chose Python for the logic piece, talking over a serial port to a microcontrolled cat feeder of my own design. Let's start at the bottom, the device, and work our way up to the top, the logic.
I first heard about the BASIC Stamp microcontroller from an article on Slashdot in which three guys were using a BASIC Stamp to control a bolt gun. They had taken some great pictures of bolts destroying fruit. Microcontrollers, I soon learned, are everywhere. They're the bits of logic in our microwaves and our remote controls. They are tiny and often difficult to use.
Parallax, Inc., specializes in making microcontrollers for non-engineers, specifically for students and hobbyists. Parallax products are well documented, easy to use and relatively inexpensive. I bought the Homework Board, the most inexpensive starter kit, from Radio Shack for around $75 US. It came with a book, a bag of electronic components for the experiments in the book and the board and chip.
The Stamp itself actually is a PIC microcontroller with some memory. Typically, you need to program microcontrollers with a low-level language, such as Assembly. What sets the BASIC Stamp apart from a typical microcontroller is the programming language you use to make it do stuff. Parallax developed a superset of BASIC, called PBASIC, that makes it easy to build expressive, useful programs quickly. In addition, the Homework Board has an integrated solderless breadboard, which makes for quick rewiring of projects.
The BASIC Stamp has 16 I/O pins. Each pin is set to high, +5V, or low, 0V, based on programs you create. Say you want to make an LED blink. You attach one end to an I/O pin and the other to a ground pin. You write a program that says, every second, turn the I/O pin to high (on), wait for a second, then turn it to low (off). Now replace the LED with a servo, and we've got the start of the cat feeder.
The I/O pins also listen for +5V or 0V. PBASIC even has a built-in function that allows an I/O pin to read serial data, the basis of which are high/low charges that make up binary words. Don't worry too much about serial connections yet; we cover them more in the next section. For now, understand that the BASIC Stamp can receive a command easily from a Linux system over a serial cable and turn on a servo that drives our cat feeder.
Parallax has done a great job of creating a fun community of hobbyists. Two mailing lists are devoted to its products, and dozens of sites have ideas for projects. Although the best integrated development environment for the BASIC Stamp is available only for Microsoft Windows, a tool called bstamp has been created, with Parallax's help, to program a BASIC Stamp with Linux. An example of tokenizing a program and running it, follows:
# bstamp_tokenize catcode.bs2 catcode.tok PBASIC Tokenizer Library version 1.16 # bstamp_run catcode.tok Model: Basic Stamp 2 Firmware version BCD = 16 Ack = 0 Ack = 0 Ack = 0 Ack = 0 Ack = 0 Ack = 0 Ack = 0 Ack = 0 Ack = 0 Ack = 0 Ack = 0 Ack = 0 DEBUG OUTPUT: (Press [Control]-[C] to complete sequence) _________________________________________________________ Waiting for Command Received Command: B Feed the kitty! Waiting for Command Received Command: B Feed the kitty! Waiting for Command __________________________________________________________ Received [Control]-[C]! Shutting down communication!
Everything I know about serial, I learned from the excellent “Serial Howto” by David S. Lawyer and Greg Hankins. It's a thick document, with a lot of interesting, low-level information about the RS-232 standard.
Although the BASIC Stamp communicates with bstamp over a serial connection, the serial port provided with the Homework Board is not a good candidate for true serial communication. Parallax wired the port in a nontraditional way. For one thing, all commands sent to the port are echoed back to the host, which makes two-way communication difficult.
The RS-232 standard dictates that the electrical signals that travel along our cable be +/- 12V. Because of this, if we hook up a serial connection directly to our Stamp I/O pins, we most likely will burn it out, as it expects +5V. The solution is to use an intermediary to lower the 12V signal coming from the PC to 5V and boost the 5V signal coming from the Stamp to 12V. Such a chip does exist, and it is called a MAX232. Luckily, you can get a MAX232-based RS-232-compliant adapter specifically built for solderless breadboards from a Texan named Al Williams. The device is called the RS-1, and a link to his Web site is included in the on-line Resources for this article.
Starting with the 2.4 kernel, Linux names serial ports as /dev/ttyS0, 1, 2, 3 and so on. These device files act like any other file. You open them, read or write to them and close them. The OS buffers reads and writes with a 16k buffer, which is more than adequate for most serial communication. This is good; you don't have to worry about losing bits simply because you weren't reading at the exact moment your device sent them across the wire. It also means you need to flush the buffers explicitly on the OS side when you're ready to send.
Because the port is treated as a file, you need to set the permissions accordingly. In my case, because I ultimately want a CGI program to drive the feeder, I made apache the owner. If you're in a secure environment, you always could chmod 777 /dev/ttyS0, but this obviously is insecure. It's best to decide up front what you want to do with your port and set the permissions in as secure a way as possible.
Because Linux treats our serial port as a file, it's easy to use Python to talk to the Stamp. Python's file object makes it simple to read and write files:
>>> f = open("/tmp/cotton.txt",'w') >>> f.write("Cotton loves treats!") >>> f.close() >>> f = open("/tmp/cotton.txt",'r') >>> f.read() 'Cotton loves treats!' >>> f.close()
As you can see, however, although it's easy to open and close a file, doing so could get tricky if that file actually is a serial port. Fortunately for us, our Python script needs to write only a letter at a time to tell the feeder to dispense a treat. That said, I wanted to use as robust a method of communication as possible, and all this opening and closing worried me, as I see this project as something that always will be a work in progress. Maybe the cats will want to hit a button that sends us a message at work, who knows? The point is, I wanted something that was more serial-aware than a straight file handle. Luckily, someone else wanted the exact same thing. Chris Liechti has been nice enough to create PySerial for exactly this sort of situation. Here's an example of PySerial in action:
>>> import serial >>> sp = serial.Serial(0) >>> sp.portstr '/dev/ttyS0' >>> sp.write("F") >>> sp.readline()
We don't actually open /dev/ttyS0, we open 0. PySerial is smart enough to know we mean the first serial port and opens it accordingly. This also means that PySerial is cross-platform, so you don't have to know that your port is /dev/ttyS0 on one machine and /dev/ttya on another. It's all handled by PySerial.
Now that Python is talking over the serial port, we need to get it on-line. I admit, I'm not terribly fond of Python in a CGI environment. Don't let that stop you though; there's a working group whose mission it is to see the CGI libraries improved, and several Python Web frameworks make CGI unnecessary. In addition, mod_python, in its latest release, has included Python Server Pages (PSP), a PHP-like syntax for mixing Python directly into an HTML page. In short, you have a lot of options when it comes to using Python on-line. For our purposes, however, the Python CGI library is more than enough to keep our kittens well fed.
Here's a brief CGI example for a bare-bones cat feeder:
#!/usr/bin/env python import serial import cgi class Feeder: def __init__(self): self.port = serial.Serial(0) def feed(self): self.port.write("B") print 'Content-Type: text/html' print # Blank line marking end of HTTP headers cgiParameters = cgi.FieldStorage() control = Feeder() control.feed() print "<p>Thanks for feeding the kittens!"
First of all, I import the PySerial and CGI modules and then I declare a class feeder. The constructor for the class opens the serial port. The class has one method, feed, which sends an arbitrary character, in this case B, down the wire to the feeder. On the other end, PBASIC is listening for the character B and dispenses a treat when it sees it.
I built the cat feeder with a carousel design, where the treats would be put into cells, divided by a rotating paddle, driven by a servo. When the paddles rotate, a load of treats drops through a cutout in one of the cells to a food bowl. I used a container meant for storing frozen waffles for the carousel, with a custom cut rotating paddle and a Parallax servo to drive it all. The whole assembly, including the BASIC Stamp circuit, is housed in a plastic storage box in my home office. The box is connected to my Web server on /dev/ttyS0 for the feeder and /dev/ttyS1 for the debug port. Figure 1 is a picture of the cat feeder on my shelf. I'm using Fedora Core 1, with Apache 2.0.48.
The initial problem was how do I determine that the paddles have rotated enough to drop the treats and stop them from rotating? The easiest solution was to put a small sensor on the side of the carousel that would detect a paddle passing in front of it. I chose a sensor from Parallax used primarily to find a black line on the ground. I put a flat black piece of posterboard on the edge of each paddle and the sensor on the bottom of the carousel right after the edge of the hole. When the feeder feeds, the sensor detects when the first paddle moves past; when the second paddle passes the sensor, the servo stops.
I wired up the Stamp relatively quickly over a few days of experimenting. The attached breadboard is a great feature of the Homework Board. I was able to rewire and test circuits quickly without having to solder and desolder. Figure 2 shows the completed schematic. Figure 3 is a picture of the wired-up Homework Board.
Writing the code for the BASIC Stamp mostly was a matter of cutting and pasting code examples from the Parallax Web site. Listing 1 is the final code that I used on the Stamp. PBASIC relies heavily on GOTO statements for flow control, which took some getting used to on my part.
Listing 2 shows the complete Python code we use to drive the feeder. The CGI script uses the built-in shelf module for Python; shelf allows you to store live objects in a DBM database. In addition to shelf, I'm also using the Cheetah Template engine. The line t = Template(open('feeder.tmpl.py').read()) opens an HTML template called feeder.tmpl.py, reads the contents and uses it as the Cheetah template. The template format looks something like <p>The cats have been fed $fed times</p>. When we set the template variable, t.fed, to some number (say 5), the line then becomes <p>The cats have been fed 5 times</p>. My wife, a graphic designer by trade, whipped up some graphics for the page.
The cat feeder is open for business. Occasionally, a treat jams up the works, but 95% of the time, the cats get a stinky little fish. We already have plans for cat feeder v.2.0. We'd love to add a Webcam to see the kittens during the day, as well as move the device to a wireless laptop in the kitchen. The feeder is, as with most of our projects, a work in progress. Feel free to go to the Web site and give Cotton and Tulip a treat.
Resources for this article: /article/7741.