PiPlanter | Going from analog data to the web using python, mysql and php

Here’s a video:

Essentially, the adc reads an analog value and sends it to python. Python connects to a mysql database and adds the data to that. Once the user accesses the php script, a table, containing all of the values, is rendered.
First of all, you’ll need to make a mysql table with the correct specifications:
CREATE TABLE adc_input_data_10(Sample_Number INT NOT NULL AUTO_INCREMENT PRIMARY KEY, Time VARCHAR(100), Channel_1 VARCHAR(100), Channel_2 VARCHAR(100), Channel_3 VARCHAR(100) );
This creates a table that is found in the python script so it is very important that the TABLE values match as well as the column names.
Here’s that python script:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import spidev
import time
import MySQLdb
import sys
import RPi.GPIO as GPIO
import datetime

now = datetime.datetime.now()

pin = 26

GPIO.setmode(GPIO.BOARD)
GPIO.setup(pin, GPIO.OUT)

con = MySQLdb.connect('localhost','adc_user','adc_user_pass','adc_database');
cursor = con.cursor()

spi = spidev.SpiDev()
spi.open(0, 0)
maxcyclenumber = 10

count = 0

def readadc(adcnum):
# read SPI data from MCP3008 chip, 8 possible adc's (0 thru 7)
    if adcnum > 7 or adcnum < 0:
        return -1
    r = spi.xfer2([1, 8 + adcnum << 4, 0])
    adcout = ((r[1] & 3) << 8) + r[2]
    return adcout

for _ in range(maxcyclenumber):
	cursor.execute("INSERT INTO adc_input_data_10(Time,Channel_1,Channel_2,Channel_3) VALUES(%s,'%s','%s','%s')",(datetime.datetime.now().strftime('%b-%d-%I%M%p-%G'),readadc(0),readadc(1),readadc(2)) )
	con.commit() #this is important for live updating
	count = count+1
	print count
	time.sleep (1)

if count == maxcyclenumber:
	GPIO.cleanup()
	con.close()</pre>
This reads the values from the adc (it is wired up as seen in this post)
Here’s the php, it reads the values from the adc_input_data_10 table on the adc_database.
<?php
mysql_connect("localhost", "adc_user","adc_user_pass") or die ("Could not connect: " . mysql_error());
mysql_select_db("adc_database");

$result = mysql_query("SELECT * FROM adc_input_data_10");

echo "<table border='1'>
<tr>
<th>Sample Number</th>
<th>Time</th>
<th>Channel 1</th>
<th>Channel 2</th>
<th>Channel 3</th>
</tr>";

while($row = mysql_fetch_array($result)){
	echo"<tr>";
	echo"<td>" . $row['Sample_Number'] . "</td>";
	echo"<td>" . $row['Time'] . "</td>";
	echo"<td>" . $row['Channel_1'] . "</td>";
	echo"<td>" . $row['Channel_2'] . "</td>";
	echo"<td>" . $row['Channel_3'] . "</td>";
	echo"</tr>";
}

echo "</table>";
mysql_close($con);
?>
This is all very preliminary stuff, and I’ll tighten up the code as time goes on.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.