1

I have written a script in python in my Raspberry Pi 3, to get and plot data in real-time from an ADC.

The problem is that the data is not time accurate. I want my data to be read once per second or with a delay of one second each. Is there any software method in Raspberry Pi 3, or should I get extra clock and get it with ADC together?

A part of the code

def value_adc(): 
    startmess = time.process_time() 
    ADC = ADS1256.ADS1256()
    ADC.ADS1256_init()
    ADC_Value = ADC.ADS1256_GetAll()
    volt = [(ADC_Value[0]*5.0)]
    
    diffrence = time.process_time()-startmess
    if diffrence < 0.1:
        conn = sqlite3.connect(raspi)
        curs = conn.cursor()
        write = curs.execute("INSERT INTO poti values(datetime('now'), (?))", (volt))
        conn.commit()
        pause.seconds(1-diffrence)
        return write
        return conn.commit() 
    else: 
        print(datetime.datetime.now())

I have tried to pause for (1 sec - the run time of the code) but I still sometimes get more than one data per secound, and sometime a delay of more than a secound.

1
  • 1
    Do you have to re-initialize the ADC for every reading? Wouldn't it be better to initialize it outside this function, and then pass it in or access it as a class member or global?
    – goldilocks
    Oct 27, 2022 at 13:28

1 Answer 1

1

I would use the real system time not the process_time (cpu time).

I have a class which helps me schedule tasks like this. I create a stopwatch then start it, I keep checking the elapsed time using the elapsed() or elapsed_ms() method and when it returns a value greater than the interval I want I execute the task I need to run and then call start on the stopwatch again.

import time

class StopWatch:

"""
a class which performs timing
"""

def __init__(self):
    """Initialize a new `Stopwatch`, but do not start timing."""
    self.start_time = None
    self.stop_time = None

def start(self):
    """Start timing."""
    self.start_time = time.time()

def stop(self):
    """Stop timing."""
    self.stop_time = time.time()

def elapsed(self) -> int:
    """Return the number of seconds that have elapsed since this
    `Stopwatch` started timing.
    This is used for checking how much time has elapsed while the timer is
    still running.
    """
    if self.start_time:
        return int(time.time() - self.start_time)
    return 0

def elapsed_ms(self) -> int:
    """Return the number of milliseconds that have elapsed since this
    `Stopwatch` started timing.
    This is used for checking how much time has elapsed while the timer is
    still running.
    """
    if self.start_time:
        return int((time.time() - self.start_time) * 1000)
    return 0

Your Answer

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

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