PiPlanter | Interfacing an ADC, Python, and MySQL [Documentation]

As this post is more of an update, I won’t be adding any explanations, just giving the python code.

This will read 3 values from the adc and put them into the database “adc_database”. It will put them in the table “adc_input_data_4″ in the columns “Channel_1″,”Channel_2″ and “Channel_3″ respectively.

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import spidev
import time
import MySQLdb
import sys
import RPi.GPIO as GPIO

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)
count = 0
maxcyclenumber = 5

tmp = "derp"

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):
	
	GPIO.output(pin,True)
	cursor.execute("INSERT INTO adc_input_data_4(Channel_1,Channel_2,Channel_3) VALUES('%s','%s','%s')",(readadc(0),readadc(1),readadc(2)) )
	GPIO.output(pin,False)
	
	count = count+1
	print count
	time.sleep (1)
	
if count == maxcyclenumber:
	GPIO.cleanup()
	con.commit()
	con.close()

There you go, bigger post coming later tonight.

Leave a Reply

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