My previous problem is solved, but I got another issue.
I would like to use pushbuttons to write a number in a file, like button 1 is 1, button 2 is 2 etc.
I've used interrupts to do this, and it works.
However, python is now printing like 1000 times the same value with the same time stamp in the csv file every 60 seconds.
How can I fix it?
The code:
Code: Select all
import RPi.GPIO as GPIO
from time import gmtime, strftime
import csv, os, glob, time, datetime, numpy
GPIO.setmode(GPIO.BCM)
GPIO.setup(23, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(17, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(24, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
button = []
button_mean = 0
def my_callback(channel):
button.insert(0,1)
print "button is 1"
print button
def my_callback2(channel):
button.insert(0,2)
print "button is 2"
print button
GPIO.add_event_detect(17, GPIO.FALLING, callback=my_callback, bouncetime=300)
GPIO.add_event_detect(23, GPIO.FALLING, callback=my_callback2, bouncetime=300)
try:
print "Press button 3 to quit "
while True:
elapsed = (int(time.time())%60)
if elapsed == 59:
if len(button) > 0 :
button_mean = numpy.mean(button)
with open("button.csv", "a") as csvfile:
out = csv.writer(csvfile, delimiter=",",
quotechar='|',quoting=csv.QUOTE_MINIMAL)
date = datetime.datetime.now()
out.writerow([date.strftime("%Y"),date.strftime("%m"),date.strftime("%d"),date.strftime("%H"),date.strftime("%M"),date.strftime("%S"), button_mean])
print button
button = []
else:
with open("button.csv", "a") as csvfile:
out = csv.writer(csvfile, delimiter=",",
quotechar='|',quoting=csv.QUOTE_MINIMAL)
date = datetime.datetime.now()
out.writerow([date.strftime("%Y"),date.strftime("%m"),date.strftime("%d"),date.strftime("%H"),date.strftime("%M"),date.strftime("%S"), button_mean])
print button
button = []
GPIO.wait_for_edge(24, GPIO.RISING)
print "Finished"
except KeyboardInterrupt:
GPIO.cleanup() # clean up GPIO on CTRL+C exit
GPIO.cleanup() # clean up GPIO on normal exit