reading data from arduino with python
Question: im trying to do something which arduino sends bunch of data frequently, and my
objective is:

  1. every 100 data, make a new file. (lets call it a1, a2, ...)

  2. in one generic file, take the average of each of these a files and write it inside of that file as a new line

for experiment i coded my arduino like that:

    
    
    void setup(){
    Serial.begin(9600);
    }
    
    void loop(){
    Serial.println(random(100,500)); 
    delay(20);
    }
    

and here is the python code:

    
    
    import serial, struct
    
    initialfreq = 0
    a = 0
    interval = 0
    
    fileName = 'general_list'
    general_list = open(fileName, 'wb')
    
    ser = serial.Serial(port = 'COM3', baudrate = 9600)
    
    
    def mean(numberList):
        return sum(numberList) / len(numberList)
    
    
    
    while(1):
      for i in '100' :
          temparray=[]
          fileName = 'interval' + str(initialfreq) + '.data'
          temp_file = open(fileName, 'wb')
          readoff = ser.readline()
          temparray.append(readoff)
          temp_file.write(readoff)
    
    
    ##        temp_file.flush()
    print("bitti")
    general_list.write(str(interval)+"    "+str(mean(temparray)))
    general_list.write(str(mean(temparray)))
    initialfreq= initialfreq + 1
    a=0`
    

my problem is,

  1. for loop is not working properly, even when i sad 100, its not taking 100 values.

  2. arduino sending codes with \n. i cant see them in files but in temparray i see that there is \n 's so its not calculating the average.

thanks a lot guys.


Answer: Here is the solution for your first problem.

1)

    
    
    for i in range(100):
    

