每N毫秒重复N次的功能

时间:2018-08-07 14:17:38

标签: python multithreading xlsxwriter adc

我是Python编程的初学者。我本质上是想创建一个程序,该程序将每毫秒对ADC的电压进行采样,然后将该数据放入矩阵中,然后将其导出到Excel文件中。现在,我正在为ADC数据使用占位符。这是到目前为止我得到的:

import xlsxwriter
import time
import numpy
import threading

a = numpy.array(['Time (ms)','Current (A)'])    #Writes header values, sets up array a
maxtime = 200   #Limit for how long the program will run, in ms
elapsed = 0

def readdata(maxtime):
    global elapsed
    global a
    if elapsed <= maxtime:
        threading.Timer(0.01, readdata)
        elapsed +=1
        b = numpy.array(['Test1', 'Test2']) #'Test1' and 'Test2' Will eventually be replaced with ADC data
        a = numpy.concatenate((a, b), axis=0)   #Combines the arrays
    else:
        generatespreadsheet(a)


def generatespreadsheet():
    global a
    workbook = xlsxwriter.Workbook(time.strftime("%Y%m%d-%H%M%S") + ".xlsx") #Define workbook name as date and time
    worksheet = workbook.add_worksheet()    #Adds the first sheet
    row = 0

    for col, data in enumerate(a):
        worksheet.write_row(col, row, data) #write the array in Excel
    workbook.close()

readdata(maxtime)

我遇到的问题是代码似乎什么也没做。甚至不抛出错误代码。任何帮助将不胜感激!

更新:我转而使用发电机,代码如下:

    import xlsxwriter
import time
import numpy
import threading

a = numpy.array(['Time (ms)','Current (A)'])    #Writes header values, sets up array a
maxtime = 200   #Limit for how long the program will run, in ms
elapsed = 0

def do_every(period,f):
    def g_tick():

        t = time.time()
        count = 0
        while True:
            count += 1
            yield max(t + count*period - time.time(),0)
    g = g_tick()
    while True:
        time.sleep(next(g))
        f()
        global elapsed
        global maxtime
        elapsed += 1
        if elapsed >= maxtime
            generatespreadsheet()



def readdata():
    global a
    b = numpy.array(['Test1', 'Test2']) #'Test1' and 'Test2' Will eventually be replaced with ADC data
    a = numpy.concatenate((a, b), axis=0)   #Combines the arrays




def generatespreadsheet():
    global a
    workbook = xlsxwriter.Workbook(time.strftime("%Y%m%d-%H%M%S") + ".xlsx") #Define workbook name as date and time
    worksheet = workbook.add_worksheet()    #Adds the first sheet
    row = 0

    for col, data in enumerate(a):
        worksheet.write_row(col, row, data) #write the array in Excel
    workbook.close()
    exit()


do_every(0.001,readdata)

0 个答案:

没有答案
相关问题