pythoncsvbeagleboneblackadafruit

Read input data to csv file


I am doing a BeagleBone project that measures temperature from a sensor. I want to save the data into a CSV file. I am new to programming and Python and I am little lost. I have been google searching for a while now and found little that can help me. So I wanted to ask instead about this. How to I get new data written into the CSV file every second?

import Adafruit_BBIO.ADC as ADC
import time
import csv

sensor_pin = 'P9_40'

ADC.setup()

while True:
    reading = ADC.read(sensor_pin)
    millivolts = reading * 1800  # 1.8V reference = 1800 mV
    temp_c = (millivolts - 500) / 10
    temp_f = (temp_c * 9/5) + 32
    print('mv=%d C=%d F=%d' % (millivolts, temp_c, temp_f))

    time.sleep(1)

    # field names 
    fields = ['Milivolts', 'Celsius'] 


    # data rows of csv file
    rows = [ [millivolts,"|", temp_c]]

    # name of csv file
    filename = "textfile.csv"

    # writing to csv file
    with open(filename, 'w') as csvfile:
        # creating a csv writer object
        csvwriter = csv.writer(csvfile)

        # writing the fields 
        csvwriter.writerow(fields)

        # writing the data rows
        csvwriter.writerows(rows)

Solution

  • One fix to apply is to open the file in append mode so that the file content is not overwritten at every step; just change the 'w' to 'a' in this line:

    with open(filename, 'a') as csvfile:
    

    Please note that without any output and/or description of the problem you are encountering, it will be difficult to help you more.