0

I am very new to python. I am working on a project that reads in data from an accelerometer, and writes that data to a file. I did this with much success. I now am attempting to make it where the input() command that reads in the data is interrupted every two minutes, and with that a new file is written, and the process is repeated. This is to be used in a research device in a vehicle, so the script initiates when the car is started. I am posting a sample script below, right now It never enters the main loop (after the input). I need to interrupt this input after a time window, and would love to learn how. My code is below. Thanks!

import sys
import time
import traceback
import serial
import datetime
import os
import datetime
import os.path

from Phidget22.Devices.Accelerometer import *
from Phidget22.PhidgetException import *
from Phidget22.Phidget import *
from Phidget22.Net import *
from pathlib import Path
from PhidgetHelperFunctions import *


os.chdir("C:/Users/Mohsine/OneDrive - UAB - The University of Alabama at 
Birmingham/Car project/accelometer/")

now = datetime.datetime.now()
print(now)

m = int(now.strftime("%M"))      

print(m)

def fileNamer():
looper = 1 
counter = 1 

while looper > 0:        
    fname =  'P1' + "S" + str(counter) + now.strftime("Acc Y%Y-M%m-D%d H%H- 
    M%M") +  '.txt'
    my_file = Path("C:/Users/Mohsine/OneDrive - UAB - The University of 
    Alabama at Birmingham/Car project/accelometer/" + fname)
    if my_file.is_file():
        counter = counter + 1            
    else:
        looper = 0
    return fname







def onAccelerationChangeHandler(self, acceleration, timestamp):



        D=acceleration[0], acceleration[1], acceleration[2]

        #print(acceleration[0])

        #print("                      -> Timestamp   : %f\n" % timestamp)


        x = str(datetime.datetime.now())
        #fname = now.strftime("ACCELOMETER test  ")
        f = open(fname,"a")
        f.write(x + " ")
        f.write("%s " % str(acceleration[0]))
        f.write("%s " % str(acceleration[1]))
        f.write("%s\n" % str(acceleration[2]))
        print(D)
        f.close()


fname = fileNamer()

ch = Accelerometer()

print(fname)
ch.setDeviceSerialNumber(415163)

ch.setOnAccelerationChangeHandler(onAccelerationChangeHandler)

ch.openWaitForAttachment(5000)

accelerometer = input('accelerometer : \n ')        
def main():
    now = datetime.datetime.now()
    k = m
    print(k)  
    if(int(now.strftime("%M")) == k+2 or int(now.strftime("%M")) == k-58):


        fname = fileNamer()

        ch = Accelerometer()

        print(fname)
        ch.setDeviceSerialNumber(415163)

        ch.setOnAccelerationChangeHandler(onAccelerationChangeHandler)

        ch.openWaitForAttachment(5000)


        accelerometer = input('accelerometer : \n ')
        k = k+2    

main()
4
  • I believe I have now. I still struggles with these. New to python Commented Mar 2, 2019 at 18:11
  • duplicate of stackoverflow.com/questions/32031762/… Commented Mar 2, 2019 at 18:21
  • Similar issue, but this problem requires a keyboard interrupt to completely terminate the task, and it kills the entire script. Not what I was asking for. Commented Mar 4, 2019 at 17:11
  • You can put any handler (ex to completely terminate the task) for signals and keyboard interrupt is just another signal nothing special to it, Commented Mar 5, 2019 at 17:24

2 Answers 2

0

Obligatory "this is not tested", as of course I don't have the actual device.

If I correctly understood, the device triggers a onAccelerationChangeHandler() call whenever a new value is read, and you want this handler to write to a new file if more than two minutes elapsed since the first call of the handler.

You can try with this:

def onAccelerationChangeHandler(self, acceleration, timestamp):
    if 'file_creation_time' not in onAccelerationChangeHandler.__dict__:
        # save the time in seconds since epoch for first file creation
        onAccelerationChangeHandler.file_creation_time = time.time()
    if 'file_name' not in onAccelerationChangeHandler.__dict__:
        # get the first file name
        onAccelerationChangeHandler.file_name = fileNamer()
    now = time.time()
    if (now - onAccelerationChangeHandler.file_creation_time) > 120:
        # The file was created more than two minutes ago!
        onAccelerationChangeHandler.file_creation_time = now  # new creation time!
        onAccelerationChangeHandler.file_name = fileNamer()  # new file name!
    save_stuff_into_this_file(onAccelerationChangeHandler.file_name)

Now, I am not entirely sure about the position of the Python community about static variables in functions. The usual way is creating a class and keeping static data as attributes of the instance, but since this method is somewhat hooked to a library object instance I'm not entirely sure it can be done.

Sign up to request clarification or add additional context in comments.

1 Comment

This method worked. I apologize. I have a better understanding now. The input was not continuous. Main as a whole was being looped through, and a single data line was written with each loop. This method worked, but I later simplified it by running the filenamer function and updating the file name global variable every two minutes using a scheduler library, thus writing to a new file. Thanks so much for your assistance.
0

I'm not quite sure, because I don't understand your script completely, but maybe it is, because you are calling the filenamer() before the main() and you have a loop?

3 Comments

Yeah. That was an attempt at getting it to activate prior to entering the loop. But then I realized the input read is continuous
It is not. Even if I delete that portion, once the input starts, the read is continuous. It just continues to write accelerometer data to the file until the script is terminated (when the car powers off).
Try to call the main function after the looper=0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.