Tag: automate

Mounting the Raspberry Pi and Servo Motor to a Dry Food Dispenser

Mounting the Raspberry Pi and Servo Motor to a Dry Food Dispenser

You made it to the end! (or you happened to stumble upon this part of the guide). Looking back, part’s one, two and three weren’t so bad now that you’ve got the hang of things. Here in part four we’re going to mount the Raspberry Pi and servo motor onto the food dispenser.

The goals of this part are:

  • Connect the servo motor to the knob of the dispenser.
  • Cut the threaded rod down to size.
  • Mount the servo to the dispenser.
  • Bind the PVC fitting to the dispenser so the food has a path to follow.
  • Mount the Raspberry Pi to the dispenser.

I chose to connect everything to the dispenser and nothing to the stand. This offers a bit of flexibility: with everything relying on the dispenser the stand can be interchanged. Before we get started, power down the Raspberry Pi: sudo shutdown -h

Connecting the Parts

We’ll start by connecting the servo motor to the knob of the dispenser. I originally did this by using tape which actually worked fine for a while. However, over time the tape began to lose its grip on the knob, preventing it from turning as effectively. The tape has been replaced with zip ties which have been working flawlessly:

  • Take the knob of the food dispenser out of the dispenser.
  • To give the zip ties a flat surface to latch onto, I used a hacksaw to square off the rounded edges of the knob.
  • Wrap and connect a zip tie around the knob and servo, tightening it in place. Repeat this process until the servo is securely fastened. Use the image below as a guide to how I went about doing this.
  • Insert your creation back into the food dispenser.

Servo Attached to Knob

This is great! It looks complete, but what you’ll notice if you tried spinning the motor is that it won’t have anything to grasp onto, so it will spin with the knob. We need to fasten the motor to the dispenser. If you look at the top and bottom of the motor you’ll notice two sets of screw holes. The set that’s furthest away from the center of the dispenser knob is the one we’ll be dealing with. Using the image above as reference, that’s the set of screw holes on the top of the motor.

The screw holes are slightly smaller than the threaded rod, so we’ll need to do a tiny bit of surgery to get the rods to fit:

  • Using your box cutter, carefully cut away a very little piece of the plastic at the smallest point of the screw hole.
  • Try pushing the threaded rod into the screw hole. Did it fit? Then move on down! Otherwise repeat the previous steps until it fits snug.

Now we’ll cut the rod to the appropriate length, drill a couple holes into the dispenser and fish the threaded rods through. With the motor/ knob inserted into the dispenser (like the image above):

  • Measure the distance from the screw hole to the dispenser, then add about an inch or two.
  • Using your hacksaw, cut two pieces of threaded rod to the measured length.
  • Place the two pieces of threaded rod into the screw holes of the motor and push them flush against the wall of the dispenser.
  • Make a tiny mark on the dispenser where the threaded rods touch it. This will identify where we need holes for the rods to fit through.
  • Make an attempt to spin the wheel of the dispenser manually by rotating the knob. If any part of the knob hits the rod you’ll need to trim the knob’s plastic down a bit with your hacksaw.
  • Remove the motor/ knob, and the white rubber wheel from inside the dispenser.
  • Stop: obligatory (but very important) warning to put on your safety goggles, please.
  • Drill two holes slightly larger than the threaded rods into the dispenser where you made your markings.
  • Insert the threaded rods through the holes and fasten them down with a couple of hex nuts.

Did you wind up with this?

Threaded Rod in Dispenser

At this point mounting the motor is pretty straightforward. Before we bring it back into the picture let’s get the PVC fitting attached to the hole of the dispenser. We need two holes opposite one another at the mouth of the dispenser, and two more holes at the top of the PVC fitting.

  • Place the mouth of the PVC fitting flush against the mouth of the dispenser.
  • Use a pen to mark slightly below the lip of the PVC fitting closest to the dispenser. Make another mark directly above that on the dispenser itself. Make the same markings on opposite sides of the PVC fitting and dispenser.
  • Using a drill bit large enough for a zip tie to squeeze through, drill holes where you made the marks.
  • Using zip ties, bind the PVC fitting to the mouth of the dispenser.

The result should look something like this:

PVC Fitting Connected to Dispenser

Now that the threaded rods are in place, add back the motor/ knob. Position the threaded rod through the screw holes of the motor and tighten with a hex nut. You probably won’t have enough space to add two hex nuts. That’s alright, I didn’t either:

Motor Attached to Dispenser

Fantastic, we’re mostly there. We just need to mount the Raspberry Pi to the dispenser and we’re done! I mounted my Raspberry Pi as center to the dispenser as I could, but it doesn’t really matter:

  • Place the Raspberry Pi against the body of the dispenser where you’d like to mount it.
  • Make two markings on the dispenser, one on either side of the Raspberry Pi.
  • Drill two holes into the dispenser where you marked it.
  • Using a zip tie, mount the Raspberry Pi to the dispenser through those two holes.
Pi Mounted to Dispenser
Pi Mounted to Dispenser

Congratulations, you did it! An automated food dispenser is now at your command. 

Conclusion

The Raspberry Pi is an incredible little machine with endless possibilities. I sincerely hope this series of posts was as helpful to you as it was me. It was a long journey, but now you’re prepared to tackle any new DIY Raspberry Pi projects that may come your way.

I encourage you to leave comments letting me know what you think. If anything was unclear I’d appreciate hearing about it.

  • In part one we laid out the plan.
  • Part two we set ourselves up with the power of reading emails.
  • In part three we talked all about controlling servo motors.
  • And here in part four we put it all together to make an impressive new toy.

If you enjoyed this series of posts, please be sure to check out my series on building an automatic cat laser pointer toy!

Controlling a Servo Motor with Gmail and Raspberry Pi

Controlling a Servo Motor with Gmail and Raspberry Pi

You covered part one and part two (good work!), or maybe you didn’t and you found yourself here anyway (welcome). Part three is focused on the servo motor, primarily making it spin. Later in part four we’ll wrap things up by connecting it to the dispenser.

As always, let’s start with what it is we’re trying to accomplish here:

  • Connect the servo motor to the Raspberry Pi’s GPIO header pins
  • Write some code to make that motor functional
  • Tie in the GmailWrapper.py script we wrote in part two so the motor spins when the right email lands in your inbox

Here we go!

Connecting the Servo Motor to the Raspberry Pi

If you’re using the same servo motor as me, it has power, ground and control wires. If you decided to use the standard non-continuous servo motor (which is a viable alternative since we won’t be performing a full revolution), then: power is red, ground is black and white is control.

Connect your male-to-female jumper cables to the servo. Now, using the GPIO diagram below as reference, connect the wires to the Pi’s GPIO headers as follows:

Note: this diagram is for Raspberry Pi’s with 40 pin GPIO, but the below works with 26 pin GPIO as well.

  • power connects to header pin 2 (5v power)
  • ground (black wire for standard servo) connects to header pin 6 (Ground)
  • control (white for standard servo) connects to header pin 12 (GPIO18)

GPIO Pinout Diagram

Here’s what mine looks like (don’t mind the zip tie):

Servo Connecting to Pi
Servo Connecting to Pi’s GPIO

 

Writing Code to Make the Servo Motor Spin

Before getting started, let’s update our Pi to the latest packages and install the GPIO library. Run this in the terminal:

sudo apt-get update
sudo apt-get upgrade
sudo apt-get install rpi.gpio

We’re all set. In the terminal, create a new python script using nano: sudo nano CatFeeder.py

Within the CatFeeder.py script, add the following code:

#!/usr/bin/env python

import RPi.GPIO as GPIO
import time

def feed():
    # let the GPIO library know where we've connected our servo to the Pi
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(18, GPIO.OUT)

    try:
        servo = GPIO.PWM(18, 50)
        servo.start(12.5)

        # spin left, right, then left again rather than in a continuous circle
        # to prevent the food from jamming the servo
        for index in range(0, 3):
            dutyCycle = 2.5 if (index % 2 == 0) else 12.5
            servo.ChangeDutyCycle(dutyCycle)
            # adjust the sleep time to have the servo spin longer or shorter in that direction
            time.sleep(0.8) 
    finally:
        # always cleanup after ourselves
        servo.stop()
        GPIO.cleanup()

if __name__ == '__main__':
    # kick off the feeding process (move the servo)
    feed()

Save and exit the nano editor: CTRL+X, then Y, then Enter. Moment of truth, time to make that servo move! Let’s drop back into the Python interpreter, in the terminal:

# remember, hit enter after each line to have the interpreter... interpret
python
import CatFeeder
CatFeeder.feed()

I hope that went smooth for you, because I just got really excited. Welcome to physical computing! You moved a physical object with code, hell yeah.

GmailWrapper, Meet CatFeeder: Putting it all Together

Alright, so we’ve created a way to read emails, and we’ve created a way to move a servo motor. Now we need to combine the two so the servo motor moves when we read emails.

Open CatFeeder.py in nano and add the highlighted lines of code: sudo nano CatFeeder.py

#!/usr/bin/env python

from GmailWrapper import GmailWrapper

import RPi.GPIO as GPIO
import time

HOSTNAME = 'imap.gmail.com'
USERNAME = '<your gmail username>'
PASSWORD = '<your app password or regular gmail password>'

def feedByGmail():
    gmailWrapper = GmailWrapper(HOSTNAME, USERNAME, PASSWORD)
    ids = gmailWrapper.getIdsBySubject('feed cats')
    if(len(ids) > 0):
        try:
            feed()
            gmailWrapper.markAsRead(ids)
        except:
            print("Failed to feed cats, they're starvingggg")

def feed():
    # let the library know where we've connected our servo to the Pi
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(18, GPIO.OUT)

    try:
        servo = GPIO.PWM(18, 50)
        servo.start(12.5)

        # spin left, right, then left again rather than in a continuous circle
        # to prevent the food from jamming the servo
        for index in range(0, 3):
            dutyCycle = 2.5 if (index % 2 == 0) else 12.5
            servo.ChangeDutyCycle(dutyCycle)
            time.sleep(0.8)
    finally:
        # always cleanup after ourselves
        servo.stop()
        GPIO.cleanup()

if __name__ == '__main__':
    # kick off the feeding process (move the servo)
    # we now use our new feedByGmail method to handle the feeding
    feedByGmail()

Save and exit the nano editor: CTRL+X, then Y, then Enter. As always, let’s give it a test. Send yourself an email with the subject feed cats. Drop into the python interpreter once the email arrives:

python
import CatFeeder
CatFeeder.feedByGmail()

Did it work? It did? Excellent! If it didn’t, don’t be discouraged! Python’s support community is huge, you’ll find the answer. Plus, you can always leave a comment below.

Scheduling a Cron Job to Run Our Script Regularly

We have code to move our servo motor when the correct email lands in our inbox, but it currently only runs when we physically tell it to. Let’s fix that by setting up a cron job to run our script every 60 seconds.

In order for the cron job to execute our script, we need to make our script executable. This is done by issuing the following command in the terminal: sudo chmod +x CatFeeder.py

Now we’ll add the cron job. In the terminal: crontab -e. Add the following after the very last commented line (comments start with #):

* * * * * python /path/to/your/script/CatFeeder.py

As Gabe called out in the comments, adding python after the last asterisk (*) in the line above will force the python interpreter to be used while running our script. We’re in the nano editor, so save and exit: CTRL+XYEnter. Easy as Pi (sorry). A job is now running every 60 seconds with the sole task of looking for emails and feeding cats. Don’t believe me? Give it a shot, send yourself an email with the subject feed cats.

A nicety of cron jobs is they’ll continue running automatically if your Pi ever restarts.

Scheduling an Email to be Sent Regularly

We have the code, we have the cron job. Sending an email on demand will cause the servo motor to spin, but what about spinning it on a schedule? That’s where we’ll make use of IFTTT. IFTTT stands for if this then that and allows you to connect two disparate systems based on what they call a “recipe” (trigger and action). For our purpose, we need the clock to trigger an email to be sent (action). Here’s what to do:

  1. Setup an account if you haven’t already
  2. Use IFTTT website or download the app to your phone and log in
  3. In the My Applets section, add a new applet
  4. You’ll see a screen saying if +this then that: click the +this button, then select the Date & Time service.
  5. Select the Every day at trigger, and select the time you’d like the cat feeder to activate, then hit next
  6. Now you’ll see +that, click it and find the Gmail service. You’ll need to connect the service to your Gmail account. Once finished, set the action to Send yourself an email with the subject Feed cats.
  7. Hit next, then Finish

There you have it, every day at the time you specified an email will be sent to your account. If you had any issues setting up the IFTTT recipe, check out this post for a really nice and in-depth walk-through.

Having fun? Here’s Other Ways to Send an Email

Alexa

Alexa integrates nicely with IFTTT. In the IFTTT app, create a new recipe with the trigger (+this) connecting to Alexa. You’ll need to connect the service like you did for Gmail. Once connected, set the action (+that) to send an email, like we did in the previous section.

Hands free feeding at your ready: Alexa, trigger the cat feeder.

The DO Button App

Created by the IFTTT team, the DO Button app and accompanying widget provides a straightforward way to trigger the action. You! You’re the trigger. You setup a recipe, same as before, except you’ll notice there’s no +this. You are the +this. You open the app and click the button, it then triggers an email. This app can also be configured to show on your iPhone or Androids home screen, so triggering the email is even easier.

Conclusion and Next Steps

Part one has goals and items covered, part two has Gmail automation down, and part three provided the spinning of the motor. A lot has been done so far, we’re nearly there. Up for part four? That’s where I’m headed to connect the Pi and motor to the dispenser.

Reading Gmail with Raspberry Pi and IMAPClient

Reading Gmail with Raspberry Pi and IMAPClient

In part one we covered the basics of what we’re trying to build, and what you’ll need to get started. Here in part two we’ll be playing with some python code to interact with our Gmail account using IMAPClient. Later on, part three is focused on the servo motor, while part four connects it all to the food dispenser.

The goal of this part?

  • Setup your Gmail Account with 2-step authentication for a secure way to interact with it through code. 
  • Write some code to interrogate your inbox for an email and mark it as read when found using the IMAPClient library.

Let’s get to it!

Preparing Your Gmail Account with 2-step Authentication

This is not strictly necessary, but a good security practice. If you don’t mind your credentials being in plain text in your code, feel free to skip ahead.

Since we’re going to be using email as the trigger, we’ll need a way to securely log into our Gmail account from code. You could store your credentials in plain text within the code we write, but I strongly discourage that. Instead, make use of Gmail’s two-step authentication and app passwords

I created a new Gmail account for this purpose.

  1. Log into your gmail account
  2. Navigate to the Sign-in and security page
  3. Under the Signing in to Google section, click the 2-Step Verification menu, then follow the instructions to enable 2-Step Verification
  4. Back in the Sign-in and security page right under the 2-Step Verification button you’ll see App passwords
  5. Generate a password
    1. Note: this password will be 16 digits with spaces separating every 4 digits (e.g. xxxx xxxx xxxx xxxx). Please be sure to include the spaces!

The password you generated can be used to log into your Gmail account. We don’t need it right this second, but we’ll be using it to scan for an email that demands we feed the cats!

Writing Code to Read Your Gmail

Now that we have a Gmail account ready to rock, let’s write some code to interrogate it. We’re going to be using the IMAPClient python library for this purpose, and we’ll wrap the calls to this client in our own Python class.

Install IMAPClient now from the terminal: sudo pip install imapclient

Create the GmailWrapper.py Script

Now let’s create our Gmail wrapper class: nano GmailWrapper.py. Within the GmailWrapper.py script, add the following code:

#!/usr/bin/env python

from imapclient import IMAPClient, SEEN

SEEN_FLAG = 'SEEN'
UNSEEN_FLAG = 'UNSEEN'

class GmailWrapper:
    def __init__(self, host, userName, password):
        #   force the user to pass along username and password to log in as 
        self.host = host
        self.userName = userName
        self.password = password
        self.login()

    def login(self):
        print('Logging in as ' + self.userName)
        server = IMAPClient(self.host, use_uid=True, ssl=True)
        server.login(self.userName, self.password)
        self.server = server

    #   The IMAPClient search returns a list of Id's that match the given criteria.
    #   An Id in this case identifies a specific email
    def getIdsBySubject(self, subject, unreadOnly=True, folder='INBOX'):
        #   search within the specified folder, e.g. Inbox
        self.setFolder(folder)  

        #   build the search criteria (e.g. unread emails with the given subject)
        self.searchCriteria = [UNSEEN_FLAG, 'SUBJECT', subject]

        if(unreadOnly == False):
            #   force the search to include "read" emails too
            self.searchCriteria.append(SEEN_FLAG)

        #   conduct the search and return the resulting Ids
        return self.server.search(self.searchCriteria)

    def markAsRead(self, mailIds, folder='INBOX'):
        self.setFolder(folder)
        self.server.set_flags(mailIds, [SEEN])

    def setFolder(self, folder):
        self.server.select_folder(folder)

Save and exit the nano editor: CTRL+Xthen Y, then Enter.

Verifying the GmailWrapper.py Class Works

Let’s do a test: our script is going to log into the Gmail account, search for email with a specific subject, then mark it as read. Before running the code, send yourself an email with the subject feed cats (the search is case-insensitive, by the way).

We’re going to use the Python interpreter to run our tests. In your terminal make sure you’re in the same directory as the GmailWrapper.py class we just created, then:

# press enter after each line for the interpreter to engage

# invoke the interpreter
python

# import our wrapper class for reference
from GmailWrapper import GmailWrapper

# create an instance of the class, which will also log us in
# the <password> should be the 2-step auth App Password, or your regular password
gmailWrapper = GmailWrapper('imap.gmail.com', '<your gmail username>', '<password>')

# search for any unread emails with the subject 'feed cats', and return their Ids
ids = gmailWrapper.getIdsBySubject('feed cats')

# have the interpreter print the ids variable so you know you've got something
ids

# now lets mark the email as read
gmailWrapper.markAsRead(ids)

# exit the interpreter
quit()

If everything went as planned your email should now be marked as read. Pretty neat!

Conclusion and Next Steps

Part one set the goals and outline. Now with part two wrapped up we have the ability to discern whether or not an email exists. With this power we can trigger certain events, such as spinning a servo motor. That’s exactly what we’re going to do in part three, I’ll meet you there.

Later on in part four we’ll be attaching the Pi and servo motor to the dispenser, but before we make anything permanent let’s get that servo spinning.