-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathIMU_GUI.py
1065 lines (817 loc) · 33.5 KB
/
IMU_GUI.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
<<<<<<< HEAD
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# Author : MikeChan
# Email : [email protected]
# Date : 06/21/2016
import time, sys, os, datetime, threading
from PyQt4.QtCore import *
from PyQt4.QtGui import *
#===== Global Varibles =====
now = datetime.datetime.now()
today = str( str(now).split(" ")[0].split("-")[0] + str(now).split(" ")[0].split("-")[1] + str(now).split(" ")[0].split("-")[2] )
tonow = str( str(now).split(" ")[1].split(":")[0] + str(now).split(" ")[1].split(":")[1] )
#===== for raspberry PI =====
import smbus
import picamera
i2c = smbus.SMBus(1)
#enable pi-camera
try:
camera = picamera.PiCamera()
except:
pass
addr = 0x68
raw_data = []
#====== QT area ======
class IMU_GUI(QWidget):
def __init__(self, parent = None):
super(IMU_GUI, self).__init__(parent)
self.imu_start_record = imu_start_record()
self.imu_start_record_stable = imu_start_record_stable()
self.save_record = save_record()
# create Layout and connection
self.createLayout()
self.createConnection()
# window properties adjustment
self.setGeometry(140,70,300,400)
#self.resize(300,400)
#self.move(140,35)
self.setWindowIcon(QIcon('/home/pi/Self_IMU/icon/QIMU.png'))
self.setWindowTitle("MPU9250 & PiCamera GUI")
# varibles
self.preview_switch = False
self.film_switch = False
self.IMU_KEY = False
self.photo_count = 0
self.video_count = 0
self.path = "%s_%s" % (today, tonow)
if not os.path.exists(self.path):
try:
os.makedirs(self.path)
except OSError:
if not os.path.isdir(self.path):
raise
def createLayout(self):
#===== IMU Layout =====
self.IMU_Label = QLabel("@ IMU Area @")
self.stableCheckBox = QCheckBox(u"即時慢速寫入")
h0=QHBoxLayout()
h0.addWidget(self.IMU_Label)
h0.addWidget(self.stableCheckBox)
self.statusBrowser = QTextBrowser()
h1 = QHBoxLayout()
h1.addWidget(self.statusBrowser)
self.startButton = QPushButton("Start IMU")
self.stopButton = QPushButton("Stop IMU")
self.saveButton = QPushButton("Save Data")
h2 = QHBoxLayout()
h2.addWidget(self.startButton)
h2.addWidget(self.stopButton)
h2.addWidget(self.saveButton)
#===== PiCamera layout ======
self.PiCamera_Label = QLabel("@ PiCamera Area @")
h3=QHBoxLayout()
h3.addWidget(self.PiCamera_Label)
self.camBrowser = QTextBrowser()
h4 = QHBoxLayout()
h4.addWidget(self.camBrowser)
self.previewButton = QPushButton("Preview")
self.filmButton = QPushButton("Filming")
self.photoButton = QPushButton("Photo Take")
h5 = QHBoxLayout()
h5.addWidget(self.previewButton)
h5.addWidget(self.filmButton)
h5.addWidget(self.photoButton)
# setting layout
layout1 = QVBoxLayout()
layout2 = QVBoxLayout()
layout0 = QVBoxLayout()
# IMU Layout
layout1.addLayout(h0)
layout1.addLayout(h1)
layout1.addLayout(h2)
# PiCamera Layout
layout2.addLayout(h3)
layout2.addLayout(h4)
layout2.addLayout(h5)
layout0.addLayout(layout1)
layout0.addLayout(layout2)
self.setLayout(layout0)
self.previewButton.setEnabled(True)
self.filmButton.setEnabled(True)
self.photoButton.setEnabled(True)
self.startButton.setEnabled(True)
self.stopButton.setEnabled(False)
self.saveButton.setEnabled(False)
def createConnection(self):
#===== Picamera related =====
self.previewButton.clicked.connect(self.preview)
self.filmButton.clicked.connect(self.film)
self.photoButton.clicked.connect(self.take_photo)
#===== IMU related =====
self.startButton.clicked.connect(self.start)
self.stopButton.clicked.connect(self.stop)
self.saveButton.clicked.connect(self.save)
self.connect(self.save_record, SIGNAL("finished()"), self.finished)
#====== Stable CheckBox related =====
self.stableCheckBox.stateChanged.connect(self.enable_stable)
#===== IMU Func. area =====
def start(self):
test_t0 = time.time()
self.statusBrowser.append("MPU9250 BootUp...")
#===== IMU initial =====
try:
i2c.write_byte_data(0x68, 0x6a, 0x00) # Clear sleep mode bit (6), enable all sensors
time.sleep(0.1) # Wait for all registers to reset
i2c.write_byte_data(0x68, 0x1a, 0x03)
# Configure Gyro and Thermometer
# Disable FSYNC and set thermometer and gyro bandwidth to 41 and 42 Hz, respectively;
# minimum delay time for this setting is 5.9 ms, which means sensor fusion update rates cannot
# be higher than 1 / 0.0059 = 170 Hz
# DLPF_CFG = bits 2:0 = 011; this limits the sample rate to 1000 Hz for both
# With the MPU9250, it is possible to get gyro sample rates of 32 kHz (!), 8 kHz, or 1 kHz
i2c.write_byte_data(0x68, 0x19, 0x04)
# sample_rate = internal_sample_rate/ (1+SMPLRT_DIV)
# Use a 200 Hz rate; a rate consistent with the filter update rate
#determined inset in CONFIG above
#ACC_CFG = i2c.read_byte_data(0x68, 0x1c)
#ACC_CFG_2 = i2c.read_byte_data(0x68, 0x1D)
#GYRO_CFG = i2c.read_byte_data(0x68, 0x1b)
'''
# add bias to offset ax_bias=71=0x47 , ay_bias= -56 =FFC7 , az_bias= -502 = FE09
# ax_offset high bit
i2c.write_byte_data(0x68, 0x77, 0x00)
# ax_offset low bit
i2c.write_byte_data(0x68, 0x78, 0x00)
# ay_offset high bit
i2c.write_byte_data(0x68, 0x7A, 0x00)
# ay_offset low bit
i2c.write_byte_data(0x68, 0x7B, 0x00)
# az_offset high bit
i2c.write_byte_data(0x68, 0x7D, 0x00)
# az_offset low bit
i2c.write_byte_data(0x68, 0x7E, 0x00)
'''
i2c.write_byte_data(0x68, 0x37, 0x02) # set pass-through mode
time.sleep(0.1)
i2c.write_byte_data(0x0c, 0x0a, 0x16) # enable AKM
time.sleep(0.1)
self.statusBrowser.append("Initialization Done!")
self.IMU_KEY = True
except:
self.statusBrowser.append("Bootup Failed! Check Wiring...")
self.IMU_KEY = False
self.startButton.setEnabled(True)
self.stopButton.setEnabled(False)
self.saveButton.setEnabled(False)
#===== end initial ======
if self.IMU_KEY and not self.stableCheckBox.isChecked():
self.tt0 = time.time()
self.statusBrowser.append("Start Recording....")
self.startButton.setEnabled(False)
self.stopButton.setEnabled(True)
self.saveButton.setEnabled(False)
self.imu_start_record.start()
elif self.IMU_KEY and self.stableCheckBox.isChecked():
self.tt0 = time.time()
self.statusBrowser.append("Start Recording in Stable Status...")
self.startButton.setEnabled(False)
self.stopButton.setEnabled(True)
self.saveButton.setEnabled(False)
self.imu_start_record_stable.start()
def stop(self):
global raw_data
self.duringTime = time.time() - self.tt0
self.statusBrowser.append("Record Stop!")
self.statusBrowser.append("During Time: " + "%.2f" %self.duringTime)
if not self.stableCheckBox.isChecked():
self.imu_start_record.stop()
self.startButton.setEnabled(True)
self.stopButton.setEnabled(False)
self.saveButton.setEnabled(True)
elif self.stableCheckBox.isChecked():
self.imu_start_record_stable.stop()
self.startButton.setEnabled(True)
self.stopButton.setEnabled(False)
self.saveButton.setEnabled(False)
self.statusBrowser.append("== Data Saved and Port Clear ==")
def save(self):
self.statusBrowser.append("Data saving....")
time.sleep(0.5)
self.save_record.start()
self.startButton.setEnabled(False)
self.stopButton.setEnabled(False)
self.saveButton.setEnabled(False)
def finished(self): # will be call when save_record was finished
self.statusBrowser.append("Data saved, memory clear.")
self.statusBrowser.append("===== End Section =====")
self.saveButton.setEnabled(False)
self.stopButton.setEnabled(False)
self.startButton.setEnabled(True)
def enable_stable(self):
check_stable = QMessageBox.question(self, u'啟動即時寫入', \
u"此選項將延遲每筆資料速度,並保證資料即時記錄於檔案中,確定嗎?\n 按'Yes'啟動即時檔案寫入,\n 按'NO'取消即時檔案寫入", \
QMessageBox.Yes | QMessageBox.No)
if check_stable == QMessageBox.Yes:
self.statusBrowser.append(u"*IMU即時寫入已啟動")
self.stableCheckBox.setCheckState(2)
self.saveButton.setEnabled(False)
else:
self.statusBrowser.append(u"*取消即時寫入")
self.stableCheckBox.setCheckState(0)
self.saveButton.setEnabled(True)
#===== Picamera Func. area =====
def preview(self):
camera.stop_preview()
if not self.preview_switch:
self.camBrowser.append("Preview on.")
camera.start_preview(fullscreen = False, window = (450, 10, 400, 300) )
self.preview_switch = True
elif self.preview_switch:
self.camBrowser.append("Preview off.")
self.camBrowser.append("==========")
camera.stop_preview()
self.preview_switch = False
else:
self.camBrowser.append("Prview Booom!")
def film(self):
#camera.stop_recording()
film_path = self.path
if not os.path.exists(film_path):
try:
os.makedirs(film_path)
except OSError:
if not os.path.isdir(film_path):
raise
if not self.film_switch:
self.camBrowser.append("Start Filming...")
self.video_count += 1
camera.start_recording(film_path + '/video%d.h264' %(self.video_count) )
self.film_switch = True
self.photoButton.setEnabled(False)
elif self.film_switch:
self.camBrowser.append("Stop Filming...")
camera.stop_recording()
self.camBrowser.append("Film saved.")
self.film_switch = False
self.camBrowser.append("==========")
self.photoButton.setEnabled(True)
else:
self.camBrowser.append("Film Booom!")
def take_photo(self):
self.photo_count += 1
self.filmButton.setEnabled(False)
self.photoButton.setEnabled(False)
# Create "Photo" folder if not exist
photo_path = self.path
if not os.path.exists(photo_path):
try:
os.makedirs(photo_path)
except OSError:
if not os.path.isdir(photo_path):
raise
camera.capture(photo_path + '/image%d.jpg' %self.photo_count )
self.camBrowser.append("image%d saved" %self.photo_count )
self.photoButton.setEnabled(True)
self.filmButton.setEnabled(True)
class imu_start_record(QThread):
def __init__(self, parent=None):
super(self.__class__, self).__init__(parent)
self.stoped = False
self.mutex = QMutex()
def run(self):
global raw_data
# varibles
self.t0 = time.time()
self.t_a_g = []
with QMutexLocker(self.mutex):
self.stoped = False
while 1:
if not self.stoped:
self.mpu9250_data_get_and_write()
else:
#print("break!")
break
raw_data = list(self.t_a_g)
#print "data copy!"
def stop(self):
with QMutexLocker(self.mutex):
self.stoped = True
def isStop(self):
with QMutexLocker(self.mutex):
return self.stoped
def mpu9250_data_get_and_write(self):
# keep AKM pointer on continue measuring
i2c.write_byte_data(0x0c, 0x0a, 0x16)
# get MPU9250 smbus block data
#xyz_g_offset = i2c.read_i2c_block_data(addr, 0x13, 6)
xyz_a_out = i2c.read_i2c_block_data(addr, 0x3B, 6)
xyz_g_out = i2c.read_i2c_block_data(addr, 0x43, 6)
#xyz_a_offset = i2c.read_i2c_block_data(addr, 0x77, 6)
# get AK8963 smbus data (by pass-through way)
xyz_mag = i2c.read_i2c_block_data(0x0c, 0x03, 6)
#xyz_mag_adj = i2c.read_i2c_block_data(0x0c, 0x10, 3)
# get real time
t1 = time.time() - self.t0
# save file to list buffer
self.t_a_g.append(t1)
self.t_a_g.append(xyz_a_out)
self.t_a_g.append(xyz_g_out)
self.t_a_g.append(xyz_mag)
#self.t_a_g.append(xyz_mag_adj)
time.sleep(0.00001)
class imu_start_record_stable(QThread):
def __init__(self, parent=None):
super(self.__class__, self).__init__(parent)
self.stoped = False
self.mutex = QMutex()
self.imu_count_stable = 0
def run(self):
self.t0 = time.time()
self.imu_count_stable += 1
with QMutexLocker(self.mutex):
self.stoped = False
while 1:
if not self.stoped:
self.mpu9250_data_get_and_write()
else:
break
def stop(self):
with QMutexLocker(self.mutex):
self.stoped = True
def isStop(self):
with QMutexLocker(self.mutex):
return self.stoped
def mpu9250_data_get_and_write(self):
# keep AKM pointer on continue measuring
i2c.write_byte_data(0x0c, 0x0a, 0x16)
# get MPU9250 smbus block data
#xyz_g_offset = i2c.read_i2c_block_data(addr, 0x13, 6)
xyz_a_out = i2c.read_i2c_block_data(addr, 0x3B, 6)
xyz_g_out = i2c.read_i2c_block_data(addr, 0x43, 6)
#xyz_a_offset = i2c.read_i2c_block_data(addr, 0x77, 6)
# get AK8963 smbus data (by pass-through way)
xyz_mag = i2c.read_i2c_block_data(0x0c, 0x03, 6)
#xyz_mag_adj = i2c.read_i2c_block_data(0x0c, 0x10, 3)
# get real time
t1 = time.time() - self.t0
# save file to list buffer
#self.t_a_g.append(t1)
#self.t_a_g.append(xyz_a_out)
#self.t_a_g.append(xyz_g_out)
#self.t_a_g.append(xyz_mag)
#t_a_g.append(xyz_mag_adj)
filename = "IMU_LOG_REALTIME_%s.txt" %(self.imu_count_stable)
file_s = open(filename, "a")
print >> file_s, "%f" %t1
print >> file_s, xyz_a_out
print >> file_s, xyz_g_out
print >> file_s, xyz_mag
file_s.close()
time.sleep(0.00001)
class save_record(QThread):
def __init__(self, parent=None):
super(self.__class__, self).__init__(parent)
self.imu_count = 0
def run(self):
global raw_data
self.imu_count += 1
try:
filename = "IMU_LOG_%s.txt" %(self.imu_count)
self.data_f = open(filename, "w")
for i in raw_data:
if isinstance(i, float):
print >> self.data_f ,"%f" %i
else:
print >> self.data_f , i
except:
print "Data saving failed"
finally:
i2c.write_byte_data(addr, 0x6A, 0x07)
raw_data = []
self.data_f.close()
if __name__ == "__main__":
app=QApplication(sys.argv)
IMU_GUI = IMU_GUI()
IMU_GUI.show()
sys.exit(app.exec_())
=======
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# Author : MikeChan
# Email : [email protected]
# Date : 06/21/2016
import time, sys, os, datetime, threading
from PyQt4.QtCore import *
from PyQt4.QtGui import *
#===== Global Varibles =====
now = datetime.datetime.now()
today = str( str(now).split(" ")[0].split("-")[0] + str(now).split(" ")[0].split("-")[1] + str(now).split(" ")[0].split("-")[2] )
tonow = str( str(now).split(" ")[1].split(":")[0] + str(now).split(" ")[1].split(":")[1] )
countdown_sec = 0
#===== for raspberry PI =====
import smbus
import picamera
i2c = smbus.SMBus(1)
#enable pi-camera
try:
camera = picamera.PiCamera()
except:
pass
addr = 0x68
raw_data = []
#====== QT area ======
class IMU_GUI(QWidget):
global countdown_sec
def __init__(self, parent = None):
super(IMU_GUI, self).__init__(parent)
self.imu_start_record = imu_start_record()
self.imu_start_record_stable = imu_start_record_stable()
self.save_record = save_record()
# create Layout and connection
self.createLayout()
self.createConnection()
# window properties adjustment
self.setGeometry(140,70,300,400)
#self.resize(300,400)
#self.move(140,35)
self.setWindowIcon(QIcon('/home/pi/Self_IMU/icon/QIMU.png'))
self.setWindowTitle("MPU9250 & PiCamera GUI")
# varibles
self.preview_switch = False
self.film_switch = False
self.IMU_KEY = False
self.PAUSE_KEY = False
self.photo_count = 0
self.video_count = 0
self.path = "%s_%s" % (today, tonow)
if not os.path.exists(self.path):
try:
os.makedirs(self.path)
except OSError:
if not os.path.isdir(self.path):
raise
def createLayout(self):
#===== IMU Layout =====
self.IMU_Label = QLabel("@ IMU Area @")
self.stableCheckBox = QCheckBox(u"即時慢速寫入")
self.stableCheckBox.setChecked(True)
h0=QHBoxLayout()
h0.addWidget(self.IMU_Label)
h0.addWidget(self.stableCheckBox)
self.record_sec_le = QLineEdit()
self.sec_label = QLabel(u'分')
self.set_record_sec_btn = QPushButton(u"輸入幾分鐘(0=無限)")
h01 =QHBoxLayout()
h01.addWidget(self.record_sec_le)
h01.addWidget(self.sec_label)
h01.addWidget(self.set_record_sec_btn)
self.record_sec_le.setText(str(0))
self.statusBrowser = QTextBrowser()
h1 = QHBoxLayout()
h1.addWidget(self.statusBrowser)
self.startButton = QPushButton("Start IMU")
self.pauseButton = QPushButton("Pause/Resume")
self.stopButton = QPushButton("Stop IMU")
self.saveButton = QPushButton("Save Data")
h2 = QHBoxLayout()
h2.addWidget(self.startButton)
#h2.addWidget(self.pauseButton)
h2.addWidget(self.stopButton)
h2.addWidget(self.saveButton)
#===== PiCamera layout ======
self.PiCamera_Label = QLabel("@ PiCamera Area @")
h3=QHBoxLayout()
h3.addWidget(self.PiCamera_Label)
self.camBrowser = QTextBrowser()
h4 = QHBoxLayout()
h4.addWidget(self.camBrowser)
self.previewButton = QPushButton("Preview")
self.filmButton = QPushButton("Filming")
self.photoButton = QPushButton("Photo Take")
h5 = QHBoxLayout()
h5.addWidget(self.previewButton)
h5.addWidget(self.filmButton)
h5.addWidget(self.photoButton)
# setting layout
layout1 = QVBoxLayout()
layout2 = QVBoxLayout()
layout0 = QVBoxLayout()
# IMU Layout
layout1.addLayout(h0)
layout1.addLayout(h01)
layout1.addLayout(h1)
layout1.addLayout(h2)
# PiCamera Layout
layout2.addLayout(h3)
layout2.addLayout(h4)
layout2.addLayout(h5)
layout0.addLayout(layout1)
layout0.addLayout(layout2)
self.setLayout(layout0)
self.previewButton.setEnabled(True)
self.filmButton.setEnabled(True)
self.photoButton.setEnabled(True)
self.startButton.setEnabled(True)
self.stopButton.setEnabled(False)
self.saveButton.setEnabled(False)
def createConnection(self):
#===== IMU related =====
self.set_record_sec_btn.clicked.connect(self.set_record_sec)
self.startButton.clicked.connect(self.start)
self.pauseButton.clicked.connect(self.pause)
self.stopButton.clicked.connect(self.stop)
self.saveButton.clicked.connect(self.save)
#self.connect(self.save_record, SIGNAL("finished()"), self.finished)
#===== Picamera related =====
self.previewButton.clicked.connect(self.preview)
self.filmButton.clicked.connect(self.film)
self.photoButton.clicked.connect(self.take_photo)
#====== Stable CheckBox related =====
self.stableCheckBox.stateChanged.connect(self.enable_stable)
#===== IMU Func. area =====
def set_record_sec(self):
num,ok = QInputDialog.getInt(self,u"預計IMU紀錄時間",u"輸入想要紀錄幾分鐘")
if ok:
self.record_sec_le.setText(str(num))
def start(self):
test_t0 = time.time()
countdown_sec = self.record_sec_le.text() * 60
self.statusBrowser.append("MPU9250 BootUp...")
#===== IMU initial =====
try:
i2c.write_byte_data(0x68, 0x6a, 0x00) # Clear sleep mode bit (6), enable all sensors
time.sleep(0.1) # Wait for all registers to reset
i2c.write_byte_data(0x68, 0x1a, 0x03)
# Configure Gyro and Thermometer
# Disable FSYNC and set thermometer and gyro bandwidth to 41 and 42 Hz, respectively;
# minimum delay time for this setting is 5.9 ms, which means sensor fusion update rates cannot
# be higher than 1 / 0.0059 = 170 Hz
# DLPF_CFG = bits 2:0 = 011; this limits the sample rate to 1000 Hz for both
# With the MPU9250, it is possible to get gyro sample rates of 32 kHz (!), 8 kHz, or 1 kHz
i2c.write_byte_data(0x68, 0x19, 0x04)
# sample_rate = internal_sample_rate/ (1+SMPLRT_DIV)
# Use a 200 Hz rate; a rate consistent with the filter update rate
#determined inset in CONFIG above
#ACC_CFG = i2c.read_byte_data(0x68, 0x1c)
#ACC_CFG_2 = i2c.read_byte_data(0x68, 0x1D)
#GYRO_CFG = i2c.read_byte_data(0x68, 0x1b)
i2c.write_byte_data(0x68, 0x37, 0x02) # set pass-through mode
time.sleep(0.1)
i2c.write_byte_data(0x0c, 0x0a, 0x16) # enable AKM
time.sleep(0.1)
self.statusBrowser.append("Initialization Done!")
self.IMU_KEY = True
except:
self.statusBrowser.append("Bootup Failed! Check Wiring...")
self.IMU_KEY = False
self.startButton.setEnabled(True)
self.stopButton.setEnabled(False)
self.saveButton.setEnabled(False)
#===== end initial ======
countdown_sec = int(self.record_sec_le.text()) *60
s = u"預定記錄秒數: %ss" %countdown_sec
self.statusBrowser.append(s)
#確認 stable checkbox 是否開啟
if self.IMU_KEY and not self.stableCheckBox.isChecked():
self.tt0 = time.time()
self.statusBrowser.append(u"開始紀錄...")
self.imu_start_record.start()
elif self.IMU_KEY and self.stableCheckBox.isChecked():
self.tt0 = time.time()
self.statusBrowser.append(u"即時存檔狀態->開始紀錄...")
self.imu_start_record_stable.start()
# 防誤觸鎖鍵
self.startButton.setEnabled(False)
self.stopButton.setEnabled(True)
self.saveButton.setEnabled(False)
def pause(self):
if not self.stableCheckBox.isChecked():
if self.PAUSE_KEY == False:
self.imu_start_record.stop()
elif self.PAUSE_KEY == True:
self.imu_start_record.start()
elif self.stableCheckBox.isChecked():
if self.PAUSE_KEY == False:
self.imu_start_record_stable.stop()
elif self.PAUSE_KEY == True:
self.imu_start_record_stable.start()
self.PAUSE_KEY = not self.PAUSE_KEY
def stop(self):
global raw_data
self.duringTime = time.time() - self.tt0
self.statusBrowser.append(u"停止紀錄!")
self.statusBrowser.append("During Time: " + "%.2f" %self.duringTime)
if not self.stableCheckBox.isChecked():
self.imu_start_record.stop()
self.save()
self.startButton.setEnabled(True)
self.stopButton.setEnabled(False)
self.saveButton.setEnabled(True)
self.statusBrowser.append(u"=檔案儲存完畢,清除 IMU 連線=")
i2c.write_byte_data(addr, 0x6A, 0x07)
elif self.stableCheckBox.isChecked():
self.imu_start_record_stable.stop()
self.startButton.setEnabled(True)
self.stopButton.setEnabled(False)
self.saveButton.setEnabled(False)
self.statusBrowser.append(u"=檔案儲存完畢,清除 IMU 連線=")
i2c.write_byte_data(addr, 0x6A, 0x07)
def save(self):
self.statusBrowser.append(u"檔案儲存中")
time.sleep(0.5)
self.save_record.start()
self.startButton.setEnabled(False)
self.stopButton.setEnabled(False)
self.saveButton.setEnabled(False)
def finished(self): # will be call when save_record was finished
self.statusBrowser.append(u"檔案已儲存,清空記憶體")
self.statusBrowser.append("===== End Section =====")
self.saveButton.setEnabled(False)
self.stopButton.setEnabled(False)
self.startButton.setEnabled(True)
# show stable checkbox option
def enable_stable(self):
check_stable = QMessageBox.question(self, u'啟動即時寫入', \
u"此選項將延遲每筆資料速度,並保證資料即時記錄於檔案中,確定嗎?\n 按'Yes'啟動即時檔案寫入,\n 按'NO'取消即時檔案寫入", \
QMessageBox.Yes | QMessageBox.No)
if check_stable == QMessageBox.Yes:
self.statusBrowser.append(u"*IMU即時寫入已啟動")
self.stableCheckBox.setCheckState(2)
self.saveButton.setEnabled(False)
else:
self.statusBrowser.append(u"*取消即時寫入")
self.stableCheckBox.setCheckState(0)
self.saveButton.setEnabled(True)
#===== Picamera Func. area =====
def preview(self):
camera.stop_preview()
if not self.preview_switch:
self.camBrowser.append("Preview on.")
camera.start_preview(fullscreen = False, window = (450, 10, 400, 300) )
self.preview_switch = True
elif self.preview_switch:
self.camBrowser.append("Preview off.")
self.camBrowser.append("==========")
camera.stop_preview()
self.preview_switch = False
else:
self.camBrowser.append("Prview Booom!")
def film(self):
#camera.stop_recording()
film_path = self.path
if not os.path.exists(film_path):
try:
os.makedirs(film_path)
except OSError:
if not os.path.isdir(film_path):
raise
if not self.film_switch:
self.camBrowser.append("Start Filming...")
self.video_count += 1
camera.start_recording(film_path + '/video%d.h264' %(self.video_count) )
self.film_switch = True
self.photoButton.setEnabled(False)
elif self.film_switch:
self.camBrowser.append("Stop Filming...")
camera.stop_recording()
self.camBrowser.append("Film saved.")
self.film_switch = False
self.camBrowser.append("==========")
self.photoButton.setEnabled(True)
else:
self.camBrowser.append("Film Booom!")
def take_photo(self):
self.photo_count += 1
self.filmButton.setEnabled(False)
self.photoButton.setEnabled(False)
# Create "Photo" folder if not exist
photo_path = self.path
if not os.path.exists(photo_path):
try:
os.makedirs(photo_path)
except OSError:
if not os.path.isdir(photo_path):
raise
camera.capture(photo_path + '/image%d.jpg' %self.photo_count )
self.camBrowser.append("image%d saved" %self.photo_count )
self.photoButton.setEnabled(True)
self.filmButton.setEnabled(True)
class imu_start_record(QThread):
def __init__(self, parent=None):
super(self.__class__, self).__init__(parent)
self.stoped = False
self.mutex = QMutex()
#===== QTimer =====
self.timer = QTimer()
self.timer.setInterval(10)
self.connect(self.timer, SIGNAL("timeout()"), self.mpu9250_data_get_and_write)
def run(self):
global raw_data
# varibles
self.t0 = time.time()
self.t_a_g = []
with QMutexLocker(self.mutex):
self.stoped = False
self.timer.start()
raw_data = list(self.t_a_g)
#print "data copy!"
def stop(self):
with QMutexLocker(self.mutex):
self.stoped = True
def isStop(self):
with QMutexLocker(self.mutex):
return self.stoped
def mpu9250_data_get_and_write(self):
# keep AKM pointer on continue measuring
i2c.write_byte_data(0x0c, 0x0a, 0x16)
# get MPU9250 smbus block data
#xyz_g_offset = i2c.read_i2c_block_data(addr, 0x13, 6)
xyz_a_out = i2c.read_i2c_block_data(addr, 0x3B, 6)
xyz_g_out = i2c.read_i2c_block_data(addr, 0x43, 6)
#xyz_a_offset = i2c.read_i2c_block_data(addr, 0x77, 6)
# get AK8963 smbus data (by pass-through way)
xyz_mag = i2c.read_i2c_block_data(0x0c, 0x03, 6)
#xyz_mag_adj = i2c.read_i2c_block_data(0x0c, 0x10, 3)
# get real time
t1 = time.time() - self.t0
# save file to list buffer
self.t_a_g.append(t1)
self.t_a_g.append(xyz_a_out)
self.t_a_g.append(xyz_g_out)
self.t_a_g.append(xyz_mag)
#self.t_a_g.append(xyz_mag_adj)
time.sleep(0.00001)
class imu_start_record_stable(QThread):
def __init__(self, parent=None):
super(self.__class__, self).__init__(parent)
self.stoped = False
self.mutex = QMutex()
self.t0 = time.time()
self.imu_count_stable = 0
self.countdown_sec = 60
#===== QTimer =====
self.big_timer = QTimer()
self.timer = QTimer()
#self.timer.setInterval(10)
self.connect(self.timer, SIGNAL("timeout()"), self.mpu9250_data_get_and_write)
def run(self):
self.timer.start(7)
self.big_timer.singleShot(self.countdown_sec *1000, self.stop)
with QMutexLocker(self.mutex):
self.stoped = False
def stop(self):
with QMutexLocker(self.mutex):
self.stoped = True
self.timer.stop()
print 'Done'
def isStop(self):
with QMutexLocker(self.mutex):