“I’d made a video about controlling servo motors using a Raspberry Pi and I wanted to follow that up with a simple, practical project that would put Raspberry Pi-controlled servos into action,” he explains. To that end, the Hamster Feeder was created as a tutorial for his YouTube channel, ExplainingComputers. “It would just need a little refinement to be used to feed a real hamster,” he readily admits.
Air pods
Since his channel focuses on single-board computers, he decided to use a Raspberry Pi Zero running Raspbian for his project. He also handmade two little food pods, mounting a servo on the side of each one.
“The most difficult part of the project was progressing from the idea of ‘let’s use a servo as a catch to open a door at the base of a container’, to actually having two of those little doors on two small containers suspended in the air,” Chris says.
“I happened to have some plasticard sheet and solvent adhesive, but it was very much a situation of working out what I could design and build in a few hours, with the added complication of how to show the process in a video. I remember a very intense and frantic morning!”
Nutty coding
After connecting the servos to his Raspberry Pi Zero, Chris turned to Python and broke his code down into three sections. “The first loads in the GPIO, time, and datetime libraries, before setting up board numbering for the GPIO pins,” he explains. “It then sets up pins 11 and 12 as GPIO outputs with software pulse-width modulation, or PWM, which is what is needed to control servos.”
The second is dedicated to nut loading: “Here the user is invited to close (and hold shut) each pod bay door in turn, and press the ENTER key to allow the servo to move and function as a latch. To maintain a record of each door being closed, variables pod1 and pod2 are set to a value of 1 to indicate when their respective doors are shut.”
Finally, there is a ‘main while’ loop – a control flow statement that can execute statements when a condition is true. “An if and an elif statement compare the current date and time with two hard-coded dates and times in order to check if a pod door should be opened. They also see if a door is still shut by checking its pod1 or pod2 value, and setting this to 0 once a door is opened.”
Feeding frenzy
Of course, improvements could be made. Servos, Chris says, could swing the doors open and closed. “It would also need some chutes to direct the nuts into a hamster cage with the pods and servos entirely separated from a live animal outside of the cage,” he continues. There’s scope to regulate the number of nuts dispensed and to remove hard-coded dates and times in the code.
“I did think of using another servo to raise a flag saying ‘lunchtime’ every time a pod bay released some nuts,” he adds. “This said, I’m not sure that most hamsters can read and which languages they are most familiar with.”