Latest news about Bitcoin and all cryptocurrencies. Your daily crypto news habit.
This article is part of a serie about how to spy your pet with Raspberry Pi, donât miss the first steps !
- Spy your pet with a Raspberry Pi Camera Server where I describe how to set up a Raspberry Pi and a camera stream server!
- How to access your Raspberry Pi Camera from anywhere where you will learn how to configure everything for remote control.
On the previous articles, we learned how to build a Camera server and access it from anywhere. But having a camera is quite basic stuff nowadays right ? How cool would it be to trigger a food dispenser for your companion at home !
Required material
Letâs sum up the required materials that youâll have to buy.
- A Raspberry Pi and a configured Wifi Dongle
- A food dispenser of course. It has been quite a challenge to find one in France. I recommend getting a small one with hard plastic blades. Donât forget that youâll have to strongly paste or screw a motor on the spinner. So you might not want a metal one !
- A motor strong enough to rotate the spinner but not to powerful in order to be natively compatible with the Raspberry Pi voltage (5V).
About motors : There are many kind of motors. The simple spinning ones are called DC motors. Then, steppers motors which can stop at certain positions. Finally, servo motors where position can generally be accurately set between 0 and 180°. (However, 360° servo motors exists aswell). For more details, check out this great summary.
Because I wanted to have the possibility to trigger different food doses for my bunny, I decided to go for a servo motor. I took the Adafruit Continuous Rotation Servo since it was perfectly suited for Raspberry Pi GPIOÂ voltage.
In order to get use to Raspberry PI electronic pins, I strongly recommend you to buy a tutorial kit which will make you confortable using the GPIO pins ! The CamJam Kit is perfect for that !
Plug-in everything up !
Good ! We are all geared up to plug-in everything and start coding our first python script to activate the servo motor. Letâs first plug everything correctly by following this scheme.
Pretty straight forward right ? Letâs sum up
- Plug the servo positive red wire to the Pi 5VÂ pin
- Plug the servo negative black wire to one of the Pi grounds
- Plug the control orange wire to one of the Pi GPIO (exemple : BCM18 in the picture).
How to recognize the pins names ? Go and bookmark this page
(Optional) Configure your development environment
In the next chapter, we are going to code scripts and launch many commands. Knowing that it can be tiring to switch from our computer to our Pi every time. If you would like to configure your computer so you can develop and launch commands remotely on your Pi using your favorite code editor, I strongly recommend following this great tutorial : Getting started on raspberry PI in less than 10min
Create the rotation script in Python
Now letâs get back to our servo ! We need to build the script that is going to trigger it. While the RaspberryPi (& Raspian) run Python out-of-the-box, you need to install pip for easy installation/removal of packages. On your raspberry Pi, type :
# Install python pip package manager curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
Thanks to pip, we are now able to download and use a super usefull library to manipulate by code the raspberry PI electronic pins.
pip install RPi.GPIO
Now lets create our servo script !
# Create the directorymkdir pet-feedercd pet-feeder
# Create the file with execution rightstouch feed.pychmod +x feed.py
How to use the servo controller
Everything is ready, we can start coding. What we want to do is control the servo by sending electricity pulses into the control wire of the servo. Thatâs the way is works. Referring to Adafruit documentation we have this :
Position "90" (1.5ms pulse) is stop, "180" (2ms pulse) is full speed forward, "0" (1ms pulse) is full speed backwards
This means that, as long as the control wire is receiving electricity pulses (with a duration of 2ms each), the servo will continuously go forward at full speed.
But.. the Pi is only capable of delivering a constant current of 3V through the GPIOs, how am I going to make pulses ?
The library RPi.GPIO that we installed earlier has everything we need ! What we want to use is called âPulse wave modulationâ. You can import it in your Python script like this.
##!/usr/bin/env pythonimport RPi.GPIO as GPIO
Now, letâs configure the library with our plugged servo. First, set the mode to BCM in order to have your pins matching the GPIO names and NOT the physical locations.
GPIO.setmode(GPIO.BCM)
Next, letâs setup which pin is going under our control. If you took the BCM18 like in the picture above, then :
FEED_SERVO_CONTROL_PIN = 18GPIO.setup(FEED_SERVO_CONTROL_PIN, GPIO.OUT)
Finally, letâs initiate the pulse wave modulations to activate the servo forward movement. To do this, youâll have to play with two variables : frequency and duty cycle in order to reach the required pulses. (1.5ms pulse is stop, 2ms pulse is forward, 1ms pulse is backwards)
Frequency is the amount of pulses there are going to be per second. It is always expressed in Hertz. Example :
- 1 hertz = 1 pulse / second â 1 pulse = 1Â second
- 100 hertz = 100 pulse per second â 1 pulse =Â 10ms
Duty cycle is the fraction of one period in which a signal is active. In simple terms, the percentage of active signal during a pulse. Example :
- A pulse of 10ms with a 10% duty cycle is 1ms of active signal
- A pulse of 10ms with a 20% duty cycle is 2ms of active signal
Wait⊠isnât it the exact pulses weâre looking for ? Yes !! we have our variables all set !
# Import time to manage servo activation durationimport time
# Let's set the frequency and dutycyclePWM_FREQUENCY = 100FULL_SPEED_FORWARD_DC = 20FULL_SPEED_BACKWARD_DC = 10
# Activate the servo !pwm = GPIO.PWM(FEED_SERVO_CONTROL_PIN, PWM_FREQUENCY)pwm.start(FULL_SPEED_FORWARD_DC)
# Let it run for 3 secondstime.sleep(3)
# Let's go backward now !pwm.ChangeDutyCycle(FULL_SPEED_BACKWARD_DC)time.sleep(3)
# Stop and Clean everythingpwm.stop()time.sleep(0.5)GPIO.cleanup() # Very important !
Ready to try out your script ? Save your code and launch it using :
# and the magic appearspython feed.py
Script summary
Launch your script from a browser
Letâs move further and launch our script though a browser instead of typing command lines in the terminal. First of all, we need to have a local server on our Pi, capable of running python scripts.
Download and install Apache on Raspberry Pi
# Install apachesudo apt-get install apache2# Make it Python friendlysudo a2enmod cgid
By default, Apache will create a test file under /var/www/html/index.html. Copy paste your directory next to that file.
mv ~/pet-feeder /var/www/html
Finally, make Apache able to read our script inside this particular folder.
# open the file as rootsudo vim /etc/apache2/sites-enabled/000-default
Add the python cgi-script handler to it.
Finally restart apache and test everything in your computer browser directly !
# Restart Apachesudo service apache2 reload
# Find out your Pi IP addressip addr show wlan0 | grep inet
# Go to your computer browserhttp:<IP_ADDR>/pet-feeder/feed.py
Launch the script from internet (router and server configurations)
If you didnât follow the previous tutorial, I strongly recommend you to check it out. Youâll have to do exactly the same thing ! However this time, we will change the redirection port. Previously, we were handling request from port 8081 because it is the camera stream server. Now, we also want to handle requests from port 80, simply because it is apache default port.
To do that, we simply add another Port Forwarding rule to our router. Please find all the explanations on the âConfigure the port forwarding to your PIâ section. At the end, thatâs how it should look like.
The important part here is the redirecting rule 80:80We are actually telling our router: Please redirect all outside world request coming in with port 80 to the raspberry Pi on port 80.
Reboot your router to take account of the new port forwarding rule. and letâs find out if it works !
https://<your_ddns_name>.dyndns.com:80/pet-feeder/feed.py
Just like on the previous tutorial, try this with a different connection than your home. For example, on your smartphone 4G. When being inside your local network, trying to use the DDNS may not work. This is a limitation with routers.
(Optional) Want a little extra ?
What about making a daily task that will give a treat to our pet every couple hours ? Does that sounds cool đ? Here you go !
Crontasks
Crontasks are instructions that you can configure to execute desired tasks (in the background) at designated times.
# Open the crontab panelcrontab -e
# Add your feeding task# FEED PET EVERY DAY AT 9AM AND 6PM0 9,18 * * * python /var/www/html/pet-feeder/feed.py >/dev/null 2>&1
The five time-and-date fields are as follows: minute (0â59), hour (0â23, 0 = midnight), day (1â31), month (1â12), weekday (0â6, 0 =Â Sunday).
OMG ! At last ! We finally have a way to both see and feed our little companion through a connected cage !
Why not going one step further ? In the next tutorial we will learn how to incorporate even more electronics by adding buttons on the cage. Check it out đ !
Build a connected food dispenser with Raspberry Pi was originally published in Hacker Noon on Medium, where people are continuing the conversation by highlighting and responding to this story.
Disclaimer
The views and opinions expressed in this article are solely those of the authors and do not reflect the views of Bitcoin Insider. Every investment and trading move involves risk - this is especially true for cryptocurrencies given their volatility. We strongly advise our readers to conduct their own research when making a decision.