This project has been submitted for the "Exploring Cellular IoT with Hologram Nova and Raspberry Pi" competition on Hackster.io. We are still working on the project but it is now locked for editing so we can't share updates right now - more to come soon!!
Feel free to skip over this first section...
19/01/18
New stuff:
We have some new components that haven't made it into the tutorial below, some have been tested and others haven't. First up, we improved on the crappy rain sensor in the reservoir and now have a water level sensor from Seeed Studio made up of a float and a reed switch. The electronics do not need to be modified but I did use a 10k pull-down resistor - I will up date the schematics shortly...
We also 3D printed a clip to hold it in place:
In the post we received a capacitive level sensor that doesn't need to be submerged as it can be attached to the outside of the reservoir, but we haven't been able to test it yet. This was a little hard to find online, it's called the Open-Smart Capacitive Level Sensor there are some other brands and packages available as well. We also received a much more compact solenoid valve array which is sold by Elecrow - which can distribute one source to 4 seperate locations - but again, this is untested, both are pictured below:
Problems:
The biggest problem we are suffering with is keeping the project water tight. We upgraded to 8mm (inside diameter) tube which made it much easier to 3D print parts and also eased pressure in the system. We also managed to print a good adaptor for the Adafruit Valves which works great with a little teflon (plumbing) tape - so the water works are finally good. The new problem that has emerged however is the planter edges have split under stress with the project being moved around over the last few weeks, we had some hairy moments as a result!! The planter definitely needs a rework.
Drainage isn't great, we will remove all the soil substitute at some point soon and place a layer of gravel at the bottom of the planter to try to improve this.
Also, pretty disappointing after a good run with no issues, we seem to be having some trouble with the script killing itself - but this isn't down to the Pi restarting, I wonder if the Pi is going to sleep or something similar, a small problem I will track down soon, but you can see there are dead periods on ThingSpeak as a result:
Future Plans:
Despite the cover photo showing a packet of tomato seeds, the planter is pretty small so planning to grow vegetables in it was probably a little ambitious - but it could be perfect for herbs! A selection of herbs would have different requirements for soil moisture retention, watering and drainage - so the cloud data would be really helpful in refining watering routines over time as it gives a good indication of drainage over time. So, stay tuned for our growing adventures!
1. Intro:The CSAD IoT Automated Crop Care Project is a proof of concept for a scalable crop care system that features a variety of ambient sensors, automated water distribution and cloud connectivity to monitor historic data and perform analytics with a cellular broadband interface.
Our model includes a filtration system and a water reservoir which can recycle water, and an SMS alert system for the reservoir water level that can easily be adapted for other alerts.
The system is based on the Raspberry Pi Zero W, the Hologram Nova USB cellular modem, Catnip Electronics i2c soil moisture sensors and the ThingSpeak Cloud IoT service. The intention behind this project is to create/contribute to the growing world of open-source systems for crop care automation. We want a system that can be easily scalable to your individual needs - it could be a fun indoor system for a couple of potted house plants or could work for an allotment patch with a wide variety of plants with different needs. Larger projects are feasible in theory, but are not particularly covered in the scope of this tutorial, any comments towards this are of course welcome!
2. System Overview:A Raspberry Pi Zero W is at the centre of this system. A set of python scripts running on the Pi collect data from the sensors, reactively control a DC pump and solenoid valves and push data to the ThingSpeak IoT cloud service. The Hologram Nova cellular interface grants portability and the option for setup in more remote locations (providing there is a 2g/3g cellular service), and also allows for SMS alerts to be sent to the user.
We used the excellent Catnip Electronics i2c Soil Moisture Sensors, which are weather proof and provide data for soil moisture, temperature and light levels. The i2c protocol makes these sensors stackable as they can be wired in parallel, so a good number of them could be used if required for a particular application.
For a small system like our concept model, a single ULN2003a Darlington Array is pretty much the only extenal component required between the Raspberry Pi and the pump / solenoids. The solenoid valves are normally closed, and only draw current when activated to open the valve. The system only needs to water one location at a time, so only one solenoid and the dc pump would be active at any given point - so again, the system can be scaled up by simply adding more water distribution with solenoid controlled valves, this doesn't require any modification to the power supply.
Our concept model has three planters with drainage that falls into a simple filtration unit, and then into a reservoir. This is a closed system that requires topping up with water occasionally, but could just as easily be an outdoor rain water collection / filtering system for the reservoir.
A system flow chart is shown below:
The concept is simple and is similar to a number of other diy projects, if the soil moisture sensors detect that soil in a designated location has become too dry, a valve within a tubing network will open to direct water to that location, and the dc pump will activate to push water through the system and to that location. This concept is enhanced in this model by including the cellular interface, allowing for remote installation, remote access to sensor readings and SMS alerts for the user.
3. Planter Construction (optional):We laser cut a small 3 pot planter out of 5mm clear laser acrylic which looks great! Illustrator files are included if you want to copy or modify our design, but your system could be any indoor or outdoor configuration. Our unit has 2 main parts, a removable top with 3 planters and a base with filtration, water reservoir and houses the electronics.
A small wedge at one end of the unit sets the planters on a slight inclination to allow for drainage towards the planter at the opposite end. There are holes below this planter to allow for drainage into the filter, which in turn will drain the filtered water into the reservoir with the aid of a little gravity. We made a concept model first:
All pieces of the planter unit have smooth edges which we joined with liquid cement, and then made water tight with clear silicone sealant. You only need a small amount of liquid cement to bond two pieces together, but it is very important that the pieces are clean and are not placed under stress during bonding, unlike other types of glue, smooth surfaces are better for bonding than keyed surfaces. Bonding is fast, and it is fairly safe to move things after about 20 minutes. Silicone sealant should be applied generously to every inside edge that needs to be water tight, you can spread it so it sets into the edge using your finger, then use a thin flat card or something similar to get a clean flat finish. For our model, this is working pretty well, but it hasn't been properly stress tested - a jigsaw join between the acrylic pieces might be a better choice. It was also a fairly expensive approach, 6 pieces of 600x400x5mm laser acrylic cost approx £60 - but it does look great! :D
The filter is simply a sealed laser cut tub with holes in the base. It is made up from the bottom up of a layer of cotton sheet, a thin layer of gravel, a layer of activated charcoal chippings and then a second layer of gravel, this should be fine for plant water and will remove most pollutants and debris - but maybe not suitable for human consumption! ;)
The pictures above show the planter with a wire-bent acrylic rod being used to distribute the pipes across the top planter. We have now removed this and replaced it with a bunch of small 3D printed clips that can carry the pipes, these are all included in the CAD files:
Although we haven't tested it yet for planting, the pots have a soil substitute called coco compost. This substitute isn't particularly good for water retention so we added perlite to the mix. The coco compost comes in a dry block and needs to be hydrated, and expands like crazy once it has been! We used a single 10L block to fill the planter with about 2 cups of perlite mixed in.
We are now using 11mm aquarium tubing (8mm inner diameter) to move water around the system. Adaptors and splitters were needed to connect tubes together and to the pump and valves - we 3d printed all of these parts on an Ultimaker 2+ with a 0.6mm nozzle. The Adafruit Valves needed a couple of wraps of teflon (plumbers) tape around the thread in order to stay water tight, but the print should otherwise work great!
We have been plagued with leaks in this project and whilst we managed to fix most of them, we're not quite there yet - if you want to follow our plans make sure you test in a waterproof container, keep electronics safe and towels to hand! The short video below was from an early test of the drainage in the system:
This section covers the construction of the circuitry for the project. If you are new to soldering, Sparkfun have a good tutorial to start with here: Sparkfun Soldering Tutorial
Sensors
Each planter has a Chirp! i2c capacitive soil moisture sensor made by Catnip Electronics. These sensors are based on the ATTiny441 and have been sealed in epoxy resin for rugged weather proofing. The resin doesn't have a major impact on the sensor reading as it is based on capacitance as opposed to conductive resistance. The sensors also have a temperature sensor and a clever means of detecting light levels as well. The sensors communicate over i2c and the i2c address of each sensor can be reassigned, so you can chain many of them together. The sensors can be powered from 3.3V to 5V and connect to the Pi's i2c bus on GPIO pins 3 and 5. The i2c bus will need 10k pull up resistors to work effectively - please refer to the schematic towards the end of this section.
*** I had a small issue with the sensors where the i2c address was reassigning itself to random numbers on power up. The documentation for the sensors mentions that this can happen if you "hot plug" the sensors with the Pi powered on. We think this is down to the Hologram Nova causing a small power dip if it is connected when the Pi is powered on, we noticed that if you connect the Nova when the Pi is powered on then it can cause the system to restart. We got around this by powering the sensors seperately from a 5V regulator, but you could probably use a powered USB hub for the Nova as an alternative.
See the Tindie page for the sensors here: https://www.tindie.com/products/miceuz/i2c-soil-moisture-sensor/, and Ageir's chirp-rpi GitHub repository maintaining a python class for the sensor and with lots of useful commands.
The reservoir has a water level sensor from Seeed Studio, which is a float containing a magnet and a reed switch. When the float is close enough to the reed switch it will close so you can use it just like a normal switch or button. We use a 10k pull-down resistor so if the when the float falls too low the switch opens and the GPIO pin on the Pi will be pulled low (we were previously using a crappy rain sensor which essentially did the same thing).
Solenoid Valves and DC Pump
For a small system like ours, a ULN2003a darlington array should be sufficient for driving a motor and solenoid valve (depending on the current required for operation). The ULN2003a is a DIP package and has 7 npn darlington pairs with the collectors available on individual pins. A logic input pin is associated with each darlington pair and can be activated with logic level signals as low as 2 volts. You could attach 1 pump and 6 solenoid valves to one of these chips, and simply add another chip if you want more valves. The gates are designed to sink current, and are pulled low when you set the associated logic pin high. The collector current of each pin can sink up to 500mA, if you have a pump that pulls more current then you can simply link two collectors (and logic inputs) in parallel. The ULN2003a is also very useful for having pretty much all the protective circuitry needed with internal diodes, greatly reducing the risk of damage to your microcontroller. See the ULN2003a datasheet.
We experimented with a range of different DC pumps and for a variety of reasons from leaks to faulty parts we are yet to settle on a particular model. We liked a peristaltic pump initially because it had a convenient connector for our early 6mm tubing. A peristaltic pump operates on a similar principle to an organic organ, which will squeeze fluid down a tube to move it from one place to another. Inside the pump is a piece of tubing that is squeezed by a rotating piece, creating a vacuum and suction inside the tube. This means the pump can source water from the reservoir without needing to be submerged in it. The pump operates at 12V and pulls about 450mA - I was concerned that this was a little close to the collector-current limit, so I used two pins in parallel on the ULN2003a. BCM23 / GPIO16 activates buffers 3 and 4 on the ULN2003a. It is now looking like we are going to use a diaphragm pump like this, but it is a crazy step up in power so we may need to change to a pin on the Pi that is PWM capable to drop the motor speed!! Remember the ULN2003a buffers should sink current, not source it, so connect the positive pin of the pump to 12V and the negative to the ULN2003a collector. Make sure you know which tube is the input/output on the pump!
After failing miserably at 3d printing our own solenoid valves, we picked up some from Adafruit. These work really well and have a rubber diaphragm seal inside which makes all the difference! The diaphragm also acts as a one-way valve. The valves are also normally closed, and as such they only need to consume current when they need to be opened. The solenoid will activate when 6V - 12V voltage difference is applied across the pins - just like the motor, connect one terminal to the 12V rail, and the other end to a free collector pin on the ULN2003a. I use buffers 5, 6 and 7 on the ULN2003a for three seperate solenoid valves. These buffers are activated by setting BCM pins 14, 15 and 18 (or GPIO 8, 10 and 12) to go "high" on the Pi.
Here is a complete schematic of our model:
And some pictures showing our gnarly prototype (this shows the old rain sensor, not the new water level switch):
WARNING: You need to use a detachable connector for the i2c sensors, I used breadboard type male/female header pins. They all have the same i2c address by default so if they are all connected before you reassign the address, the Pi won't be able to differentiate between them! As you can see in our prototype, pretty much everything can be removed from the proto board.
5. SoftwareRaspberry Pi Setup
We use a Raspberry Pi Zero W which is perfect for the application, it is low cost and it has plenty of capability to expand on this project further with more sensors or solenoid valves. If you have a new Raspberry Pi and need to set it up then please follow the steps here.
If you have a model Zero W like us then setup is a little more challenging than with a standard Pi - but there are some good tricks to making the process fairly painless. You will need a micro SD card, a seperate computer to configure the Pi (I'm using an old MacBook Pro) and a USB power source. The Pi Zero W requires less power than the Pi 3, and I have had no problem powering it from my laptops USB port, otherwise micro USB chargers for phones are fairly generic and easy to find in stores. Also, make sure you have a way to connect the micro SD to your computer - I have a USB adaptor that covers lots of formats, which is super useful as the SD port on my ageing MacBook is very unreliable.
I work entirely "headless" which means I never use the Pi Zero W with a display, I do all my work remotely through an SSH connection with my MacBook Pro. If you want to work on the Pi directly, you will also need a HDMI display, a mini HDMI to standard HDMI lead or adaptor for the Pi, a USB keyboard (and mouse) and a USB adaptor to use the Pi's micro USB port. Personally, I find this is quite an inconvenient way to work so I don't recommend it!
In your browser, navigate to the Raspberry Pi Foundation website and download the latest image for Raspbian Stretch: https://www.raspberrypi.org/downloads/raspbian/
Follow the instructions found in the link in Step 1 to burn the Raspbian Stretch image to the SD card. On the Mac there is now an app called Etcher which makes this process super simple as you won't even need to unzip the image. This takes a little time, so make a nice cuppa while you wait.
If you just finished burning the image onto the SD Card, you will need to remove it and reinsert it in order for your system to detect it again.
Before we start up the Pi, it is possible (and recommended!) to configure the network settings with a little trick by creating a new file on the SD Card. Open a command line editor to modify the SD Card, I use Terminal on the Mac. The SD card now has a root directory called "boot". On Mac, you can navigate to this directory using the command
cd /Volumes/boot/
then we will use a terminal text editor called nano to create the new file and edit it, type the following:
nano wpa_supplicant.conf
This will open the nano editor. Type in the following lines:
ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
network={
ssid="YOUR_NETWORK_NAME"
psk="YOUR_PASSWORD"
key_mgmt=WPA-PSK
}
you will need to enter your network name under ssid= and your password under psk=. Then press ctrl-x to quit, you should be prompted with a message saying, "save modified buffer?" type Y and press return to save the document with the name wpa_supplicant.conf - done! When we start the Pi for the first time, it will copy this file over to the correct location, and your Pi will automatically connect to your WiFi network, but don't do this just yet. In Finder or your file browser, you should see the file:
We also need to enable SSH, this is a little easier than above. In the Terminal window, type:
touch ssh
This will create an empty file called ssh. When the Pi boots up, it will see this file and will activate SSH in response so you can connect remotely.
Here's a little trick I have used once or twice - you can also use most smartphones as a Wifi 'hotspot', you can connect both your computer and the Raspberry Pi to the hotspot to establish a connection between them, a handy trick if you don't have a network you can access, or one that has advanced security.
Now eject the SD card from your computer, pop it in the Pi Zero W and power on...
Let's SSH in to the Pi, your computer must be on the same network for this to work - try entering the following line in your terminal editor:
ssh pi@raspberrypi.local
If this doesn't work (it never does for me!), then we need to know the IP address of the Pi in order to patch in - I use a free app for Mac called LanScan which will scan your current network and report any devices it finds:
I can see the Pi on my home network has the IP address 192.168.0.14, so back in Terminal type the following (use the IP address that you find):
ssh pi@192.168.0.14
You should be prompted by your computer that it is connecting to an unfamiliar device and do you want to continue? - type Y. You should then be asked to type in a password - this is the default Raspberry Pi password which is "raspberry" - type it in and press return, and you are in!
Let's make some quick changes just to finish setting up the Pi for the project. The Raspberry Pi has a command line tool for hardware configuration, open it by typing the command:
sudo raspi-config
Go to 5. Interfacing Options and make sure i2c is enabled, we will need it for the i2c soil moisture sensors.
While we are here, you can change your password and user name if you wish, I also went to Boot Options and set the Pi to boot in Command Line Auto Login, to make sure it wasn't opening up the desktop in the background.
That's everything we need for now, let's move on.
Hologram Nova Setup
Hologram recommends the following libraries are installed on the Pi, first run this command which will get the Pi an up-to-date list of contents for the Raspbian repository:
sudo apt-get update
Then install the recommended libraries with the following command:
sudo apt-get install git git-core build-essential python-dev python-openssl python-smbus python3-pip python-pip screen
Next we want to install the Nova Python SDK provided by Hologram:
curl -L hologram.io/python-install | bash
Test the install was successful using the command:
hologram version
This should return the version of the SDK you just installed.
Before you go any further with the Nova as a network interface, you need to activate the Sim Card - follow the instructions on the hologram website found here: https://dashboard.hologram.io/activate - you will need to create an account with hologram.io as well.
Before you leave the Hologram page, you want to make a note of the Sim device key, it is necessary for some of the things we want to do, navigate to https://dashboard.hologram.io/ and select the new device you have created, mine is called IoTPiZeroW:
In the device options, navigate to the Configuration tab, scroll down to find the section that says "Data Engine" and click on "+Show Device Key"
Save the key in a text file somewhere as we need to use it later.
Now we can test the Hologram Nova works as a network interface. Plug the Sim card and provided antenna into the Hologram Nova and plug the Nova into the Raspberry Pi via the micro USB port. The official Hologram quickstart guide is here.
WARNING: when I connect the Nova interface to the Pi Zero W, it seems to restart the Pi - I guess it causes a small power spike on boot which is a little too much for the Pi. I recommend that you power the Pi off, connect the USB device and then power back on
Once the Nova is connected you should see two LEDs, the blue LED indicates the modem is active and the red LED should be solid if the modem is connected to a 2g/3g network. A simple connectivity test you can perform is to query signal strength with the command:
sudo hologram modem signal
So long as you don't get an error message, then you are good to go!
ThingSpeak Setup
ThingSpeak is a cloud service which has an easy API and is great for displaying data and performing analytics. You can set up a basic account for free. Navigate to the ThingSpeak website here https://thingspeak.com/ and click on the "Get Started for Free" option, which will guide you through setting up a MathWorks account. Once you have registered, you can create a new Channel.
Navigate to the "Channels" tab and choose the "New Channel" option. You will be presented with a configuration page for the channel:
Most importantly for now, give your channel a name, and fill in the fields you want to use - I am using 5 fields at the time of writing, which are for the data from 3 soil moisture sensors, an ambient temperature reading and an ambient light reading:
- Field 1: Planter 1 Soil Moisture
- Field 2: Planter 2 Soil Moisture
- Field 3: Planter 3 Soil Moisture
- Field 4: Ambient Temperature
- Field 5: Ambient Light
Once you have filled in the fields, scroll to the bottom of the page and save the channel. The channel becomes live immediately, but you can update the configuration or reset the data at any point. You can see how my channel looks here: https://thingspeak.com/channels/393003 there isn't too much to see as we haven't actually started growing things and we are still tweaking the system.
Before we move on, we need to get the channels API key for writing data, navigate to the "API Keys" tab and save the 16 digit Write API Key somewhere so you can use it later.
Project Python Code
Nearly there!
We have put together a GitHub repository for the code, this makes it easy to download and run on your Pi, you can find the repository here: https://github.com/AidanTek/CSADIoTCropCareProject
First, lets clone the repository onto the Pi. Go back to your terminal console and if you haven't already done so, SSH in to your Pi. Once you are there, clone the repository into your Documents folder with the following commands:
cd Documents/
git clone https://github.com/AidanTek/CSADIoTCropCareProject.git
This will create a new folder in Documents called CSADIoTCropCareProject, with the python scripts in a folder called "Project" navigate there now with the command
cd CSADIoTCropCareProject/Project
Type "ls" to see the contents of this folder.
There are 3 scripts that are core to the project, main.py, watering.py and sensorReading.py. I have included the python class for the Chirp! i2c Soil Moisture sensors by ageir and also a script so you can reassign the i2c address of the sensors. The main.py script is the program you will normally want to run, and it will access sensorReading.py and watering.py when it needs to.
At this point I assume that you have built the circuit as described in the electronics section, so before we move on we need to assign the i2c address of each individual sensor. It is important to not plug in the Chirp! sensors when the Pi is powered on as this can scramble the i2c address, so with the Pi powered off, attach one of the Chirp! sensors and then power on.
Once the Pi has booted up and you have SSH'd in - type in the following command:
i2cdetect -y 1
You should see something like this:
Only hopefully, you should see an entry for 0x20 (I didn't have a sensor to hand when I took this image!)
If you had to restart the Pi, navigate back to the project folder and open the python script called i2cAddressChange.py with the command:
cd /Documents/CSADIoTCropCareProject/Project
nano i2cAddressChange.py
Each sensor starts with the default address of 0x20. I use the addresses 0x20, 0x21 and 0x22 for my three sensors - if you use something different then you will need to modify sensorReading.py to have the correct address as well. To change a sensors address, type the desired i2c address in the sensorNewAddress field in the script, then press ctrl-x and press Y to save the script. You then need to run the script with the command:
python i2cAddressChange.py
You should get a short prompt to tell you the operation was successful, and this does work fine except the output prompt doesn't show the correct number. Do this for each of your sensors, then check that the change has been successful by running:
i2cdetect -y 1
Once your sensors are set up, you can test them out. The script sensorReading.py has a test mode you can activate, use nano to open the script now:
nano sensorReading.py
scroll right to the bottom of the script to find the line that says testMode = 0, and change this line to say testMode = 1
now save the modification with ctrl-x and run the code with the command:
python sensorReading.py
You should see the reading from all the sensors, including the water level switch if you have it attached which will be outputting 1 or 0 every other line. Oh yes, you can also calibrate the sensors from here - I tested the difference between the sensor reading in open air against it being dunked in a cup of water. You can set the min/max value for each sensor in this script. You need to press ctrl-c to break out of the loop.
Once you are satisfied that things are working, open up sensorReading.py with nano again and change "testMode = 1" back to "testMode = 0"
The same can be done to test your pump and solenoids. Open the script watering.py with nano with the following command:
nano watering.py
Scroll to the bottom of the script, and the process is the same. Change testMode = 0 to testMode = 1. Press ctrl-x to save and then run the script with:
python watering.py
The script will test the watering routine for each pot, so it should activate the solenoid valve, wait a second, activate the pump for a period, deactivate the pump and then deactivate the solenoid valve. Once the routines are all complete, the script will clean up the GPIO and exit. Here is our leaky test:
Don't forget to return to the script and set testMode back to testMode = 0 when you are done.
If everything is working - great! There's only one thing left to do now and that is to set up the main script so it is linked to your ThingSpeak channel, your Sim card and it knows which mobile phone(s) to send warning messages to.
Once again, let's do this with the nano editor:
nano main.py
In main.py, there are a couple of lines you need to edit. Scroll down to find the line that says credentials = {'devicekey': 'xxxxxxxx'} and replace the xxxxxxxx with the Hologram Sim Card device key that you saved earlier:
Next, input the Write API key for ThingSpeak you saved earlier which is a couple of lines below in the field myAPI = "xxxxxxxxxxxxxxxx":
Finally, this script has two circumstances in which a warning SMS is sent to the user using the Nova interface. The first is when the script starts, which will either be because the user starts the script, or because the Pi has restarted and the script has autorun (we haven't put that in yet). The second is a situation where the reservoir level has drained too low, the script will send out a warning SMS. You need to put in the number that you want that SMS to be sent to in both of these cases:
You need to include the national code in the number, so a UK number would look something like "+44776654321". (In the next update I will just make this a field at the top of the script). Once you have made these updates, press ctrl-x and save the script.
If your system is relatively put together, this is a great time to test if everything is working. Because we are using the cellular network, we need to first activate it, and it is a requirement of the Hologram Python SDK that a user with root privaleges executes commands, so we need to execute our script with a sudo command. Run these two commands to start the program:
sudo hologram network connect
sudo python main.py
There is a short pause at the start of the program (the terminal window should prompt you on what is happening) as I think the Hologram Nova needs a little time to reconnect to the network after a text is sent. Observe the LEDs on the Nova to get an idea of which state it is in.
The terminal window should inform you if sensor data has been successfully sent to your ThingSpeak channel, and should also give you live readings. The default cycle time is 15 minutes, it really doesn't need to be faster than that! But if you want to see a bit more activity for testing purposes, change the cycleTime field in main.py to something like 10 (10 seconds).
If everything is working, great work!
6. AutorunThe aim of this project is to allow for it to run remotely, so it needs an autorun script, so it keeps on doing what it is meant to in case of a power cut or some other kind of power failure that causes the Pi to restart. You don't have to do it this way but I would recommend that you install a command line tool called tmux to do this. Tmux will allow you to create a virtual terminal session that the script can run in. This means you will be able to SSH in to the Pi and easily access the running script to check the message prompt, or you can work on other things whilst the script runs in the background.
To install tmux:
sudo apt-get update
sudo apt-get install tmux
Let's check out how it works, enter the command:
tmux
Things look the same, but somehow different - you are now in a tmux session. Try running the main.py script again now:
cd Documents/CSADIoTCropCareProject/Project
sudo python main.py
With the script running, try pressing "ctrl-b" and then "d", this should bring you out to the previous terminal window before you executed tmux. Now try typing:
tmux attach
You should find that you are back in the tmux session, with your script still running, neat!
What's even better is we can automate all of this with a very simple script that will run shortly after the Pi boots up.
In the Project folder create a new file with the following commands:
cd Documents/CSADIoTCropCareProject/Project
touch tmux_autostart.sh
Now let's edit the script using nano:
nano tmux_autostart.sh
In the nano editor, create the following script:
#!/bin/bash
sudo hologram network connect
tmux new-session -d -s IoT 'sudo python /home/pi/Documents/CSADIoTCropCareProject/Project/main.py
and then press ctrl-x and save the script. It should look a little like this:
You can probably figure out what these two commands will do - now we just need to help the Pi know that it needs to point to them when it boots up. We can do this by editing a file in /etc/ called rc.local:
sudo nano /etc/rc.local
(we need to use sudo in this case because /etc/ is a folder than needs a user with root privileges to modify.)
In this file, we need to add the line:
sudo -u pi bash /home/pi/Documents/CSADIoTCropCareProject/Project/tmux_autostart.sh &
the file should look like this:
Press ctrl-x to save and now there is nothing left to do but test it out! Reboot the Pi with the command:
sudo reboot
Once the Pi has restarted and you are able to SSH in, you should be able to use "tmux attach" to switch over to the tmux session that started running after boot - also, if you set up your mobile number in main.py, you should have received a text to inform you the script started.
And we are there! That's the lot folks, now it is over to you to develop this system to suit your own gardening needs. If you look through the scripts main.py, watering.py and sensorReading.py, you should see that it is easy to iterate the software if you want to add more sensors or pumps - if you want advice on doing this, please ask in the comments below.
This is our first hackster.io project and we would really welcome any feedback you have - we are still developing our planter as well (aka plugging leaks!!) so stay tuned for updates and we welcome any advice and pointers on improving the hardware and software!
Comments