从ADS1115 Python向MySQL插入数据

2024-06-25 23:51:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我在用adcads1115从树莓pi的加速度传感器中提取数据时遇到了一个问题。在

我使用这段代码将数据插入mysql

# Author: Tony DiCola
# License: Public Domain
# Import the ADS1x15 module.
import Adafruit_ADS1x15
import MySQLdb
import time
import datetime
# Create an ADS1115 ADC (16-bit) instance.
adc = Adafruit_ADS1x15.ADS1115()
# Or create an ADS1015 ADC (12-bit) instance.
#adc = Adafruit_ADS1x15.ADS1015()

# Note you can change the I2C address from its default (0x48), and/or the I2C
# bus by passing in these optional parameters:
#adc = Adafruit_ADS1x15.ADS1015(address=0x49, busnum=1)

# Choose a gain of 1 for reading voltages from 0 to 4.09V.
# Or pick a different gain to change the range of voltages that are read:
#  - 2/3 = +/-6.144V
#  -   1 = +/-4.096V
#  -   2 = +/-2.048V
#  -   4 = +/-1.024V
#  -   8 = +/-0.512V
#  -  16 = +/-0.256V
# See table 3 in the ADS1015/ADS1115 datasheet for more info on gain.
GAIN = 1

time_sensor = time.time()
# Main loop.
x = [1]*4
y = [2]*4
z = [3]*4   
for i in range(4):
    x[i] = adc.start_adc(i, gain=GAIN)
    y[i] = adc.start_adc(i, gain=GAIN)
    z[i] = adc.start_adc(i, gain=GAIN)
# Read the specified ADC channel using the previously set gain value.
# Once continuous ADC conversions are started you can call get_last_result() to
db = MySQLdb.connect("localhost", "root", "raspberry", "sensor_log")
curs=db.cursor()

while True:
    try:
        curs.execute("""INSERT INTO table_sensor_log(time, koordinatx, koordinaty, koordinatz) 
        values(%s,%s,%s,%s)""",(time_sensor,x[i],y[i],z[i]))
        db.commit()
    except:
        print "Error"
        db.rollback()
    time.sleep(1)
db.close()

问题是当我运行该脚本时,接收到的数据是重复的,该脚本只从加速度计传感器的第一个数据中获取数据,然后重复插入。在

这就是我得到的。在

^{pr2}$

我需要传感器的真实数据,如果我使用print,数据会正确显示,但是当我把它插入mysql时,数据会是这样的。在


Tags: the数据importadafruitdbtime传感器sensor
2条回答

ads1115只有一个模拟读卡器,你可以看到4个模拟管脚,但是所有的模拟读卡器都通过多路复用器连接到一个模拟读卡器上, 所以当你试图读pin0到pin1时,多路复用器需要时间来转换。对于一点点你必须延迟,可能是10微秒。 你可以看到在数据表ads1115刚刚读860在连续模式。连续模式意味着你只需要读一个针。如果您在ads1115上读到4针,您必须等待

在循环内移动光标初始化

while True:
    try:
        curs=db.cursor()
        curs.execute("""INSERT INTO table_sensor_log(time, koordinatx, koordinaty, koordinatz) 
        values(%s,%s,%s,%s)""",(time_sensor,x[i],y[i],z[i]))
        db.commit()
        curs.close()
    except:
        print "Error"
        db.rollback()
    time.sleep(1)

相关问题 更多 >