Python 每N毫秒重复N次的函数
我是Python编程的初学者。我基本上是想创建一个程序,每毫秒对ADC的电压进行一次采样,将数据放入矩阵,然后将其导出到Excel文件。现在我正在为ADC数据使用占位符。以下是到目前为止我得到的信息:Python 每N毫秒重复N次的函数,python,multithreading,xlsxwriter,adc,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 m
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)
我对pythonic线程的使用不多,但感觉您错过了这里的开始操作<代码>一些线程.start()启动线程时可能需要重复的线程。做但是你确定要启动这么多线程吗?乍一看,您将得到大约200条线程。不确定你的机器是否能处理。。。我的建议是更改逻辑…感谢@bayko的帮助,尽管我不确定在代码中的何处或如何实现这一点。
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)