-
Notifications
You must be signed in to change notification settings - Fork 3
/
SpectrumAnalyzer-v01c.py
1385 lines (1038 loc) · 43.5 KB
/
SpectrumAnalyzer-v01c.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# SpectrumAnalyzer-v01c.py(w) (26-10-2014)
# For Python version 2.6 or 2.7
# With external module pyaudio (for Python version 2.6 or 2.7); NUMPY module (for used Python version)
# Created by Onno Hoekstra (pa2ohh)
# Launchpad functionality by Siddharth Vadgama (@siddvee)
import pyaudio
import math
import time
import wave
import struct
import launchpad
import tkFont
from Tkinter import *
from tkFileDialog import askopenfilename
from tkSimpleDialog import askstring
from tkMessageBox import *
LP = launchpad.Launchpad()
LP.Open()
LP.Reset()
NUMPYenabled = True # If NUMPY installed, then the FFT calculations is 4x faster than the own FFT calculation
# Values that can be modified
GRWN = 800 # Width of the grid
GRHN = 400 # Height of the grid
X0L = 20 # Left top X value of grid
Y0T = 25 # Left top Y value of grid
Vdiv = 8 # Number of vertical divisions
TRACEmode = 1 # 1 normal mode, 2 max hold, 3 average
TRACEaverage = 10 # Number of average sweeps for average mode
TRACEreset = True # True for first new trace, reset max hold and averageing
SAMPLErate = 24000 # Sample rate of the soundcard 24000 48000 96000 192000
UPDATEspeed = 1.1 # Update speed can be increased when problems if PC too slow, default 1.1
ZEROpadding = 1 # ZEROpadding for signal interpolation between frequency samples (0=none)
DBdivlist = [1, 2, 3, 5, 10, 20] # dB per division
DBdivindex = 4 # 10 dB/div as initial value
DBlevel = 0 # Reference level
SMPfftlist = [64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536] # FFT samples list
SMPfftindex = 5 # index X (start with 0) from SMPfftlist as initial value
# Colors that can be modified
COLORframes = "#000080" # Color = "#rrggbb" rr=red gg=green bb=blue, Hexadecimal values 00 - ff
COLORcanvas = "#000000"
COLORgrid = "#808080"
COLORtrace1 = "#00ff00"
COLORtrace2 = "#ff8000"
COLORtext = "#ffffff"
COLORsignalband = "#ff0000"
COLORaudiobar = "#606060"
COLORaudiook = "#00ff00"
COLORaudiomax = "#ff0000"
# Button sizes that can be modified
Buttonwidth1 = 12
Buttonwidth2 = 8
# Initialisation of general variables
STARTfrequency = 0.0 # Startfrequency
STOPfrequency = 10000.0 # Stopfrequency
# Other global variables required in various routines
GRW = GRWN # Initialize GRW
GRH = GRHN # Initialize GRH
CANVASwidth = GRW + 2 * X0L # The canvas width
CANVASheight = GRH + 80 # The canvas height
AUDIOsignal1 = [] # Audio trace channel 1
AUDIOdevin = None # Audio device for input. None = Windows default
AUDIOdevout = None # Audio device for output. None = Windows default
WAVinput = 0 # DEFAULT 0 for Audio device input, 1 for WAV file channel 1 input, 2 for WAV file channel 2 input
FFTresult = [] # FFT result
T1line = [] # Trace line channel 1
T2line = [] # Trace line channel 2
S1line = [] # Line for start of signal band indication
S2line = [] # line for stop of signal band indication
RUNstatus = 1 # 0 stopped, 1 start, 2 running, 3 stop now, 4 stop and restart
AUDIOstatus = 0 # 0 audio off, 1 audio on
STOREtrace = False # Store and display trace
FFTwindow = 5 # FFTwindow 0=None (rectangular B=1), 1=Cosine (B=1.24), 2=Triangular non-zero endpoints (B=1.33),
# 3=Hann (B=1.5), 4=Blackman (B=1.73), 5=Nuttall (B=2.02), 6=Flat top (B=3.77)
AUDIOlevel = 0.0 # Level of audio input 0 to 1
RXbuffer = 0.0 # Data contained in input buffer in %
RXbufferoverflow = False
if NUMPYenabled == True:
try:
import numpy.fft
except:
NUMPYenabled = False
# =================================== Start widgets routines ========================================
def Bnot():
print "Routine not made yet"
def BNormalmode():
global TRACEmode
TRACEmode = 1
UpdateScreen() # Always Update
def BMaxholdmode():
global TRACEmode
global TRACEreset
TRACEreset = True # Reset trace peak and trace average
TRACEmode = 2
UpdateScreen() # Always Update
def BAveragemode():
global TRACEmode
global TRACEaverage
global TRACEreset
TRACEreset = True # Reset trace peak and trace average
TRACEmode = 3
s = askstring("Power averaging", "Value: " + str(TRACEaverage) + "x\n\nNew value:\n(1-n)")
if (s == None): # If Cancel pressed, then None
return()
try: # Error if for example no numeric characters or OK pressed without input (s = "")
v = int(s)
except:
s = "error"
if s != "error":
TRACEaverage = v
if TRACEaverage < 1:
TRACEaverage = 1
UpdateScreen() # Always Update
def BFFTwindow():
global FFTwindow
global TRACEreset
FFTwindow = FFTwindow + 1
if FFTwindow > 6:
FFTwindow = 0
TRACEreset = True # Reset trace peak and trace average
UpdateAll() # Always Update
def BAudiostatus():
global AUDIOstatus
global RUNstatus
if AUDIOstatus == 0:
AUDIOstatus = 1
else:
AUDIOstatus = 0
if RUNstatus == 0: # Update if stopped
UpdateScreen()
def BSTOREtrace():
global STOREtrace
global T1line
global T2line
if STOREtrace == False:
T2line = T1line
STOREtrace = True
else:
STOREtrace = False
UpdateTrace() # Always Update
def BScreensetup():
global GRWN
global GRW
global GRHN
global GRH
global STOREtrace
global Vdiv
if (STOREtrace == True):
showwarning("WARNING","Clear stored trace first")
return()
s = askstring("Screensize", "Give number:\n(1, 2 or 3)")
# if (s == None): # If Cancel pressed, then None
# return()
try: # Error if for example no numeric characters or OK pressed without input (s = "")
v = int(s)
except:
s = "error"
if s != "error":
if v == 1:
GRW = int(GRWN / 4)
GRH = int(GRHN / 4)
if v == 2:
GRW = int(GRWN / 2)
GRH = int(GRHN / 2)
if v == 3:
GRW = int(GRWN)
GRH = int(GRHN)
s = askstring("Divisions", "Value: " + str(Vdiv) + "\n\nNew value:\n(4-100)")
if (s == None): # If Cancel pressed, then None
return()
try: # Error if for example no numeric characters or OK pressed without input (s = "")
v = int(s)
except:
s = "error"
if s != "error":
Vdiv = v
if Vdiv < 4:
Vdiv = 4
if Vdiv > 100:
Vdiv = 100
UpdateTrace()
def BStart():
global RUNstatus
if (RUNstatus == 0):
RUNstatus = 1
UpdateScreen() # Always Update
def Blevel1():
global RUNstatus
global DBlevel
DBlevel = DBlevel - 1
if RUNstatus == 0: # Update if stopped
UpdateTrace()
def Blevel2():
global RUNstatus
global DBlevel
DBlevel = DBlevel + 1
if RUNstatus == 0: # Update if stopped
UpdateTrace()
def Blevel3():
global RUNstatus
global DBlevel
DBlevel = DBlevel - 10
if RUNstatus == 0: # Update if stopped
UpdateTrace()
def Blevel4():
global RUNstatus
global DBlevel
DBlevel = DBlevel + 10
if RUNstatus == 0: # Update if stopped
UpdateTrace()
def BStop():
global RUNstatus
if (RUNstatus == 1):
RUNstatus = 0
elif (RUNstatus == 2):
RUNstatus = 3
elif (RUNstatus == 3):
RUNstatus = 3
elif (RUNstatus == 4):
RUNstatus = 3
UpdateScreen() # Always Update
def BSetup():
global SAMPLErate
global ZEROpadding
global RUNstatus
global AUDIOsignal1
global T1line
global TRACEreset
if (RUNstatus != 0):
showwarning("WARNING","Stop sweep first")
return()
s = askstring("Sample rate","Sample rate of soundcard.\n\nValue: " + str(SAMPLErate) + "\n\nNew value:\n(6000, 12000, 24000, 48000, 96000, 192000)")
if (s == None): # If Cancel pressed, then None
return()
try: # Error if for example no numeric characters or OK pressed without input (s = "")
v = int(s)
except:
s = "error"
if s != "error":
SAMPLErate = v
AUDIOsignal1 = [] # Reset Audio trace channel 1
T1line = [] # Reset trace line 1
# StartStop = askyesno("Start Stop","Start-Stop mode on?", default = NO)
s = askstring("Zero padding","For better interpolation of levels between frequency samples.\nBut increases processing time!\n\nValue: " + str(ZEROpadding) + "\n\nNew value:\n(0-5, 0 is no zero padding)")
if (s == None): # If Cancel pressed, then None
return()
try: # Error if for example no numeric characters or OK pressed without input (s = "")
v = int(s)
except:
s = "error"
if s != "error":
if v < 0:
v = 0
if v > 5:
v = 5
ZEROpadding = v
TRACEreset = True # Reset trace peak and trace average
UpdateScreen() # Always Update
def BStartfrequency():
global STARTfrequency
global STOPfrequency
global RUNstatus
# if (RUNstatus != 0):
# showwarning("WARNING","Stop sweep first")
# return()
s = askstring("Startfrequency: ","Value: " + str(STARTfrequency) + " Hz\n\nNew value:\n")
if (s == None): # If Cancel pressed, then None
return()
try: # Error if for example no numeric characters or OK pressed without input (s = "")
v = int(s)
except:
s = "error"
if s != "error":
STARTfrequency = abs(v)
if STOPfrequency <= STARTfrequency:
STOPfrequency = STARTfrequency + 1
if RUNstatus == 0: # Update if stopped
UpdateTrace()
def BStopfrequency():
global STARTfrequency
global STOPfrequency
global RUNstatus
# if (RUNstatus != 0):
# showwarning("WARNING","Stop sweep first")
# return()
s = askstring("Stopfrequency: ","Value: " + str(STOPfrequency) + " Hz\n\nNew value:\n")
if (s == None): # If Cancel pressed, then None
return()
try: # Error if for example no numeric characters or OK pressed without input (s = "")
v = int(s)
except:
s = "error"
if s != "error":
STOPfrequency = abs(v)
if STOPfrequency < 10: # Minimum stopfrequency 10 Hz
STOPfrequency = 10
if STARTfrequency >= STOPfrequency:
STARTfrequency = STOPfrequency - 1
if RUNstatus == 0: # Update if stopped
UpdateTrace()
def Bsamples1():
global SMPfftindex
global RUNstatus
global TRACEreset
if (SMPfftindex >= 1):
SMPfftindex = SMPfftindex - 1
TRACEreset = True # Reset trace peak and trace average
if RUNstatus == 0: # Update if stopped
UpdateScreen()
if RUNstatus == 2: # Restart if running
RUNstatus = 4
def Bsamples2():
global SMPfftlist
global SMPfftindex
global RUNstatus
global TRACEreset
if (SMPfftindex < len(SMPfftlist) - 1):
SMPfftindex = SMPfftindex + 1
TRACEreset = True # Reset trace peak and trace average
if RUNstatus == 0: # Update if stopped
UpdateScreen()
if RUNstatus == 2: # Restart if running
RUNstatus = 4
def BDBdiv1():
global DBdivindex
global RUNstatus
if (DBdivindex >= 1):
DBdivindex = DBdivindex - 1
if RUNstatus == 0: # Update if stopped
UpdateTrace()
def BDBdiv2():
global DBdivindex
global DBdivlist
global RUNstatus
if (DBdivindex < len(DBdivlist) - 1):
DBdivindex = DBdivindex + 1
if RUNstatus == 0: # Update if stopped
UpdateTrace()
# ============================================ Main routine ====================================================
def AUDIOin(): # Read the audio from the stream and store the data into the arrays
global AUDIOsignal1
global AUDIOdevin
global AUDIOdevout
global RUNstatus
global AUDIOstatus
global SMPfftlist
global SMPfftindex
global SAMPLErate
global UPDATEspeed
global RXbuffer
global RXbufferoverflow
while (True): # Main loop
PA = pyaudio.PyAudio()
FORMAT = pyaudio.paInt16 # Audio format 16 levels and 2 channels
CHUNK = int(SMPfftlist[SMPfftindex])
# RUNstatus = 1 : Open Stream
if (RUNstatus == 1):
if UPDATEspeed < 1:
UPDATEspeed = 1.0
TRACESopened = 1
try:
chunkbuffer = CHUNK
if chunkbuffer < SAMPLErate / 10: # Prevent buffer overload if small number of samples
chunkbuffer = int(SAMPLErate / 10)
chunkbuffer = int(UPDATEspeed * chunkbuffer)
stream = PA.open(format = FORMAT,
channels = TRACESopened,
rate = SAMPLErate,
input = True,
output = True,
frames_per_buffer = int(chunkbuffer),
input_device_index = AUDIOdevin,
output_device_index = AUDIOdevout)
RUNstatus = 2
except: # If error in opening audio stream, show error
RUNstatus = 0
txt = "Sample rate: " + str(SAMPLErate) + ", try a lower sample rate.\nOr another audio device."
showerror("Cannot open Audio Stream", txt)
UpdateScreen() # UpdateScreen() call
# RUNstatus = 2: Reading audio data from soundcard
if (RUNstatus == 2):
buffervalue = stream.get_read_available() # Buffer reading testroutine
RXbuffer = 100.0 * float(buffervalue) / chunkbuffer # Buffer filled in %. Overflow at 2xchunkbuffer
RXbufferoverflow = False
try:
signals = stream.read(chunkbuffer) # Read samples from the buffer
except:
AUDIOsignal1 = []
RUNstatus = 4
RXbufferoverflow = True # Buffer overflow at 2x chunkbuffer
if (AUDIOstatus == 1): # Audio on
stream.write(signals, chunkbuffer)
# Start conversion audio samples to values -32762 to +32767 (one's complement)
Lsignals = len(signals) # Lenght of signals array
AUDIOsignal1 = [] # Clear the AUDIOsignal1 array for trace 1
Sbuffer = Lsignals / 2 # Sbuffer is number of values (2 bytes per audio sample value, 1 channel is 2 bytes)
i = 2 * int(Sbuffer - CHUNK) # Start value, first part is skipped due to possible distortions
if i < 0: # Prevent negative values for i
i = 0
s = Lsignals - 1
while (i < s):
v = ord(signals[i]) + 256 * ord(signals[i+1])
if v > 32767: # One's complement correction
v = v - 65535
AUDIOsignal1.append(v) # Append the value to the trace 1 array
i = i + 2 # 2 bytes per sample value and 1 trace is 2 bytes totally
UpdateAll() # Update Data, trace and screen
# RUNstatus = 3: Stop
# RUNstatus = 4: Stop and restart
if (RUNstatus == 3) or (RUNstatus == 4):
stream.stop_stream()
stream.close()
PA.terminate()
if RUNstatus == 3:
RUNstatus = 0 # Status is stopped
if RUNstatus == 4:
RUNstatus = 1 # Status is (re)start
UpdateScreen() # UpdateScreen() call
# print SMPfftlist
# print RXbuffer
# Update tasks and screens by TKinter
root.update_idletasks()
root.update() # update screens
def WAVin(): # Read the audio from the WAV file and store the data into the array and read data from the array
global WAVinput
global WAVframes
global WAVchannels
global WAVsamplewidth
global WAVframerate
global WAVsignal1
global WAVsignal2
global WAVfilename
global AUDIOsignal1
global AUDIOdevin
global AUDIOdevout
global RUNstatus
global AUDIOstatus
global SMPfftlist
global SMPfftindex
global SAMPLErate
global UPDATEspeed
global RXbuffer
global RXbufferoverflow
while (True): # Main loop
CHUNK = int(SMPfftlist[SMPfftindex])
# RUNstatus = 1 : Open WAV file
if (RUNstatus == 1):
chunkbuffer = CHUNK
WAVfilename = ASKWAVfilename()
if (WAVfilename == None): # No input, cancel or error
WAVfilename = ""
if (WAVfilename == ""):
RUNstatus = 0
else:
WAVf = wave.open(WAVfilename, 'rb')
WAVframes = WAVf.getnframes()
# print "frames: ", WAVframes
WAVchannels = WAVf.getnchannels()
# print "channels: ", WAVchannels
WAVsamplewidth = WAVf.getsampwidth()
# print "samplewidth: ", WAVsamplewidth
WAVframerate = WAVf.getframerate()
# print "framerate: ", WAVframerate
SAMPLErate = WAVframerate
signals = WAVf.readframes(WAVframes) # Read the data from the WAV file and convert to WAVsignalx[]
i = 0
f = 0
s = ""
WAVsignal1 = []
WAVsignal2 = []
if (WAVsamplewidth == 1) and (WAVchannels == 1):
while (f < WAVframes):
s = str(struct.unpack('B', signals[i:(i+1)]))
v = int(s[1:-2]) - 128
WAVsignal1.append(v)
WAVsignal2.append(0)
i = i + 1
f = f + 1
if (WAVsamplewidth == 1) and (WAVchannels == 2):
while (f < WAVframes):
s = str(struct.unpack('B', signals[i:(i+1)]))
v = int(s[1:-2]) - 128
WAVsignal1.append(v)
s = str(struct.unpack('B', signals[(i+1):(i+2)]))
v = int(s[1:-2])
WAVsignal2.append(v)
i = i + 2
f = f + 1
if (WAVsamplewidth == 2) and (WAVchannels == 1):
while (f < WAVframes):
s = str(struct.unpack('h', signals[i:(i+2)]))
v = int(s[1:-2])
WAVsignal1.append(v)
WAVsignal2.append(0)
i = i + 2
f = f + 1
if (WAVsamplewidth == 2) and (WAVchannels == 2):
while (f < WAVframes):
s = str(struct.unpack('h', signals[i:(i+2)]))
v = int(s[1:-2])
WAVsignal1.append(v)
s = str(struct.unpack('h', signals[(i+2):(i+4)]))
v = int(s[1:-2])
WAVsignal2.append(v)
i = i + 4
f = f + 1
WAVf.close()
WAVpntr = 0 # Pointer to WAV array that has to be read
UpdateScreen() # UpdateScreen() call
if RUNstatus == 1:
RUNstatus = 2
# RUNstatus = 2: Reading audio data from WAVsignalx array
if (RUNstatus == 2):
RXbuffer = 0 # Buffer filled in %. No overflow for WAV mode
RXbufferoverflow = False
AUDIOsignal1 = []
n = 0
if WAVinput == 1:
while n < chunkbuffer:
v = WAVsignal1[WAVpntr]
AUDIOsignal1.append(v)
WAVpntr = WAVpntr + 1
if WAVpntr >= len(WAVsignal1):
WAVpntr = 0
n = n + 1
if WAVinput == 2:
while n < chunkbuffer:
v = WAVsignal2[WAVpntr]
AUDIOsignal1.append(v)
WAVpntr = WAVpntr + 1
if WAVpntr >= len(WAVsignal2):
WAVpntr = 0
n = n + 1
UpdateAll() # Update Data, trace and screen
if (RUNstatus == 3) or (RUNstatus == 4):
RUNstatus = 0 # Status is stopped
UpdateScreen() # UpdateScreen() call
# Update tasks and screens by TKinter
root.update_idletasks()
root.update() # update screens
def UpdateAll(): # Update Data, trace and screen
DoFFT() # Fast Fourier transformation
MakeTrace() # Update the traces
UpdateScreen() # Update the screen
def UpdateTrace(): # Update trace and screen
MakeTrace() # Update traces
UpdateScreen() # Update the screen
def UpdateScreen(): # Update screen with trace and text
MakeScreen() # Update the screen
root.update() # Activate updated screens
def DoFFT(): # Fast Fourier transformation
global AUDIOsignal1
global TRACEmode
global TRACEaverage
global TRACEreset
global ZEROpadding
global FFTresult
global AUDIOlevel
global FFTwindow
global NUMPYenabled
T1 = time.time() # For time measurement of FFT routine
REX = []
IMX = []
fftsamples = len(AUDIOsignal1)
if fftsamples < 64: # No FFT if empty or too short array of audio samples
return
n = 0
AUDIOlevel = 0.0
v = 0.0
m = 0 # For calculation of correction factor
while n < fftsamples:
v = float(AUDIOsignal1[n]) / 16000 # Convert to values between -1 and +1 (should be / 32000 for a good soundcard)
# Check for overload
va = abs(v) # Check for too high audio input level
if va > AUDIOlevel:
AUDIOlevel = va
# Cosine window function
# medium-dynamic range B=1.24
if FFTwindow == 1:
w = math.sin(math.pi * n / (fftsamples - 1))
v = w * v * 1.571
# Triangular non-zero endpoints
# medium-dynamic range B=1.33
if FFTwindow == 2:
w = (2.0 / fftsamples) * ((fftsamples / 2.0) - abs(n - (fftsamples - 1) / 2.0))
v = w * v * 2.0
# Hann window function
# medium-dynamic range B=1.5
if FFTwindow == 3:
w = 0.5 - 0.5 * math.cos(2 * math.pi * n / (fftsamples - 1))
v = w * v * 2.000
# Blackman window, continuous first derivate function
# medium-dynamic range B=1.73
if FFTwindow == 4:
w = 0.42 - 0.5 * math.cos(2 * math.pi * n / (fftsamples - 1)) + 0.08 * math.cos(4 * math.pi * n / (fftsamples - 1))
v = w * v * 2.381
# Nuttall window, continuous first derivate function
# high-dynamic range B=2.02
if FFTwindow == 5:
w = 0.355768 - 0.487396 * math.cos(2 * math.pi * n / (fftsamples - 1)) + 0.144232 * math.cos(4 * math.pi * n / (fftsamples - 1))- 0.012604 * math.cos(6 * math.pi * n / (fftsamples - 1))
v = w * v * 2.811
# Flat top window,
# medium-dynamic range, extra wide bandwidth B=3.77
if FFTwindow == 6:
w = 1.0 - 1.93 * math.cos(2 * math.pi * n / (fftsamples - 1)) + 1.29 * math.cos(4 * math.pi * n / (fftsamples - 1))- 0.388 * math.cos(6 * math.pi * n / (fftsamples - 1)) + 0.032 * math.cos(8 * math.pi * n / (fftsamples - 1))
v = w * v * 1.000
# m = m + w / fftsamples # For calculation of correction factor
REX.append(v) # Append the value to the REX array
IMX.append(0.0) # Append 0 to the imagimary part
n = n + 1
# if m > 0: # For calculation of correction factor
# print 1/m # For calculation of correction factor
# Zero padding of array for better interpolation of peak level of signals
ZEROpaddingvalue = int(math.pow(2,ZEROpadding) + 0.5)
fftsamples = ZEROpaddingvalue * fftsamples # Add zero's to the arrays
# The FFT calculation with NUMPY if NUMPYenabled == True or with the FFT calculation below
if NUMPYenabled == True:
fftresult = numpy.fft.fft(REX, n=fftsamples)# Do FFT+zeropadding till n=fftsamples with NUMPY if NUMPYenabled == True
REX=fftresult.real
IMX=fftresult.imag
else: # Else use the FFT calculation here below
while len(REX) < fftsamples: # Zeropadding (add zeros till len(REX) = fftsamples
REX.append(0)
IMX.append(0)
Pi = math.pi
NM1 = 0
ND2 = 0
M = 0
j = 0
K = 0
L = 0
LE = 0
LE2 = 0
JM1 = 0
i = 0
IP = 0
TR = 0.0
TI = 0.0
UR = 0.0
UI = 0.0
SR = 0.0
SI = 0.0
N = int(fftsamples)
NM1 = N - 1
ND2 = N / 2
M = int(math.log(N,2) + 0.5)
j = ND2
i = 1
while i <= (N - 2): # Bit reversal sorting
if i < j:
TR = REX[j]
TI = IMX[j]
REX[j] = REX[i]
IMX[j] = IMX[i]
REX[i] = TR
IMX[i] = TI
K = ND2
while K <= j:
j = j - K
K = K / 2
j = j + K
i = i + 1
L = 1
while L <= M: # Loop for each stage
LE = int(math.pow(2,L) + 0.5)
LE2 = LE / 2
UR = 1
UI = 0
SR = math.cos(Pi / LE2) # Calculate sine & cosine values
SI = -1 * math.sin(Pi / LE2)
j = 1
while j <= LE2: # Loop for each sub DFT
JM1 = j - 1
i = JM1
while i <= NM1: # Loop for each butterfly
IP = i + LE2
TR = REX[IP] * UR - IMX[IP] * UI #Butterfly calculation
TI = REX[IP] * UI + IMX[IP] * UR
REX[IP] = REX[i] - TR
IMX[IP] = IMX[i] - TI
REX[i] = REX[i] + TR
IMX[i] = IMX[i] + TI
i = i + LE
TR = UR
UR = TR * SR - UI * SI
UI = TR * SI + UI * SR
j = j + 1
L = L + 1
# Make FFT result array
Totalcorr = float(ZEROpaddingvalue)/ fftsamples # For VOLTAGE!
Totalcorr = Totalcorr * Totalcorr # For POWER!
FFTmemory = FFTresult
FFTresult = []
n = 0
while (n <= fftsamples / 2):
# For relative to voltage: v = math.sqrt(REX[n] * REX[n] + IMX[n] * IMX[n]) # Calculate absolute value from re and im
v = REX[n] * REX[n] + IMX[n] * IMX[n] # Calculate absolute value from re and im relative to POWER!
v = v * Totalcorr # Make level independent of samples and convert to display range
if TRACEmode == 1: # Normal mode, do not change v
pass
if TRACEmode == 2 and TRACEreset == False: # Max hold, change v to maximum value
if v < FFTmemory[n]:
v = FFTmemory[n]
if TRACEmode == 3 and TRACEreset == False: # Average, add difference / TRACEaverage to v
v = FFTmemory[n] + (v - FFTmemory[n]) / TRACEaverage
FFTresult.append(v) # Append the value to the FFTresult array
n = n + 1
TRACEreset = False # Trace reset done
# print len(FFTresult)
#launchpad()
T2 = time.time()
# print (T2 - T1) # For time measurement of FFT routine
def launchpad():
#print "launchpad"
global FFTresult
global T1line
localFFT = FFTresult
aggregateFFT = []
localIndex = 0
localMax = 400
for (i, item) in enumerate(T1line):
if (i % 2 == 0): #even
pass
else:
item = item-25
localIndex += 1
if item < localMax:
localMax = item
if localIndex >= 212:
aggregateFFT.append(localMax)
localIndex = 0
localMax = 400
print aggregateFFT
#print len(T1line)
for (i, item) in enumerate(aggregateFFT):
item = item/50
bar = math.floor(item)
bar = int(bar)
bar = 8-bar
if bar > 8:
bar = 8
if bar < 0:
bar = 0
#print bar
for x in range(1, 9):
if x <= bar:
if x <= 2:
LP.LedCtrlXY(i, 9-x, 0, 4)
if x > 2 and x <= 4:
LP.LedCtrlXY(i, 9-x, 2, 4)
if x > 4:
LP.LedCtrlXY(i, 9-x, 4, 0)
else:
LP.LedCtrlXY(i, 9-x, 0, 0)