0

I am sensing the vibrations of a machine live with Arduino. For that I use an accelerometer, an Arduino Uno board, and a Python script that I wrote. The code is intented to read the data of the sensor from the serial port (g), calculate the root mean square of the secuence (RMS) and save the data in an csv file. The problem I have is that my sript stops showing and saving the data out of nowhere, do you see any mistakes in the code? I couldn't identify any relationship between the different incidents, because each one happened at different timing. Here it is:

import csv
from math import sqrt
import serial
from itertools import count 
import os

ruta = 'C:/Users/jabde/OneDrive/Documentos/Juan/PhD/Ensayos/Acelerómetro/archivo.csv'

nombre_archivo = input("Ingrese el nombre del archivo: ")

ruta_completa = os.path.join(os.path.dirname(ruta), nombre_archivo + '.csv')

os.chdir(os.path.dirname(ruta))

arduinoData=serial.Serial('com3',115200)

fieldnames = ["t", "g", "RMS"]

i = 0
t = 0
g = 0.15
RMS = 0.1425
suma_cuadrados = 0

with open(ruta_completa, 'w', newline= '') as csv_file:
    csv_writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
    csv_writer.writeheader()


while True:
    with open(ruta_completa, 'a', newline= '') as csv_file:
        csv_writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
        try:
            g = arduinoData.readline()
            g = float(g) / 800
            t = t + 0.2
            t = round(t,1)
            i = i + 1
            cuadrados = g * g
            suma_cuadrados = suma_cuadrados + cuadrados
            RMS = suma_cuadrados / i
            RMS = sqrt(RMS)

            info = {
                "g": g,
                "t": t,
                "RMS": RMS
            }
        
            with open(ruta_completa, 'a', newline= '') as csv_file:
                csv_writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
                csv_writer.writerow(info)
        
            print(t, g, RMS)
            time.sleep(0.2)
        except:
            pass

I thought it could be a space problem in my laptop so I changed the rute where it was saving the CSV file but nothing happened.

vvvvv
  • 25,404
  • 19
  • 49
  • 81
  • may be try removing the "try catch", since you're in a infinite while loop and ignoring all the errors there is a chance that the error occure inside of the while loop so remove try catch and run the script – Hariharan Feb 03 '23 at 17:48
  • Hey Hariharan, thanks for replying! I added the "try catch" thinking that maybe there was an exception causing the interruption, but it kept occurring. Do you think it could be something related to the hardware I'm using? – Juan Abdelnabe Feb 03 '23 at 17:57
  • 1
    why are you opening the file three times? – JonSG Feb 03 '23 at 17:59
  • 1
    [Errors should never pass silently](https://stackoverflow.com/questions/21553327/why-is-except-pass-a-bad-programming-practice). If there's an exception, try to get at least some info about it. – Ignatius Reilly Feb 03 '23 at 18:01
  • 1
    Hey @JonSG, I had problems with the "writting a csv file" thing so I took that part from a page, do you have any suggestion on how to improve it? – Juan Abdelnabe Feb 03 '23 at 18:07
  • Hey @IgnatiusReilly! What happen is it that, out of nowhere, I stop seeing the readings in the terminal, i don't get any info :( – Juan Abdelnabe Feb 03 '23 at 18:11

1 Answers1

0

I would start with something like this and see where it got me. Note that some of your code is commented out and/or mocked for testing on my part.

The idea is to handle exceptions via an outer loop while doing expected work in the inner loop.

import csv
import math
#import serial
#import os
import time
import random

#ruta = 'C:/Users/jabde/OneDrive/Documentos/Juan/PhD/Ensayos/Acelerómetro/archivo.csv'
#nombre_archivo = input("Ingrese el nombre del archivo: ")
#ruta_completa = os.path.join(os.path.dirname(ruta), nombre_archivo + '.csv')
ruta_completa = "out.csv"

#os.chdir(os.path.dirname(ruta))

#arduinoData = serial.Serial('com3',115200)
class arduinoData:
    readline = lambda : 100_000 * random.random()

start_time = int(time.time())
suma_cuadrados = 0
i = 1

with open(ruta_completa, 'w', newline= '') as csv_file:
    csv_writer = csv.writer(csv_file)
    csv_writer.writerow(["t", "g", "RMS"])

while True:
    try:
        with open(ruta_completa, 'a', newline= '') as csv_file:
            csv_writer = csv.writer(csv_file)

            while True:
                if random.randint(0, 10) == 10:
                    raise Exception("Test Exception")

                t = round(time.time() - start_time, 1)
                g = float(arduinoData.readline()) / 800
                suma_cuadrados += (g * g)
                RMS = math.sqrt(suma_cuadrados / i)

                row = [g, t, RMS]
                csv_writer.writerow([g, t, RMS])
                print(row)

                i += 1
                time.sleep(0.2)
 
    except Exception as e:
        print(f"Error: {e}")
        print("\tTrying again in 5 seconds...")
        time.sleep(5)

JonSG
  • 10,542
  • 2
  • 25
  • 36