Я сейчас переключаю сигнал с Aduino в частотную область. (FFT) Но та же ошибка продолжает появляться. Я не понимаю причину ошибки. Можете ли вы объяснить причину ошибки?
Это ошибка
PS C:\Users\xoska\Documents\workplace> cd 'c:\Users\xoska\Documents\workplace'; ${env:PYTHONIOENCODING}='UTF-8'; ${env:PYTHONUNBUFFERED}='1'; & 'C:\Users\xoska\AppData\Local\Programs\Python\Python37\python.exe' 'c:\Users\xoska\.vscode\extensions\ms-python.python-2019.11.49689\pythonFiles\ptvsd_launcher.py' '--default' '--client' '--host' 'localhost' '--port' '54326' 'c:\Users\xoska\Documents\workplace\test.py'
Traceback (most recent call last):
File "c:\Users\xoska\Documents\workplace\test.py", line 99, in update
curve2.setData(frequencia[:int(guarda/2)], abs(np.real(data[:int(guarda/2)])))
File "C:\Users\xoska\AppData\Local\Programs\Python\Python37\lib\site-packages\pyqtgraph\graphicsItems\PlotDataItem.py", line 461, in setData
self.updateItems()
File "C:\Users\xoska\AppData\Local\Programs\Python\Python37\lib\site-packages\pyqtgraph\graphicsItems\PlotDataItem.py", line 487, in updateItems
self.curve.setData(x=x, y=y, **curveArgs)
File "C:\Users\xoska\AppData\Local\Programs\Python\Python37\lib\site-packages\pyqtgraph\graphicsItems\PlotCurveItem.py", line 307, in setData
self.updateData(*args, **kargs)
File "C:\Users\xoska\AppData\Local\Programs\Python\Python37\lib\site-packages\pyqtgraph\graphicsItems\PlotCurveItem.py", line 353, in updateData
raise Exception("X and Y arrays must be the same shape--got %s and %s." % (self.xData.shape, self.yData.shape))
Exception: X and Y arrays must be the same shape--got (100,) and (20,).
Это код Arduino. Это простой источник для печати значений.
#include <math.h>
void setup() {
Serial.begin(9600);
}
void loop() {
for(float d = 0; d < 1; d+=0.001){
float resultado = 7*sin(15 * 2 * PI * d) + 3*sin(13 * 2 * PI * d);
Serial.println(resultado, 3);
// Sampling rate is 1/T -> 2000Hz
}
}
Это код Python. Я использовал pyqtgraph.
import sys
import glob
import serial
import pyqtgraph as pg
from pyqtgraph.Qt import QtCore, QtGui
import numpy as np
from collections import deque # import a "circular" list
from threading import Thread, Lock
arduinoData = serial.Serial('com5', 9600) # 115200
freq = 2000 # 1/T
guarda = 200 # 200
#r = range(0, int(freq/2+1), int(freq/guarda))
frequencia = np.fft.fftfreq(guarda, d=1/freq)
acelx = deque([], maxlen=guarda)
win = pg.GraphicsWindow()
win.setWindowTitle('Espectro')
pg.setConfigOption('foreground', 'w')
p2 = win.addPlot()
linha4 = pg.mkPen((255, 0, 0), width=2)
p2.addLegend(offset=(10, 5))
curve2 = p2.plot(acelx,
pen=linha4,
name="<span style='color: #ffffff; font-weight: bold; font-size: 12px'>Amplitude</span>")
p2.setRange(yRange=[0, 1000], xRange=[0, int(freq/2)])
p2.setLabel('bottom',
text="<span style='color: #ffffff; font-weight: bold; font-size: 12px'>Frequency (Hz)</span>")
p2.showGrid(x=False, y=True)
i = 0
data = []
lock = Lock()
def data_input():
global i, data
for line in arduinoData:
try:
i+=1
acelx.append(float(line))
with lock:
if i > len(acelx):
data = np.fft.fft(acelx)
except ValueError:
pass
# start the data input thread. This will run in the background unaffected by the GUI.
t = Thread(target=data_input)
t.daemon = True
t.start()
def update():
if i > len(acelx):
curve2.setData(frequencia[:int(guarda/2)], abs(np.real(data[:int(guarda/2)])))
timer = QtCore.QTimer()
timer.timeout.connect(update)
timer.start(0)
if __name__ == '__main__':
import sys
QtGui.QApplication.instance().exec_()