Prerequisites
This project assumes you are familiar with the following projects/lessons:
Setup
Before getting started, make sure you have the following parts.
Step 1
Simply connect your Plant Kit to your Raspberry Pi. Note: for this project, you will only need the Soil Moisture Phidget.
If you haven't set up your Raspberry Pi with Phidgets yet, visit this project.
Logging Soil Data
The first step is to log soil mositure data to a file. To do this, create a Python script called soil.py on your Desktop and copy the code below into the script.
If you need a reminder of how create a Python script with Phidgets, revisit the Getting Started Course.
#Add Phidgets library
from Phidget22.Phidget import *
from Phidget22.Devices.VoltageRatioInput import *
#Required for sleep statement
import time
#Used to get current time
from datetime import datetime
#Used to check file status
import os
#Check file status
if(not os.path.isfile('/var/www/html/soil_data.csv')):
with open('/var/www/html/soil_data.csv','x') as datafile:
datafile.write("Date,Soil\n")
#Create
soil = VoltageRatioInput()
#Open
soil.openWaitForAttachment(1000)
#Get time
now = datetime.now()
#Format time
time_string = now.strftime("%Y-%m-%dT%H:%M:%SZ")
#Get soil moisture level
soil_string = str(soil.getVoltageRatio())
#Write data to file in CSV format
with open ('/var/www/html/soil_data.csv','a') as datafile:
datafile.write(time_string + "," + soil_string + "\n")
The Python script above does the following
- Checks if a file called soil_data.csv already exists at /var/www/html. If it does not exist, it creates the file and writes the headers for our CSV file.
- Creates and opens the Soil Moisture Phidget.
- Gets the current time and formats it.
- Gets the current soil moisture value.
- Opens the CSV file at /var/www/html/ and writes a single line including the date and the soil moisture level. This file will later be opened by a webpage and the data will be displayed on a graph.
After creating the Python script and copying the contents above, you can try running the program. If it was successful, you should see a file called soil_data.csv appear at this location: /var/www/html
Schedule With Cron
Next, schedule your Python script to run every minute using the cron command below. If you haven't used cron before, check out this project.
* * * * * python3 /home/pi/soil.py
Modify Your Website
Next, overwrite your index.html at /var/www/html file with the webpage code below. If you haven't set up a webpage with the Raspberry Pi before, visit the prequisites tab above for more information.
Practice
- Try improving the look of the website.
- Try filtering the data from the file so users can view montly data, yearly data, etc.