0

I am trying to use button presses to log number of visits to a business. How can I take each button detect event and write it to it's own row in a csv file?

def button_callback(channel):
    global counter
    counter = counter +1
    print("A Check-in #", counter)


GPIO.add_event_detect(17, GPIO.FALLING, callback=button_callback, bouncetime=300)

I would like each print of the check-in to be added into it's own row in a csv file.

Martin Evans
  • 45,791
  • 17
  • 81
  • 97
Adam Tee
  • 13
  • 3
  • 1
    Possible duplicate of [Python write to CSV line by line](https://stackoverflow.com/questions/37289951/python-write-to-csv-line-by-line) – Mihai Chelaru May 04 '19 at 17:36

1 Answers1

0

You could append each event to a CSV file as follows:

from datetime import datetime
import csv


def button_callback(channel):
    global counter

    counter += 1

    print("A Check-in #", counter)

    # Append row to a CSV file
    with open('output.csv', 'a', newline='') as f_output:
        csv_output = csv.writer(f_output)
        timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        csv_output.writerow([timestamp, counter])


GPIO.add_event_detect(17, GPIO.FALLING, callback=button_callback, bouncetime=300)

This shows you how to write to a CSV file. A csv.writer() is used to make it easier to write rows of values to a file. The writerow() function takes a list of values, and writes them as line in the file with commas separating each value.

In this example the list contains two values, the current time and the current counter value. The datetime function is used to add a timestamp for your logged event.

This would give you a sample output looking like:

2019-05-07 08:21:31,1
2019-05-07 08:27:06,2
Martin Evans
  • 45,791
  • 17
  • 81
  • 97