Python Forum
Python loop for posting data to web
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Python loop for posting data to web
#1
I got this code for posting data to thingspeak from a raspberry pi (zero):

#!/usr/local/bin/python3 
from envirophat import light, motion, weather, leds
import thingspeak
import time
from datetime import datetime

# Structure of the record - semicolon separated:
# UNIX timestamp;ISO date; light; rgb; motion; heading; temp (celsius); pressure (hPa)

# your ThnkSpeak Channel and API Write Key
channel_id="123"
api_key="456"
thingspeak_data = {}
try:
    now = datetime.now()
    ch = thingspeak.Channel(channel_id, api_key)
    timestamp = round(datetime.timestamp(now))
    cas = now.isoformat()
    leds.off()
    lux = light.light()
    print('%s;%s;%.1f' % (timestamp,cas,lux))
    thingspeak_data['field1'] = cas
    thingspeak_data['field2'] = lux
    response = ch.update(thingspeak_data)
    leds.off()

except KeyboardInterrupt:
    leds.off()
When I run the script from the terminal using the python command it works and posts once of course. But I need it to post every few minutes, so I did this. Replaced try: with while True: and added time.sleep(1800):
#!/usr/local/bin/python3 
from envirophat import light, motion, weather, leds
import thingspeak
import time
from datetime import datetime

# Structure of the record - semicolon separated:
# UNIX timestamp;ISO date; light; rgb; motion; heading; temp (celsius); pressure (hPa)


# your ThnkSpeak Channel and API Write Key
channel_id="123"
api_key="456"
thingspeak_data = {}
#try:
while True:
    now = datetime.now()
    ch = thingspeak.Channel(channel_id, api_key)
    timestamp = round(datetime.timestamp(now))
    cas = now.isoformat()
    leds.off()
    lux = light.light()
    print('%s;%s;%.1f' % (timestamp,cas,lux))
    thingspeak_data['field1'] = cas
    thingspeak_data['field2'] = lux
    response = ch.update(thingspeak_data)
    leds.off()
    time.sleep(1800)

#except KeyboardInterrupt:
#    leds.off()
It works, but only runs a few times and then stops after about the 3rd time. Why?

Mars
Reply


Messages In This Thread
Python loop for posting data to web - by marciokoko - Jul-17-2023, 07:33 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Problem posting image to clipboard noel 0 2,206 Sep-26-2020, 10:50 AM
Last Post: noel
  loop through python pandas data frame Johnse 4 2,895 Sep-02-2019, 01:45 AM
Last Post: Johnse
  module logging posting randomly DJ_Qu 2 2,246 May-14-2019, 06:41 AM
Last Post: DJ_Qu
  Posting zip file on HTTP network using Python2.7 deepti92 1 6,821 May-15-2018, 12:41 PM
Last Post: deepti92
  Need help with posting to API website pasi12 4 4,390 Feb-15-2017, 07:07 PM
Last Post: Larz60+

Forum Jump:

User Panel Messages

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