Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
python error
#11
Hey guys, I am getting the sensor readings as output but I want to store into sqlite database where I am able to create table but couldn't insert output data of sensors into my database. Please help.

import time
import grovepi
import math
dbname='sensorsData.db'
import sqlite3
import sys



sampleFreq=1*60

#def getDHTdata():
sensor=4
blue=0
 #   DHTpin=16
conn=sqlite3.connect('sensorsData.db')
curs=conn.cursor()

while True:

  try:
          [temp,humidity]= grovepi.dht(sensor, blue)
          if math.isnan(temp)==False and math.isnan(humidity)==False:
              print("temp=%.02f C humidity=%.02f%%"%(temp, humidity))

      except IOError:
                    print ("Error")


#def logData (temp,hum):

sql="insert into table_name(timestamp, temp, hum) values (1, 2, 3);"
cursor.execute(sql)
db.commit()
#curs.execute("INSERT INTO DHT_data values(datetime('now'), (temp), (hum))", (1$
#con.commit()
#conn.close()

print ("\nEntire database contents:\n")

sql="insert into table_name(timestamp, temp, hum) values (now, temp, hum);"
cursor.execute(sql)
db.commit()
#curs.execute("INSERT INTO DHT_data values(datetime('now'), (temp), (hum))", (1$
#con.commit()
#conn.close()

print ("\nEntire database contents:\n")
for row in curs.execute("SELECT* FROM DHT_data"):
    print (row)
conn.close()

Sorry this is my code:

import time
import grovepi
import math
dbname='sensorsData.db'
import sqlite3
import sys



sampleFreq=1*60

#def getDHTdata():
sensor=4
blue=0
 #   DHTpin=16
conn=sqlite3.connect('sensorsData.db')
curs=conn.cursor()

while True:
 try:
          [temp,humidity]= grovepi.dht(sensor, blue)
          if math.isnan(temp)==False and math.isnan(humidity)==False:
              print("temp=%.02f C humidity=%.02f%%"%(temp, humidity))

      except IOError:
                    print ("Error")


#def logData (temp,hum):
curs.execute("INSERT INTO DHT_data values(datetime('now'), (temp), (hum))", (11$
con.commit()
conn.close()

print ("\nEntire database contents:\n")
for row in curs.execute("SELECT* FROM DHT_data"):
    print (row)
conn.close()
Reply
#12
Hi, I am trying to assign current time and date but facing some problem in print statement like could not convert string to float: 'temp'. I am really working very hard on my code. Any solutions will be greatly appreciated. Thanks.

import datetime
import grovepi
import math
dbname='sensorsData.db'
import sqlite3
import sys
import time

#datetime.datetime.now()
#now= datetime.now().strftime("%%Y-%%m-d %H:%M")





#sampleFreq=1*60

#def getDHTdata():
sensor=4
blue=0
 #   DHTpin=16
conn=sqlite3.connect('sensorsData.db')
curs=conn.cursor()

while True:
      time.sleep(10)
      try:
          [temp,humidity]= grovepi.dht(sensor, blue)

      except IOError:
                    print ("Error")

      if math.isnan(temp)==False and math.isnan(humidity)==False:
##            print('{},{:.01f},{:.01f}' .format(time("%Ytemp, humidity))
         print("datetime=%%Y-%%m-%d %%H:%%M temp=%.02f C hum=%.02f%%"%(float("temp"), float("humidity"), float("datetime")))
        # print now +'-Temperature:{0:0.1f}C'.format(temp)+'Humidity:{0:0.1f}%'.format(humidity)

#def logData (temp,hum):
def add_data (temp, hum):
  curs.execute("INSERT INTO DHT_data values(datetime('now'), (temp), (hum,)")
  con.commit()

  conn.close()

print ("\nEntire database contents:\n")
for row in curs.execute("SELECT* FROM DHT_data"):
    print (row)
conn.close()
Reply
#13
Please, post full traceback in error tags.
also - fix the indentation of your code. It's wrong (at least lines 8-9 and maybe after that)
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#14
print("datetime=%%Y-%%m-%d %%H:%%M temp=%.02f C hum=%.02f%%"%(float("temp"), float("humidity"), float("datetime")))
print('{:.01f},{:.01f}'.format(temp, humidity))
temp and humidity are already floats.
what you do in your current code is to try to convert to float the string "temp" and string "humidity"
I will leave to you to try and fix the date and time yourself.

Note that there are more problems, but you will find them when time comes
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#15
Thank you very much. Also I am facing problem in storing these values in the database. Please help. I already have written code for this...
Reply
#16
You need to organise your code better. I'm not going to rewrite it for you.
At the moment you try to write the data using add_data function. however all the code to connect to db i out of this function (i.e. global variables)
also I am facing problem in storing these values in the database is not descriptive. Do you get error? if yes - post the full traceback.
I'm not going to answer anymore without (i) full traceback, (ii) the code that produce it.
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#17
Hi I tried


print('{:01d}/{:01d}/{:4d},{:.01f},{:.01f}'.format(temp, humidity))
but it doesn't work

print('{:01d}/{:01d}/{:4d},{:.01f},{:.01f}'.format(time, temp, humidity))
for time but doesn't work

Error:
Traceback (most recent call last): File "temp_hum.py", line 36, in <module> print("{:.01d}/{:.01d}/{:.4d},{:.01f},{:.01f}" .format(time, temp, humidity)) TypeError: unsupported format string passed to module.__format__
Reply
#18
Please, refer to string Format Specification Mini-language for details

from datetime import datetime

dt = datetime.now()
temp = 30.125
humidity = 70.465

print('{:%m/%d/%Y}, temperature: {:.1f} degrees Celsius, humidity: {:.1f}%'.format(dt, temp, humidity))
dt1 = dt.strftime('%m/%d/%Y')
print('{}, temperature: {:.1f} degrees Celsius, humidity: {:.1f}%'.format(dt1, temp, humidity))
Output:
08/14/2018, temperature: 30.1 degrees Celsius, humidity: 70.5% 08/14/2018, temperature: 30.1 degrees Celsius, humidity: 70.5%
Note that you can specify datetime format as part of the string format specification (first example) or you can convert datetime object to string (what you have actually done in one of your previous snippets).
Refer to this for date and time format specifications
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020