1

Im using an ADC to measuring values and send them over a socket via the RP, yet I also want to save the values to my RP as I'm reading them. For some reason when I open the text file it only has the last value read. I don't know why I cant figure this out.

import socket
import struct
from time import sleep
import RPi.GPIO as GPIO
import Adafruit_ADS1x15

#UDP_IP_ADDRESS = "127.0.0.1"
UDP_IP_ADDRESS = "169.254.65.163"#"169.254.168.20" #double check IP
UDP_PORT_NO = 6789

adc = Adafruit_ADS1x15.ADS1115()

clientSock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

GAIN = 1
i = 0

print('Reading ADS1x15 values, press Ctrl-C to quit...')
print('| {0:>6} | {1:>6} | {2:>6} | {3:>6} |'.format(*range(4)))
print('-' * 37)

while True:
    # Read all the ADC channel values in a list.
    values = []
    values.append(adc.read_adc(i, gain=GAIN))
    data = struct.pack("!d", values[i])
    clientSock.sendto(data, (UDP_IP_ADDRESS, UDP_PORT_NO))
    np.savetxt('RPA0data.txt', values, delimiter=',')
    print('| {0:>6} |'.format(*values))
    i = i + 1
  • 1
    It is difficult to understand this elliptic code, but a fundamental problem is that you are creating a NEW list with each loop. – Milliways Nov 4 '18 at 21:49
1

As Milliways' comment has pointed out: you are creating a new (and empty) list on each iteration of the while True loop. So values = [] should be put outside that loop.

Assuming np.savetext() is from NumPy (which is not imported in the example) you will be re-writing the file with the full list of values (after fixing the above issue of course) for each iteration - which is likely not what you want. According to this post one could append to a file using NumPy's savetext() but you will have to open the file yourself in append mode and hand the filehandle to savetext() instead of the filename. (Note that they propose to open the file in binary mode; I wonder why that is...)

f = open('asd.dat', 'ab')
np.savetxt(f, a)
f.close()

Of course outputting the values to a csv text file does not really require a special NumPy feature so one could just use native Python file handling to append a single new value to the file (example not using a list of values but just a single value):

with open("test.txt", "a") as myfile:
    myfile.write("{0}".format(value))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.