├── 1.1.1.Shift.High_Low_pass_filter.py ├── 1.1High_Low_pass_filter.py ├── 1.2_thread.py ├── 1.High_Low_pass_filter.py ├── 2.FastF.py ├── 3.simple_decimate.py ├── 4.StandardScaler.py ├── GUI ├── 1.1GIU_Shifp_timers.py ├── 1.GUI.py └── passfilter.py └── ReadMe.txt /1.1.1.Shift.High_Low_pass_filter.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import pandas as pd 3 | from scipy import signal 4 | import matplotlib.pyplot as plt 5 | import serial 6 | import time 7 | ComPort = serial.Serial('COM13') 8 | ComPort.baudrate = 115200 9 | ComPort.bytesize = 8 10 | ComPort.parity = 'N' 11 | ComPort.stopbits = 1 12 | sample_len=150 13 | random_data = np.arange(sample_len) 14 | 15 | def receive_datas(): 16 | 17 | for i in range(0,sample_len,1): 18 | random_data[i] = int(ComPort.readline()) 19 | 20 | return random_data 21 | 22 | sines=receive_datas() 23 | sine = pd.DataFrame({'data': sines} ) 24 | zet=sine.values 25 | sine ['data0'] = sine 26 | sine ['data1'] = zet 27 | sine ['data2'] = zet 28 | sine ['data3'] = zet 29 | sine ['data4'] = zet 30 | sine ['data5'] = zet 31 | sine ['data6'] = zet 32 | sine ['data7'] = zet 33 | 34 | def receive_data(a): 35 | t0 = time.perf_counter() 36 | for i in range(0,sample_len,1): 37 | random_data[i] = int(ComPort.readline()) 38 | sine ['data'+str(a)] = random_data 39 | t1 = time.perf_counter() - t0 40 | global fps 41 | fps = int (sample_len/t1) 42 | print ("fps", fps) 43 | if a==0: 44 | z = np.append(sine ['data'], (sine ['data1'])) 45 | z = np.append(z, (sine ['data2'])) 46 | z = np.append(z, (sine ['data3'])) 47 | z = np.append(z, (sine ['data4'])) 48 | z = np.append(z, (sine ['data5'])) 49 | z = np.append(z, (sine ['data6'])) 50 | z = np.append(z, (sine ['data7'])) 51 | z = np.append(z, (sine ['data0'])) 52 | if a==1: 53 | z = np.append(sine ['data'], (sine ['data2'])) 54 | z = np.append(z, (sine ['data3'])) 55 | z = np.append(z, (sine ['data4'])) 56 | z = np.append(z, (sine ['data5'])) 57 | z = np.append(z, (sine ['data6'])) 58 | z = np.append(z, (sine ['data7'])) 59 | z = np.append(z, (sine ['data0'])) 60 | z = np.append(z, (sine ['data1'])) 61 | if a==2: 62 | z = np.append(sine ['data'], (sine ['data3'])) 63 | z = np.append(z, (sine ['data4'])) 64 | z = np.append(z, (sine ['data5'])) 65 | z = np.append(z, (sine ['data6'])) 66 | z = np.append(z, (sine ['data7'])) 67 | z = np.append(z, (sine ['data0'])) 68 | z = np.append(z, (sine ['data1'])) 69 | z = np.append(z, (sine ['data2'])) 70 | if a==3: 71 | z = np.append(sine ['data'], (sine ['data4'])) 72 | z = np.append(z, (sine ['data5'])) 73 | z = np.append(z, (sine ['data6'])) 74 | z = np.append(z, (sine ['data7'])) 75 | z = np.append(z, (sine ['data0'])) 76 | z = np.append(z, (sine ['data1'])) 77 | z = np.append(z, (sine ['data2'])) 78 | z = np.append(z, (sine ['data3'])) 79 | if a==4: 80 | z = np.append(sine ['data'], (sine ['data5'])) 81 | z = np.append(z, (sine ['data6'])) 82 | z = np.append(z, (sine ['data7'])) 83 | z = np.append(z, (sine ['data0'])) 84 | z = np.append(z, (sine ['data1'])) 85 | z = np.append(z, (sine ['data2'])) 86 | z = np.append(z, (sine ['data3'])) 87 | z = np.append(z, (sine ['data4'])) 88 | if a==5: 89 | z = np.append(sine ['data'], (sine ['data6'])) 90 | z = np.append(z, (sine ['data7'])) 91 | z = np.append(z, (sine ['data0'])) 92 | z = np.append(z, (sine ['data1'])) 93 | z = np.append(z, (sine ['data2'])) 94 | z = np.append(z, (sine ['data3'])) 95 | z = np.append(z, (sine ['data4'])) 96 | z = np.append(z, (sine ['data5'])) 97 | if a==6: 98 | z = np.append(sine ['data'], (sine ['data7'])) 99 | z = np.append(z, (sine ['data0'])) 100 | z = np.append(z, (sine ['data1'])) 101 | z = np.append(z, (sine ['data2'])) 102 | z = np.append(z, (sine ['data3'])) 103 | z = np.append(z, (sine ['data4'])) 104 | z = np.append(z, (sine ['data5'])) 105 | z = np.append(z, (sine ['data6'])) 106 | if a==7: 107 | z = np.append(sine ['data'], (sine ['data0'])) 108 | z = np.append(z, (sine ['data1'])) 109 | z = np.append(z, (sine ['data2'])) 110 | z = np.append(z, (sine ['data3'])) 111 | z = np.append(z, (sine ['data4'])) 112 | z = np.append(z, (sine ['data5'])) 113 | z = np.append(z, (sine ['data6'])) 114 | z = np.append(z, (sine ['data7'])) 115 | t1 = time.perf_counter() - t0 116 | t1=t1*8 117 | # global fps 118 | 119 | 120 | #print ("fps", fps) 121 | result = pd.DataFrame({'data': z} ) 122 | # result = result[:sample_len] 123 | return result 124 | 125 | def butter_bandpass(lowcut, highcut, fs, order=5): 126 | nyq = 0.5 * fs 127 | low = lowcut / nyq 128 | high = highcut / nyq 129 | b, a = signal.butter(order, [low, high], btype='band') 130 | return b, a 131 | def butter_bandpass_filter(data, lowcut, highcut, fs, order=5): 132 | b, a = butter_bandpass(lowcut, highcut, fs, order=order) 133 | y = signal.filtfilt(b, a, data) #lfilter 134 | return y 135 | 136 | cutoffs = 10 137 | cutoff = 1 138 | figure, (ax) = plt.subplots(1, 1, sharex=True) 139 | axis_x=0 140 | a=0 141 | while 1: 142 | dataset = receive_data(a) 143 | a=a+1 144 | if (a == 7): 145 | a=0 146 | #dataset = dataset[:sample_len] 147 | # print ("sine",sine) 148 | 149 | filtered_sine = butter_bandpass_filter(dataset.data, cutoff, cutoffs, fps) 150 | print ("filtered_sine", len(filtered_sine)) 151 | filtered_sine = filtered_sine[(sample_len*8):] 152 | print ("filtered_sine", len(filtered_sine)) 153 | ax.plot(range(axis_x, axis_x+sample_len,1),filtered_sine, color = '#0a0b0c') 154 | ax.axis([axis_x-499, axis_x+501, filtered_sine[sample_len-1]-2000, filtered_sine[sample_len-1]+2000]) 155 | axis_x=axis_x+sample_len 156 | print ("ok") 157 | plt.pause(0.000001) 158 | plt.draw() 159 | -------------------------------------------------------------------------------- /1.1High_Low_pass_filter.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import pandas as pd 3 | from scipy import signal 4 | import matplotlib.pyplot as plt 5 | import serial 6 | import time 7 | 8 | ComPort = serial.Serial('COM13') 9 | ComPort.baudrate = 115200 10 | ComPort.bytesize = 8 11 | ComPort.parity = 'N' 12 | ComPort.stopbits = 1 13 | random_data = np.arange(50) 14 | 15 | def receive_data(): 16 | for i in range(0,50,1): 17 | random_data[i] = int(ComPort.readline()) 18 | result = pd.DataFrame({'data': random_data} ) 19 | return result 20 | 21 | def butter_highpass(cutoff, fs, order=3): 22 | nyq = 0.5 * fs 23 | normal_cutoff = cutoff / nyq 24 | b, a = signal.butter(order, normal_cutoff, btype='high', analog=False) 25 | return b, a 26 | 27 | def butter_highpass_filter(data, cutoff, fs, order=5): 28 | b, a = butter_highpass(cutoff, fs, order=order) 29 | y = signal.filtfilt(b, a, data) 30 | return y 31 | 32 | def butter_lowpass(cutoffs, fs, order=5): 33 | nyq = 0.5 * fs 34 | normal_cutoff = cutoff / nyq 35 | b, a = signal.butter(order, normal_cutoff, btype='low', analog=False) 36 | return b, a 37 | 38 | def butter_lowpass_filter(data, cutoffs, fs, order=5): 39 | b, a = butter_lowpass(cutoffs, fs, order=order) 40 | y = signal.lfilter(b, a, data) 41 | return y 42 | 43 | 44 | #order = 6 45 | fps=fs = 10 # sample rate, Hz 46 | cutoffs = 30 47 | cutoff=2 48 | 49 | figure, (ax1, ax2) = plt.subplots(2, 1, sharex=True) 50 | 51 | axis_x=0 52 | while 1: 53 | sine = receive_data() 54 | filtered_sine = butter_highpass_filter(sine.data, cutoff, fps) 55 | filtered_sine = butter_lowpass_filter(filtered_sine.data, cutoffs, fps) 56 | 57 | 58 | ax1.plot(range(axis_x, axis_x+50,1),sine,color = '#0a0b0c') 59 | ax2.plot(range(axis_x, axis_x+50,1),filtered_sine, color = '#0a0b0c') 60 | axis_x1_move=sine["data"] 61 | ax1.axis([axis_x-4000, axis_x+2000, axis_x1_move[48]-200000, axis_x1_move[48]+200000]) 62 | ax2.axis([axis_x-4000, axis_x+2000, filtered_sine[48]-50, filtered_sine[48]+50]) 63 | axis_x=axis_x+50 64 | 65 | 66 | plt.pause(0.001) 67 | plt.draw() 68 | 69 | #plt.show() 70 | -------------------------------------------------------------------------------- /1.2_thread.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import pandas as pd 3 | from scipy import signal 4 | import matplotlib.pyplot as plt 5 | import serial 6 | import time 7 | import threading 8 | #from ringbuf import RingBuffer #to be implemented 9 | 10 | #COM parameters 11 | port='COM13' 12 | baudrate = 115200 13 | bytesize = 8 14 | parity = 'N' 15 | stopbits = 1 16 | 17 | #display buffer 18 | sample_len=150 19 | 20 | #filter parameter init 21 | highcut = 10 22 | lowcut = 1 23 | fs = 30 #to be determined (and fixed) 24 | bandpass_a = 0 25 | bandpass_b = 0 26 | 27 | #plot init 28 | plt.ion() 29 | figure, (ax) = plt.subplots(1, 1, sharex=True) 30 | axis_x=0 31 | a=0 32 | 33 | 34 | def read_from_port(): 35 | global data_buffer, bufferComplete, mylogfile 36 | idx_buffer=0 37 | t = threading.currentThread() 38 | while getattr(t, "serialReading", True): 39 | curr_time = time.time() 40 | 41 | try: 42 | 43 | if not bufferComplete: 44 | if(idx_buffer < sample_len): 45 | 46 | curr_data = int(ComPort.readline()) 47 | data_buffer[idx_buffer] = curr_data 48 | idx_buffer += 1 49 | mylogfile.write(""+str(curr_time)+","+str(curr_data)+"\n") 50 | else: 51 | bufferComplete = True 52 | idx_buffer= 0 53 | 54 | except Exception as e: 55 | print(e) 56 | 57 | def butter_bandpass_coeff(lowcut, highcut, fs, order=5): 58 | global bandpass_b , bandpass_a 59 | nyq = 0.5 * fs 60 | low = lowcut / nyq 61 | high = highcut / nyq 62 | bandpass_b , bandpass_a = signal.butter(order, [low, high], btype='band') 63 | 64 | def butter_bandpass_filter(data): 65 | return signal.filtfilt( bandpass_b , bandpass_a, data) #lfilter 66 | 67 | 68 | if __name__ == '__main__': 69 | global data_buffer,bufferComplete, mylogfile 70 | 71 | data_buffer = np.arange(sample_len) 72 | bufferComplete = False 73 | 74 | #init serial communication 75 | ComPort = serial.Serial(port, baudrate, parity=parity, bytesize=bytesize, stopbits=stopbits, timeout=1) 76 | 77 | #init file log open 78 | mylogfile = open('loc_com_data.csv', "w") 79 | 80 | #init filter coefficents (must be called only if the cut frequencies change) 81 | butter_bandpass_coeff(lowcut, highcut, fs) 82 | 83 | t = threading.Thread(target=read_from_port) 84 | t.start() 85 | 86 | while True: 87 | if bufferComplete: 88 | tempBuff = data_buffer.copy() #safe copy to allow buffer to be filled again 89 | filtered_sine = butter_bandpass_filter(tempBuff) 90 | #print(tempBuff) 91 | 92 | ax.plot(range(axis_x, axis_x+sample_len,1),filtered_sine, color = '#0a0b0c') 93 | ax.axis([axis_x-499, axis_x+501, filtered_sine[sample_len-1]-2000, filtered_sine[sample_len-1]+2000]) 94 | axis_x=axis_x+sample_len 95 | 96 | plt.pause(0.0001) 97 | plt.draw() 98 | 99 | -------------------------------------------------------------------------------- /1.High_Low_pass_filter.py: -------------------------------------------------------------------------------- 1 | import h5py 2 | import matplotlib.pyplot as plt 3 | import time 4 | import pandas as pd 5 | from scipy import signal 6 | import scipy.fftpack 7 | import numpy as np 8 | import pyts 9 | from scipy import signal 10 | from scipy.fft import fftshift 11 | import matplotlib.pyplot as plt 12 | 13 | #1. Dataset 14 | #1.1 Read data 15 | f=h5py.File("experiment_1.nwb","r") 16 | x_eeg = f["acquisition/timeseries/recording1/continuous/processor105_100/data"] 17 | y_eeg_int = list(range(0, len(x_eeg[0]))) 18 | y_eeg=map(str, y_eeg_int) 19 | df=pd.DataFrame(x_eeg, columns=y_eeg) 20 | data_1_piezo_row = df["132"] 21 | data_2_ther_row = df["135"] 22 | 23 | #1.2 Band-pass filter 24 | def butter_lowpass(cutoff, fs, order=5): 25 | nyq = 0.5 * fs 26 | normal_cutoff = cutoff / nyq 27 | b, a = signal.butter(order, normal_cutoff, btype='low', analog=False) 28 | return b, a 29 | def butter_lowpass_filter(data, cutoff, fs, order=5): 30 | b, a = butter_lowpass(cutoff, fs, order=order) 31 | y = signal.lfilter(b, a, data) 32 | return y 33 | 34 | def butter_highpass(cutoff, fs, order=3): 35 | nyq = 0.5 * fs 36 | normal_cutoff = cutoff / nyq 37 | b, a = signal.butter(order, normal_cutoff, btype='high', analog=False) 38 | return b, a 39 | 40 | def butter_highpass_filter(data, cutoff, fs, order=5): 41 | b, a = butter_highpass(cutoff, fs, order=order) 42 | y = signal.filtfilt(b, a, data) 43 | return y 44 | 45 | 46 | fps=2000 47 | lowcut = 3 48 | highcut = 2 49 | 50 | data_1_piezo_filt_numpy_high = butter_highpass_filter(data_1_piezo_row,highcut, fps) 51 | data_2_ther_filt_numpy_high = butter_highpass_filter(data_2_ther_row,highcut, fps) 52 | 53 | data_1_piezo_filt_numpy = butter_lowpass_filter(data_1_piezo_filt_numpy_high, lowcut, fps) 54 | data_1_piezo_filt = pd.DataFrame(data_1_piezo_filt_numpy) 55 | data_2_ther_filt_numpy = butter_lowpass_filter(data_2_ther_filt_numpy_high, lowcut, fps) 56 | data_2_ther_filt = pd.DataFrame(data_2_ther_filt_numpy) 57 | 58 | 59 | 60 | # 1.3. Denoisnig 61 | # Create synthetic signal 62 | def Denoisnig(data): 63 | dt = 1 64 | data_denois=data 65 | t = np.arange(0, len(data_denois), 1) 66 | #signal = np.sin(2*np.pi*50*t) + np.sin(2*np.pi*120*t) #composite signal 67 | signal = data_denois 68 | signal_clean = signal #copy for later comparison 69 | signal = signal + 2.5 * np.random.randn(len(t)) 70 | minsignal, maxsignal = signal.min(), signal.max() 71 | ## Compute Fourier Transform 72 | n = len(t) 73 | fhat = np.fft.fft(signal, n) #computes the fft 74 | psd = fhat * np.conj(fhat)/n 75 | freq = (1/(dt*n)) * np.arange(n) #frequency array 76 | print ("freq", freq) 77 | idxs_half = np.arange(1, np.floor(n/2), dtype=np.int32) #first half index 78 | ## Filter out noise 79 | threshold = 100 80 | psd_idxs = psd > threshold #array of 0 and 1 81 | psd_clean = psd * psd_idxs #zero out all the unnecessary powers 82 | fhat_clean = psd_idxs * fhat #used to retrieve the signal 83 | signal_denois = np.fft.ifft(fhat_clean) #inverse fourier transform 84 | signal_denois=pd.DataFrame(signal_denois) 85 | return signal_denois 86 | 87 | #2.Graph 88 | #figure, (ax1) = plt.subplots(1, 1, sharex=True) 89 | #plt.plot(data_2_ther_filt) 90 | #plt.show() 91 | steps = 100 92 | ofsett_graph=1000 93 | 94 | 95 | data_for_graph_1=data_1_piezo_filt_numpy 96 | data_for_graph_2=data_2_ther_filt_numpy 97 | 98 | 99 | for number in range (0, x_eeg.shape[0], steps): 100 | #break 101 | plt.cla() 102 | plt.plot(data_for_graph_1[number:number+ofsett_graph]) # 103 | plt.plot(data_for_graph_2[number:number+ofsett_graph]) # ,color = '#0a0b0c' 104 | plt.xlabel('Ось X') 105 | plt.ylabel('Ось Y') 106 | plt.title('Black - Thermocouple, Blue - Piezo signal') 107 | plt.pause(0.000001) 108 | plt.draw() 109 | time.sleep(0.3) 110 | 111 | #3.Correlation 112 | #3.1.Spicy - Pearson 113 | def correlation(): 114 | from scipy.stats import pearsonr 115 | corr, _=pearsonr(data_1_piezo_filt_numpy, data_2_ther_filt_numpy) #Pearson’s correlation coefficient, 2-tailed p-value 116 | print('Pearsons correlation',corr) 117 | #3.2.Numpy Cov 118 | from numpy import cov 119 | covariance = cov(data_1_piezo_filt_numpy, data_2_ther_filt_numpy) #Covariance matrix 120 | print("Covariance matrix", covariance) 121 | #3.3.Spearman’s Correlation 122 | from scipy.stats import spearmanr 123 | corr, _ = spearmanr(data_1_piezo_filt_numpy, data_2_ther_filt_numpy) 124 | print("Spearman’s Correlation",corr) 125 | return True 126 | #correlation() 127 | 128 | #4.Fast_furier 129 | def Fast_furier(data1, data2): 130 | figure, axis = plt.subplots(1, 1) 131 | plt.subplots_adjust(hspace=1) 132 | axis.set_title('Fourier transform depicting the frequency components') 133 | axis.set_xlabel('Frequency') 134 | axis.set_ylabel('Amplitude') 135 | for data in (data1, data2): 136 | fourierTransform = np.fft.fft(data)/len(data) 137 | fourierTransform = fourierTransform[range(int(len(data)/2))] 138 | tpCount = len(data) 139 | values = np.arange(int(tpCount/2)) 140 | timePeriod = tpCount/fps 141 | frequencies = values/timePeriod 142 | axis.plot(frequencies, abs(fourierTransform)) 143 | 144 | axis.axis([0, 20, 0, 5]) 145 | plt.show() 146 | 147 | Fast_furier(data_for_graph_1, data_for_graph_2) 148 | 149 | #5.spectral-temporal analysis python 150 | def spectral(data): 151 | #f, t, Sxx = signal.spectrogram(data, 2000) 152 | #plt.figure(figsize=(8,10)) 153 | #plt.pcolormesh(t, f, Sxx, shading='gouraud') 154 | plt.ylabel('Frequency [Hz]') 155 | plt.xlabel('Time [sec]') 156 | plt.specgram(data,Fs=2000) 157 | plt.show() 158 | #spectral (data_1_piezo_row) 159 | 160 | 161 | #6. Coherence 162 | 163 | def Coherence(data1,data2): 164 | plt.subplots_adjust(wspace=0.5) 165 | dt = 0.01 166 | t = np.arange(0, len(data_1_piezo_row), 1) 167 | s1 = data1#0.01*np.sin(2*np.pi*10*t) + cnse1 168 | s2 = data2 #0.01*np.sin(2*np.pi*10*t) + cnse2 169 | 170 | plt.subplot(211) 171 | plt.plot(t, s1, t, s2) 172 | plt.xlim(0, len(data_1_piezo_row)) 173 | plt.xlabel('time') 174 | plt.ylabel('s1 and s2') 175 | plt.grid(True) 176 | 177 | plt.subplot(212) 178 | cxy, f = plt.cohere(s1, s2, 256, 1./dt) 179 | plt.ylabel('coherence') 180 | plt.show() 181 | 182 | #Coherence(data_1_piezo_row,data_2_ther_row) 183 | 184 | # 6.1 spectral power for signnals 185 | def spectral_power(s1,s2): 186 | dt = 0.01 187 | plt.subplot(121) 188 | plt.psd(s1, 256, 1/dt) 189 | plt.title('signal1') 190 | 191 | plt.subplot(122) 192 | plt.psd(s2, 256, 1/dt) 193 | plt.title('signal2') 194 | 195 | plt.tight_layout() 196 | plt.show() 197 | spectral_power(data_1_piezo_row,data_2_ther_row) 198 | 199 | #6.2 coherent 200 | def coherent (s1,s2): 201 | csdxy, fcsd = plt.csd(s1, s2, 256, 1./dt) 202 | plt.ylabel('CSD (db)') 203 | plt.title('cross spectral density between signal 1 and 2') 204 | plt.tight_layout() 205 | plt.show() 206 | #coherent(data_1_piezo_row,data_2_ther_row) 207 | 208 | #6.2 209 | # coherence 210 | from matplotlib import mlab 211 | s1=data_1_piezo_filt_numpy 212 | s2=data_2_ther_filt_numpy 213 | dt = 0.1 214 | # First create power sectral densities for normalization 215 | (ps1, f) = mlab.psd(s1, Fs=1./dt, scale_by_freq=False) 216 | (ps2, f) = mlab.psd(s2, Fs=1./dt, scale_by_freq=False) 217 | plt.plot(f, ps1) 218 | plt.plot(f, ps2) 219 | 220 | # Then calculate cross spectral density 221 | (csd, f) = mlab.csd(s1, s2, NFFT=256, Fs=1./dt,sides='default', scale_by_freq=False) 222 | fig = plt.figure() 223 | ax1 = fig.add_subplot(1, 2, 1) 224 | # Normalize cross spectral absolute values by auto power spectral density 225 | ax1.plot(f, np.absolute(csd)**2 / (ps1 * ps2)) 226 | ax2 = fig.add_subplot(1, 2, 2) 227 | angle = np.angle(csd, deg=True) 228 | angle[angle<-90] += 360 229 | ax2.plot(f, angle) 230 | 231 | # zoom in on frequency with maximum coherence 232 | ax1.set_xlim(9, 11) 233 | ax1.set_ylim(0, 1e-0) 234 | ax1.set_title("Cross spectral density: Coherence") 235 | ax2.set_xlim(9, 11) 236 | ax2.set_ylim(0, 90) 237 | ax2.set_title("Cross spectral density: Phase angle") 238 | 239 | plt.show() 240 | fig = plt.figure() 241 | ax = plt.subplot(111) 242 | 243 | ax.plot(f, np.real(csd), label='real') 244 | ax.plot(f, np.imag(csd), label='imag') 245 | 246 | ax.legend() 247 | plt.show() 248 | -------------------------------------------------------------------------------- /2.FastF.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import pandas as pd 3 | from scipy import signal 4 | import matplotlib.pyplot as plt 5 | import serial 6 | import time 7 | import matplotlib.pyplot as plotter 8 | 9 | ComPort = serial.Serial('COM7') 10 | ComPort.baudrate = 115200 11 | ComPort.bytesize = 8 12 | ComPort.parity = 'N' 13 | ComPort.stopbits = 1 14 | random_data = np.arange(500) 15 | 16 | def receive_data(): 17 | t0 = time.perf_counter() 18 | for i in range(0,500,1): 19 | random_data[i] = int(ComPort.readline()) 20 | result = pd.DataFrame({'data': random_data} ) 21 | return result 22 | 23 | 24 | 25 | #order = 6 26 | fps=fs = 10 # sample rate, Hz 27 | cutoffs = 30 28 | cutoff=2 29 | 30 | figure, (ax1) = plt.subplots(1, 1, sharex=True) 31 | axis_x=0 32 | 33 | 34 | figure, axis = plotter.subplots(1, 1) 35 | axis.set_title('Fourier transform depicting the frequency components') 36 | axis.set_xlabel('Frequency') 37 | axis.set_ylabel('Amplitude') 38 | 39 | while 1: 40 | axis.clear() 41 | sine = receive_data() 42 | print ("sine",sine) 43 | 44 | fourierTransform = np.fft.fft(sine.data)/len(sine.data) # 45 | fourierTransform = fourierTransform[range(int(len(sine.data)))] 46 | fourier = fourierTransform[range(int(len(sine.data)/2))] 47 | print ("fourierTransform",len (fourierTransform)) 48 | 49 | tpCount = len(sine.data) 50 | values = np.arange(int(tpCount/2)) 51 | timePeriod = tpCount/fs 52 | frequencies = values/timePeriod 53 | 54 | 55 | ax1.plot(range(axis_x, axis_x+500,1),sine,color = '#0a0b0c') 56 | # ax2.plot(range(axis_x, axis_x+500,1),abs (fourierTransform), color = '#0a0b0c') 57 | axis_x1_move=sine["data"] 58 | ax1.axis([axis_x-4000, axis_x+2000, axis_x1_move[48]-200000, axis_x1_move[48]+200000]) 59 | # ax2.axis([-4000, +2000,-5000, +5000]) 60 | axis_x=axis_x+500 61 | 62 | 63 | 64 | axis.plot(frequencies, (abs(fourier))) 65 | 66 | plt.pause(0.001) 67 | plt.draw() 68 | 69 | # break 70 | #plt.show() 71 | -------------------------------------------------------------------------------- /3.simple_decimate.py: -------------------------------------------------------------------------------- 1 | from scipy import signal 2 | import numpy as np 3 | 4 | x= np.array([1,2,3,4,5,6,7,8,9,10]) 5 | q=3 6 | d=signal.decimate(x, q, n=None, ftype='iir', axis=-1) 7 | 8 | print ("x", len(x)) 9 | print ("d",len(d)) 10 | -------------------------------------------------------------------------------- /4.StandardScaler.py: -------------------------------------------------------------------------------- 1 | from sklearn.preprocessing import StandardScaler 2 | import numpy as np 3 | 4 | data = np.array([[10, 5], [40, 10], [341, 3], [7, 22]]) 5 | scaler = StandardScaler() 6 | scaled_data = scaler.fit_transform(data) 7 | 8 | print(data) 9 | print(scaled_data) 10 | -------------------------------------------------------------------------------- /GUI/1.1GIU_Shifp_timers.py: -------------------------------------------------------------------------------- 1 | 2 | #define DWT_CONTROL *(volatile unsigned long *)0xE0001000 3 | #define SCB_DEMCR *(volatile unsigned long *)0xE000EDFC 4 | 5 | 6 | #include "main.h" 7 | SPI_HandleTypeDef hspi3; 8 | TIM_HandleTypeDef htim1; 9 | UART_HandleTypeDef huart5; 10 | 11 | void SystemClock_Config(void); 12 | static void MX_GPIO_Init(void); 13 | static void MX_UART5_Init(void); 14 | static void MX_SPI3_Init(void); 15 | static void MX_TIM1_Init(void); 16 | 17 | 18 | char trans_str[64] = {0,}; 19 | void HAL_TIM_IC_CaptureCallback(TIM_HandleTypeDef *htim) // колбек по захвату 20 | { 21 | if(htim->Instance == TIM1) 22 | { 23 | if(htim->Channel == HAL_TIM_ACTIVE_CHANNEL_1) 24 | { 25 | __HAL_TIM_SET_COUNTER(&htim1, 0x0000); 26 | } 27 | else if(htim->Channel == HAL_TIM_ACTIVE_CHANNEL_2) 28 | { 29 | uint32_t falling = HAL_TIM_ReadCapturedValue(&htim1, TIM_CHANNEL_2); 30 | // чтение значени�? в реги�?тре захвата/�?равнени�? 31 | snprintf(trans_str, 63, "Pulse %lu mks\n", falling); 32 | HAL_UART_Transmit(&huart5, (uint8_t*)trans_str, strlen(trans_str), 1000); 33 | } 34 | } 35 | } 36 | 37 | 38 | 39 | 40 | int main(void) 41 | { 42 | 43 | HAL_Init(); 44 | SystemClock_Config(); 45 | MX_GPIO_Init(); 46 | MX_UART5_Init(); 47 | MX_SPI3_Init(); 48 | 49 | MX_TIM1_Init(); 50 | 51 | 52 | 53 | 54 | int received_byte; 55 | uint8_t SDATAC = 0x11; 56 | uint8_t RESET = 0x06; 57 | // uint8_t WAKEUP = 0x02; 58 | 59 | uint8_t CONFIG1 = 0x01; 60 | uint8_t CONFIG2 = 0x02; 61 | uint8_t CONFIG3 = 0x03; 62 | uint8_t START = 0x08; 63 | uint8_t test = 0x00; 64 | uint8_t RDATAC = 0x10; 65 | // uint8_t STOP = 0x0a; 66 | 67 | uint8_t CH1SET = 0x05; 68 | uint8_t CH2SET = 0x06; 69 | uint8_t CH3SET = 0x07; 70 | uint8_t CH4SET = 0x08; 71 | uint8_t CH5SET = 0x09; 72 | uint8_t CH6SET = 0x0A; 73 | uint8_t CH7SET = 0x0B; 74 | uint8_t CH8SET = 0x0C; 75 | 76 | uint8_t received_Byte; 77 | uint32_t output[9]= {0}; 78 | 79 | uint32_t result_collect [9]= {0}; 80 | 81 | uint32_t dataPacket; 82 | uint32_t dataPacket_3bytes; 83 | 84 | 85 | 86 | uint32_t data_test = 0x7FFFFF; 87 | uint32_t data_check = 0xFFFFFF; 88 | 89 | uint32_t result; 90 | uint32_t result_before; 91 | int average_result_massiv[10]={0}; 92 | int average_result; 93 | 94 | uint32_t noise_massive [100]={0}; 95 | uint32_t final_noise_massive [100]={0}; 96 | uint32_t summa_noise; 97 | int zad = 8; 98 | int i_count = 0; 99 | int average_count= 0; 100 | int chanel_num =0; 101 | 102 | 103 | 104 | 105 | void DWT_Init(void) 106 | { 107 | SCB_DEMCR |= CoreDebug_DEMCR_TRCENA_Msk; // разрешаем использовать счётчик 108 | DWT_CONTROL |= DWT_CTRL_CYCCNTENA_Msk; // запускаем счётчик 109 | } 110 | 111 | 112 | DWT_Init(); 113 | 114 | //#define DWT_CONTROL *(volatile unsigned long *)0xE0001000 115 | //#define SCB_DEMCR *(volatile unsigned long *)0xE000EDFC 116 | // void DWT_Init(void) 117 | // { 118 | ///// SCB_DEMCR |= CoreDebug_DEMCR_TRCENA_Msk; 119 | // DWT_CONTROL |= DWT_CTRL_CYCCNTENA_Msk; 120 | // } 121 | // void delay_us(uint32_t us) 122 | // { 123 | // uint32_t us_count_tic = us * (SystemCoreClock / 1000000); 124 | // DWT->CYCCNT = 0U; 125 | // while(DWT->CYCCNT < us_count_tic); 126 | //// } 127 | // DWT_Init(); 128 | 129 | 130 | 131 | 132 | void send_data_to_brainflow (result) { 133 | 134 | 135 | 136 | int y = 255; 137 | char first_byte = result >> 16; 138 | 139 | 140 | 141 | 142 | 143 | int second_byte_int = (result >> 8) & y; 144 | unsigned char second_byte = second_byte_int; 145 | 146 | int third_byte_int = result & y; 147 | unsigned char third_byte = third_byte_int; 148 | 149 | HAL_UART_Transmit(&huart5, (uint8_t*)&first_byte, 1, 10); 150 | HAL_UART_Transmit(&huart5, (uint8_t*)&second_byte, 1, 10); 151 | HAL_UART_Transmit(&huart5, (uint8_t*)&third_byte, 1, 10); 152 | 153 | } 154 | 155 | 156 | 157 | void send_command(uint8_t cmd) 158 | { 159 | HAL_GPIO_WritePin(GPIOD, CS_Pin, GPIO_PIN_RESET); 160 | HAL_SPI_Transmit(&hspi3, (uint8_t*)&cmd,1, 0x1000); 161 | HAL_GPIO_WritePin(GPIOD, CS_Pin, GPIO_PIN_SET); 162 | } 163 | 164 | 165 | void send_data_by_uart (received_byte) 166 | { 167 | // step 1 - convert dataset 168 | char buffer[16]; 169 | char buffer1[16]; 170 | sprintf(buffer1, "%d\n", received_byte); 171 | int a=0; 172 | for (a; a> 16; 541 | 542 | int second_byte_int = (result >> 8) & y; 543 | unsigned char second_byte = second_byte_int; 544 | 545 | int third_byte_int = result & y; 546 | unsigned char third_byte = third_byte_int; 547 | 548 | unsigned char byte_0 = 160; 549 | unsigned char byte_26 = 192; 550 | 551 | char start_command [] = "b"; 552 | 553 | 554 | 555 | if( HAL_UART_Receive(&huart5, (uint8_t*)start_command_receive, 1, 1) == HAL_OK ) 556 | // HAL_UART_Receive(&huart5, (uint8_t*)start_command_receive, 1, 1000); 557 | { 558 | if (start_command_receive[0] == 98) { 559 | step=888; 560 | } 561 | if (start_command_receive[0] == 99) { 562 | step=0; 563 | //sample_number=0; 564 | } 565 | } 566 | if (step == 888) 567 | { 568 | sample_number = sample_number+1; 569 | 570 | HAL_UART_Transmit(&huart5, (uint8_t*)&byte_0, 1, 1); 571 | HAL_UART_Transmit(&huart5, (uint8_t*)&sample_number, 1, 10); 572 | 573 | 574 | send_data_to_brainflow ( result_collect[1]); 575 | send_data_to_brainflow ( result_collect[2]); 576 | send_data_to_brainflow ( result_collect[3]); 577 | send_data_to_brainflow ( result_collect[4]); 578 | 579 | send_data_to_brainflow ( result_collect[1]); 580 | send_data_to_brainflow ( result_collect[2]); 581 | send_data_to_brainflow ( result_collect[3]); 582 | send_data_to_brainflow ( result_collect[4]); 583 | 584 | // HAL_UART_Transmit(&huart5, (uint8_t*)&first_byte, 1, 10); 585 | // HAL_UART_Transmit(&huart5, (uint8_t*)&second_byte, 1, 10); 586 | // HAL_UART_Transmit(&huart5, (uint8_t*)&third_byte, 1, 10); 587 | 588 | // HAL_UART_Transmit(&huart5, (uint8_t*)&first_byte, 1, 10); 589 | // HAL_UART_Transmit(&huart5, (uint8_t*)&second_byte, 1, 10); 590 | // HAL_UART_Transmit(&huart5, (uint8_t*)&third_byte, 1, 10); 591 | 592 | // HAL_UART_Transmit(&huart5, (uint8_t*)&first_byte, 1, 10); 593 | // HAL_UART_Transmit(&huart5, (uint8_t*)&second_byte, 1, 10); 594 | // HAL_UART_Transmit(&huart5, (uint8_t*)&third_byte, 1, 10); 595 | 596 | // HAL_UART_Transmit(&huart5, (uint8_t*)&first_byte, 1, 10); 597 | // HAL_UART_Transmit(&huart5, (uint8_t*)&second_byte, 1, 10); 598 | // HAL_UART_Transmit(&huart5, (uint8_t*)&third_byte, 1, 10); 599 | 600 | // HAL_UART_Transmit(&huart5, (uint8_t*)&first_byte, 1, 10); 601 | // HAL_UART_Transmit(&huart5, (uint8_t*)&second_byte, 1, 10); 602 | // HAL_UART_Transmit(&huart5, (uint8_t*)&third_byte, 1, 10); 603 | 604 | // HAL_UART_Transmit(&huart5, (uint8_t*)&first_byte, 1, 10); 605 | // HAL_UART_Transmit(&huart5, (uint8_t*)&second_byte, 1, 10); 606 | // HAL_UART_Transmit(&huart5, (uint8_t*)&third_byte, 1, 10); 607 | 608 | // HAL_UART_Transmit(&huart5, (uint8_t*)&first_byte, 1, 10); 609 | // HAL_UART_Transmit(&huart5, (uint8_t*)&second_byte, 1, 10); 610 | // HAL_UART_Transmit(&huart5, (uint8_t*)&third_byte, 1, 10); 611 | 612 | // HAL_UART_Transmit(&huart5, (uint8_t*)&first_byte, 1, 10); 613 | // HAL_UART_Transmit(&huart5, (uint8_t*)&second_byte, 1, 10); 614 | // HAL_UART_Transmit(&huart5, (uint8_t*)&third_byte, 1, 10); 615 | 616 | HAL_UART_Transmit(&huart5, (uint8_t*)&byte_26, 1, 10); 617 | 618 | } 619 | // HAL_Delay (5); 620 | } 621 | 622 | } 623 | } 624 | 625 | 626 | 627 | 628 | 629 | void SystemClock_Config(void) 630 | { 631 | RCC_OscInitTypeDef RCC_OscInitStruct = {0}; 632 | RCC_ClkInitTypeDef RCC_ClkInitStruct = {0}; 633 | 634 | /** Configure the main internal regulator output voltage 635 | */ 636 | __HAL_RCC_PWR_CLK_ENABLE(); 637 | __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1); 638 | /** Initializes the CPU, AHB and APB busses clocks 639 | */ 640 | RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI; 641 | RCC_OscInitStruct.HSIState = RCC_HSI_ON; 642 | RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT; 643 | RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE; 644 | if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) 645 | { 646 | Error_Handler(); 647 | } 648 | /** Initializes the CPU, AHB and APB busses clocks 649 | */ 650 | RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK 651 | |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2; 652 | RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_HSI; 653 | RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV2; 654 | RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1; 655 | RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1; 656 | 657 | if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_0) != HAL_OK) 658 | { 659 | Error_Handler(); 660 | } 661 | } 662 | 663 | /** 664 | * @brief SPI3 Initialization Function 665 | * @param None 666 | * @retval None 667 | */ 668 | static void MX_SPI3_Init(void) 669 | { 670 | 671 | /* USER CODE BEGIN SPI3_Init 0 */ 672 | 673 | /* USER CODE END SPI3_Init 0 */ 674 | 675 | /* USER CODE BEGIN SPI3_Init 1 */ 676 | 677 | /* USER CODE END SPI3_Init 1 */ 678 | /* SPI3 parameter configuration*/ 679 | hspi3.Instance = SPI3; 680 | hspi3.Init.Mode = SPI_MODE_MASTER; 681 | hspi3.Init.Direction = SPI_DIRECTION_2LINES; 682 | hspi3.Init.DataSize = SPI_DATASIZE_8BIT; 683 | hspi3.Init.CLKPolarity = SPI_POLARITY_LOW; 684 | hspi3.Init.CLKPhase = SPI_PHASE_2EDGE; 685 | hspi3.Init.NSS = SPI_NSS_SOFT; 686 | hspi3.Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_16; 687 | hspi3.Init.FirstBit = SPI_FIRSTBIT_MSB; 688 | hspi3.Init.TIMode = SPI_TIMODE_DISABLE; 689 | hspi3.Init.CRCCalculation = SPI_CRCCALCULATION_DISABLE; 690 | hspi3.Init.CRCPolynomial = 10; 691 | if (HAL_SPI_Init(&hspi3) != HAL_OK) 692 | { 693 | Error_Handler(); 694 | } 695 | /* USER CODE BEGIN SPI3_Init 2 */ 696 | 697 | /* USER CODE END SPI3_Init 2 */ 698 | 699 | } 700 | 701 | 702 | /** 703 | * @brief TIM1 Initialization Function 704 | * @param None 705 | * @retval None 706 | */ 707 | static void MX_TIM1_Init(void) 708 | { 709 | 710 | /* USER CODE BEGIN TIM1_Init 0 */ 711 | 712 | /* USER CODE END TIM1_Init 0 */ 713 | 714 | TIM_ClockConfigTypeDef sClockSourceConfig = {0}; 715 | TIM_MasterConfigTypeDef sMasterConfig = {0}; 716 | TIM_IC_InitTypeDef sConfigIC = {0}; 717 | 718 | /* USER CODE BEGIN TIM1_Init 1 */ 719 | 720 | /* USER CODE END TIM1_Init 1 */ 721 | htim1.Instance = TIM1; 722 | htim1.Init.Prescaler = 8; 723 | htim1.Init.CounterMode = TIM_COUNTERMODE_UP; 724 | htim1.Init.Period = 600; 725 | htim1.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1; 726 | htim1.Init.RepetitionCounter = 0; 727 | htim1.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE; 728 | if (HAL_TIM_Base_Init(&htim1) != HAL_OK) 729 | { 730 | Error_Handler(); 731 | } 732 | sClockSourceConfig.ClockSource = TIM_CLOCKSOURCE_INTERNAL; 733 | if (HAL_TIM_ConfigClockSource(&htim1, &sClockSourceConfig) != HAL_OK) 734 | { 735 | Error_Handler(); 736 | } 737 | if (HAL_TIM_IC_Init(&htim1) != HAL_OK) 738 | { 739 | Error_Handler(); 740 | } 741 | sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET; 742 | sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE; 743 | if (HAL_TIMEx_MasterConfigSynchronization(&htim1, &sMasterConfig) != HAL_OK) 744 | { 745 | Error_Handler(); 746 | } 747 | sConfigIC.ICPolarity = TIM_INPUTCHANNELPOLARITY_RISING; 748 | sConfigIC.ICSelection = TIM_ICSELECTION_DIRECTTI; 749 | sConfigIC.ICPrescaler = TIM_ICPSC_DIV1; 750 | sConfigIC.ICFilter = 0; 751 | if (HAL_TIM_IC_ConfigChannel(&htim1, &sConfigIC, TIM_CHANNEL_1) != HAL_OK) 752 | { 753 | Error_Handler(); 754 | } 755 | sConfigIC.ICPolarity = TIM_INPUTCHANNELPOLARITY_FALLING; 756 | sConfigIC.ICSelection = TIM_ICSELECTION_INDIRECTTI; 757 | if (HAL_TIM_IC_ConfigChannel(&htim1, &sConfigIC, TIM_CHANNEL_2) != HAL_OK) 758 | { 759 | Error_Handler(); 760 | } 761 | /* USER CODE BEGIN TIM1_Init 2 */ 762 | 763 | /* USER CODE END TIM1_Init 2 */ 764 | 765 | } 766 | 767 | 768 | 769 | 770 | 771 | 772 | /** 773 | * @brief UART5 Initialization Function 774 | * @param None 775 | * @retval None 776 | */ 777 | static void MX_UART5_Init(void) 778 | { 779 | 780 | /* USER CODE BEGIN UART5_Init 0 */ 781 | 782 | /* USER CODE END UART5_Init 0 */ 783 | 784 | /* USER CODE BEGIN UART5_Init 1 */ 785 | 786 | /* USER CODE END UART5_Init 1 */ 787 | huart5.Instance = UART5; 788 | huart5.Init.BaudRate = 115200 ;// 115200 789 | huart5.Init.WordLength = UART_WORDLENGTH_8B; 790 | huart5.Init.StopBits = UART_STOPBITS_1; 791 | huart5.Init.Parity = UART_PARITY_NONE; 792 | huart5.Init.Mode = UART_MODE_TX_RX; 793 | huart5.Init.HwFlowCtl = UART_HWCONTROL_NONE; 794 | huart5.Init.OverSampling = UART_OVERSAMPLING_16; 795 | if (HAL_UART_Init(&huart5) != HAL_OK) 796 | { 797 | Error_Handler(); 798 | } 799 | /* USER CODE BEGIN UART5_Init 2 */ 800 | 801 | /* USER CODE END UART5_Init 2 */ 802 | 803 | } 804 | 805 | /** 806 | * @brief GPIO Initialization Function 807 | * @param None 808 | * @retval None 809 | */ 810 | static void MX_GPIO_Init(void) 811 | { 812 | GPIO_InitTypeDef GPIO_InitStruct = {0}; 813 | 814 | /* GPIO Ports Clock Enable */ 815 | __HAL_RCC_GPIOA_CLK_ENABLE(); 816 | __HAL_RCC_GPIOE_CLK_ENABLE(); 817 | __HAL_RCC_GPIOB_CLK_ENABLE(); 818 | __HAL_RCC_GPIOD_CLK_ENABLE(); 819 | __HAL_RCC_GPIOC_CLK_ENABLE(); 820 | 821 | /*Configure GPIO pin Output Level */ 822 | HAL_GPIO_WritePin(GPIOA, GPIO_PIN_0, GPIO_PIN_RESET); 823 | 824 | /*Configure GPIO pin Output Level */ 825 | HAL_GPIO_WritePin(GPIOE, GPIO_PIN_15, GPIO_PIN_RESET); 826 | HAL_GPIO_WritePin(GPIOE, GPIO_PIN_10, GPIO_PIN_RESET); 827 | /*Configure GPIO pin Output Level */ 828 | HAL_GPIO_WritePin(GPIOB, GPIO_PIN_10|GPIO_PIN_11, GPIO_PIN_RESET); 829 | 830 | /*Configure GPIO pin Output Level */ 831 | HAL_GPIO_WritePin(GPIOD, START_Pin|CS_Pin|CS2_Pin, GPIO_PIN_RESET); 832 | 833 | /*Configure GPIO pin : PA0 */ 834 | GPIO_InitStruct.Pin = GPIO_PIN_0; 835 | GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP; 836 | GPIO_InitStruct.Pull = GPIO_NOPULL; 837 | GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW; 838 | HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); 839 | 840 | /*Configure GPIO pin : PE15 */ 841 | GPIO_InitStruct.Pin = GPIO_PIN_15|GPIO_PIN_10; 842 | GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP; 843 | GPIO_InitStruct.Pull = GPIO_NOPULL; 844 | GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW; 845 | HAL_GPIO_Init(GPIOE, &GPIO_InitStruct); 846 | 847 | /*Configure GPIO pins : PB10 PB11 */ 848 | GPIO_InitStruct.Pin = GPIO_PIN_10|GPIO_PIN_11; 849 | GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP; 850 | GPIO_InitStruct.Pull = GPIO_NOPULL; 851 | GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW; 852 | HAL_GPIO_Init(GPIOB, &GPIO_InitStruct); 853 | 854 | /*Configure GPIO pins : START_Pin CS_Pin */ 855 | GPIO_InitStruct.Pin = START_Pin|CS_Pin|CS2_Pin; 856 | GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP; 857 | GPIO_InitStruct.Pull = GPIO_NOPULL; 858 | GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW; 859 | HAL_GPIO_Init(GPIOD, &GPIO_InitStruct); 860 | 861 | /*Configure GPIO pin : DRDY_Pin */ 862 | GPIO_InitStruct.Pin = DRDY_Pin; 863 | GPIO_InitStruct.Mode = GPIO_MODE_INPUT; 864 | GPIO_InitStruct.Pull = GPIO_NOPULL; 865 | HAL_GPIO_Init(DRDY_GPIO_Port, &GPIO_InitStruct); 866 | 867 | } 868 | //g 869 | 870 | 871 | 872 | 873 | 874 | 875 | 876 | 877 | 878 | void Error_Handler(void) 879 | { 880 | /* USER CODE BEGIN Error_Handler_Debug */ 881 | /* User can add his own implementation to report the HAL error return state */ 882 | 883 | /* USER CODE END Error_Handler_Debug */ 884 | } 885 | 886 | #ifdef USE_FULL_ASSERT 887 | /** 888 | * @brief Reports the name of the source file and the source line number 889 | * where the assert_param error has occurred. 890 | * @param file: pointer to the source file name 891 | * @param line: assert_param error line source number 892 | * @retval None 893 | */ 894 | void assert_failed(uint8_t *file, uint32_t line) 895 | { 896 | /* USER CODE BEGIN 6 */ 897 | /* User can add his own implementation to report the file name and line number, 898 | tex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */ 899 | /* USER CODE END 6 */ 900 | } 901 | #endif /* USE_FULL_ASSERT */ 902 | 903 | /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ 904 | -------------------------------------------------------------------------------- /GUI/1.GUI.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from PyQt5 import QtWidgets 3 | from PyQt5.QtWidgets import QMainWindow, QLabel, QGridLayout, QWidget 4 | from PyQt5.QtWidgets import QPushButton 5 | from PyQt5.QtCore import QSize 6 | from PyQt5.QtWidgets import QDialog, QApplication, QPushButton, QVBoxLayout 7 | from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas 8 | from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar 9 | import matplotlib.pyplot as plt 10 | from PyQt5.Qt import * 11 | import random 12 | import threading 13 | import time 14 | import numpy as np 15 | import pandas as pd 16 | from scipy import signal 17 | import serial 18 | import passfilter 19 | 20 | ComPort = serial.Serial('COM5') 21 | ComPort.baudrate = 115200 22 | ComPort.bytesize = 8 23 | ComPort.parity = 'N' 24 | ComPort.stopbits = 1 25 | random_data = np.arange(50) 26 | 27 | global fs 28 | fs = 50 # Частота дискретизации или частота дискретизации, F S , представляет собой среднее число образцов , полученных в одну секунду ( выборок в секунду ), 29 | 30 | global cutoff 31 | cutoff = 1 32 | global cutoffs 33 | cutoffs = 10 34 | class MainWindow(QMainWindow): 35 | def __init__(self): 36 | QMainWindow.__init__(self) 37 | 38 | self.setMinimumSize(QSize(300, 200)) 39 | self.setWindowTitle("BCI") 40 | pybutton = QPushButton('Click me', self) 41 | pybutton.clicked.connect(self.clickMethod) 42 | pybutton.resize(100,32) 43 | pybutton.move(50, 50) 44 | def clickMethod(self): 45 | print('Clicked Pyqt button.') 46 | 47 | seconWin.show() 48 | mainWin.close() 49 | 50 | class second_window(QWidget): 51 | 52 | def __init__(self): 53 | print ("start") 54 | QWidget.__init__(self) 55 | 56 | self.setMinimumSize(QSize(600, 500)) 57 | self.setWindowTitle("Iron_BCI") 58 | 59 | 60 | self.figure = plt.figure(figsize=(0,2,),facecolor='y', edgecolor='r') # color only 61 | self.figure1 = plt.figure(figsize=(0,2),facecolor='y') # color only 62 | self.figure2 = plt.figure(figsize=(0,2),facecolor='y') 63 | self.figure3 = plt.figure(figsize=(0,2),facecolor='y') 64 | 65 | self.canvas = FigureCanvas(self.figure) 66 | self.figure.subplots_adjust(0.2, 0.4, 0.8, 1) # only graph 67 | self.canvas1 = FigureCanvas(self.figure1) 68 | self.figure1.subplots_adjust(0.2, 0.4, 0.8, 1) # only graph 69 | self.canvas2 = FigureCanvas(self.figure2) 70 | self.figure2.subplots_adjust(0.2, 0.4, 0.8, 1) 71 | self.canvas3 = FigureCanvas(self.figure3) 72 | self.figure3.subplots_adjust(0.2, 0.4, 0.8, 1) 73 | # self.toolbar = NavigationToolbar(self.canvas, self) 74 | # self.toolbar1 = NavigationToolbar(self.canvas1, self) 75 | 76 | pybutton = QPushButton('graph', self) 77 | 78 | 79 | global axis_x 80 | axis_x=0 81 | 82 | pybutton.clicked.connect(self.clickMethod) 83 | pybutton.move(350, 10) 84 | pybutton.resize(100,32) 85 | 86 | layout = QVBoxLayout() 87 | layout.setContentsMargins(50,100,0,11) # move background 88 | layout.setGeometry(QRect(0, 0, 80, 68))# nothing 89 | # layout.addWidget(self.toolbar) 90 | layout.addWidget(self.canvas) 91 | # layout.addWidget(self.toolbar1) 92 | layout.addWidget(self.canvas1) 93 | layout.addWidget(self.canvas2) # background 94 | layout.addWidget(self.canvas3) 95 | # input dataufoff value 96 | self.le_num1 = QLineEdit() 97 | self.le_num1.setFixedSize(50, 20) # size 98 | self.pb_num1 = QPushButton('HPS') 99 | self.pb_num1.setFixedSize(50, 60) # size 100 | self.pb_num1.clicked.connect(self.show_dialog_num1) 101 | layout.addWidget(self.le_num1) 102 | self.pb_num1.move(10, 0) 103 | layout.addWidget(self.pb_num1) 104 | self.setLayout(layout) 105 | # stop input data 106 | # start input data fps 107 | self.le_num2 = QLineEdit() 108 | self.le_num2.setFixedSize(50, 20) # size 109 | self.pb_num2 = QPushButton('fs') 110 | self.pb_num2.setFixedSize(50, 60) # size 111 | self.pb_num2.clicked.connect(self.show_dialog_num2) 112 | layout.addWidget(self.le_num2) 113 | self.pb_num1.move(90, 100) 114 | layout.addWidget(self.pb_num2) 115 | self.setLayout(layout) 116 | # stop input data fps 117 | # start input data low filter 118 | self.le_num3 = QLineEdit() 119 | self.le_num3.setFixedSize(50, 20) # size 120 | self.pb_num3 = QPushButton('LPF') 121 | self.pb_num3.setFixedSize(50, 60) # size 122 | self.pb_num3.clicked.connect(self.show_dialog_num3) 123 | layout.addWidget(self.le_num3) 124 | self.pb_num1.move(190, 100) 125 | layout.addWidget(self.pb_num3) 126 | self.setLayout(layout) 127 | # stop input data filter 128 | 129 | def clickMethod(self): 130 | 131 | # while 1: 132 | try: 133 | t0 = time.perf_counter() 134 | for i in range(0,50,1): 135 | random_data[i] = int(ComPort.readline()) 136 | 137 | t1 = time.perf_counter() - t0 138 | # print ("t1", t1) 139 | # global fs 140 | # fs = int (50/t1) 141 | # print (fps) 142 | 143 | result_raw = pd.DataFrame({'data': random_data} ) 144 | result_high = passfilter.butter_highpass_filter(result_raw.data,cutoff, fs) 145 | result_low = passfilter.butter_lowpass_filter(result_raw.data,cutoffs, fs) 146 | 147 | 148 | result_band = pd.DataFrame({'data': result_high} ) 149 | #result['data']=result['data'].astype('int') 150 | #print (result) 151 | result_band = passfilter.butter_lowpass_filter(result_band.data,cutoffs, fs) 152 | #print (result) 153 | 154 | except ValueError: 155 | print ("ValueError") 156 | 157 | #data = [random.random() for i in range(axis)] 158 | #data1 = [random.random() for i in range(axis)] 159 | # print (result) 160 | # data1=result["data"] 161 | 162 | data=result_band 163 | bias= data.sum()/50 164 | 165 | #self.figure.clear() 166 | #self.figure1.clear() 167 | 168 | ax = self.figure.add_subplot(111) 169 | ax1 = self.figure1.add_subplot(111) 170 | ax2 = self.figure2.add_subplot(111) 171 | ax3 = self.figure3.add_subplot(111) 172 | #ax.plot(data, '*-') 173 | #ax.axis([0, 2000, 0, 20000]) 174 | global axis_x 175 | 176 | #Raw_data 177 | ax.plot(range(axis_x, axis_x+50,1),result_raw,color = '#0a0b0c') 178 | ax.axis([axis_x-500, axis_x+500, bias-50000, bias+50000]) # 179 | #High-pass-filter 180 | ax1.plot(range(axis_x, axis_x+50,1),result_high,color = 'b') 181 | ax1.axis([axis_x-500, axis_x+500, bias-5000, bias+5000]) # 182 | #Low-pass-filter 183 | ax2.plot(range(axis_x, axis_x+50,1),result_low,color = 'y') 184 | ax2.axis([axis_x-500, axis_x+500, bias-5000, bias+5000]) 185 | #Band_pass_filter 186 | ax3.plot(range(axis_x, axis_x+50,1),result_band,color = 'g') 187 | ax3.axis([axis_x-500, axis_x+500, bias-5000, bias+5000]) 188 | 189 | axis_x=axis_x+50 190 | 191 | self.canvas.draw() 192 | self.canvas1.draw() 193 | self.canvas2.draw() 194 | self.canvas3.draw() 195 | 196 | thread=threading.Thread(target=self.clickMethod, args=()) 197 | thread.start() 198 | # input data 199 | def show_dialog_num1(self): 200 | value, r = QInputDialog.getInt(self, 'Input dialog', 'HPS:') 201 | global cutoff 202 | cutoff = value 203 | print (cutoff) 204 | def show_dialog_num2(self): 205 | value, r = QInputDialog.getInt(self, 'Input dialog', 'fs:') 206 | global fs 207 | fs = value 208 | print (fs) 209 | def show_dialog_num3(self): 210 | value, r = QInputDialog.getInt(self, 'Input dialog', 'LPF:') 211 | global cutoffs 212 | cutoffs = value 213 | print (cutoffs) 214 | 215 | # thread.start() 216 | # mainWin.show() 217 | # seconWin.close() 218 | 219 | if __name__ == "__main__": 220 | app = QtWidgets.QApplication(sys.argv) 221 | mainWin = MainWindow() 222 | mainWin.show() 223 | seconWin = second_window() 224 | 225 | 226 | sys.exit( app.exec_() ) 227 | -------------------------------------------------------------------------------- /GUI/passfilter.py: -------------------------------------------------------------------------------- 1 | 2 | import numpy as np 3 | import pandas as pd 4 | from scipy import signal 5 | import matplotlib.pyplot as plt 6 | import serial 7 | import time 8 | 9 | # sosfiltfilt, sosfiltfilt, lfilter_zi, lfilter, lfiltic, savgol_filter, sosfilt 10 | 11 | def butter_highpass(cutoff, fs, order=4): 12 | nyq = 0.5 * fs 13 | normal_cutoff = cutoff / nyq 14 | b, a = signal.butter(order, normal_cutoff, btype='high', analog=False) 15 | return b, a 16 | 17 | def butter_highpass_filter(data, cutoff, fs, order=4): 18 | b, a = butter_highpass(cutoff, fs, order=order) 19 | y = signal.filtfilt(b, a, data) 20 | return y 21 | 22 | def butter_lowpass(cutoff, fs, order=4): 23 | nyq = 0.5 * fs 24 | normal_cutoff = cutoff / nyq 25 | b, a = signal.butter(order, normal_cutoff, btype='low', analog=False) 26 | return b, a 27 | 28 | def butter_lowpass_filter(data, cutoff, fs, order=4): 29 | b, a = butter_lowpass(cutoff, fs, order=order) 30 | y = signal.lfilter(b, a, data) 31 | return y 32 | 33 | def butter_bandpass(lowcut, highcut, fs, order=5): 34 | nyq = 0.5 * fs 35 | low = lowcut / nyq 36 | high = highcut / nyq 37 | b, a = signal.butter(order, [low, high], btype='band') 38 | return b, a 39 | 40 | def butter_bandpass_filter(data, lowcut, highcut, fs, order=5): 41 | b, a = butter_bandpass(lowcut, highcut, fs, order=order) 42 | y = signal.lfilter(b, a, data) 43 | return y 44 | 45 | -------------------------------------------------------------------------------- /ReadMe.txt: -------------------------------------------------------------------------------- 1 | In progress 2 | 3 | Real-time EEG BCI signal processing by Python 4 | Fourier transform (FFT) 5 | Wavelet transform 6 | Canonical correlation analysis (CCA) 7 | Linear discriminant analysis (LDA) 8 | Support vector machine (SVM) 9 | --------------------------------------------------------------------------------