-
Notifications
You must be signed in to change notification settings - Fork 0
/
compass_test.py
106 lines (78 loc) · 2.16 KB
/
compass_test.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
import smbus
import time
last_movement = 100
move_counter = 0
bus = smbus.SMBus(1)
# MAG3110 I2C address 0x0E
# Select Control register, 0x10(16)
bus.write_byte_data(0x0E, 0x10, 0x01)
time.sleep(0.5)
# MAG3110 I2C address 0x0E
# Read data back from 0x01(1), 6 bytes
data = bus.read_i2c_block_data(0x0E, 0x01, 6)
# Convert the data
xMag = data[0] * 256 + data[1]
if xMag > 32767:
xMag -= 65536
yMag = data[2] * 256 + data[3]
if yMag > 32767:
yMag -= 65536
zMag = data[4] * 256 + data[5]
if zMag > 32767:
zMag -= 65536
# Output data
print("X-Axis : %d" % xMag)
print("Y-Axis : %d" % yMag)
print("Z-Axis : %d" % zMag)
def compass_init():
global bus
print('Compass Init')
bus = smbus.SMBus(1)
# MAG3110 I2C address 0x0E
# Select Control register, 0x10(16)
bus.write_byte_data(0x0E, 0x10, 0x01)
time.sleep(0.5)
def get_compass():
# MAG3110 I2C address 0x0E
# Read data back from 0x01(1), 6 bytes
data = bus.read_i2c_block_data(0x0E, 0x01, 6)
# Convert the data
xMag = data[0] * 256 + data[1]
if xMag > 32767:
xMag -= 65536
yMag = data[2] * 256 + data[3]
if yMag > 32767:
yMag -= 65536
zMag = data[4] * 256 + data[5]
if zMag > 32767:
zMag -= 65536
# Output data
print('----------------------------')
movement = (xMag + yMag + zMag)
if movement == 0:
compass_init()
get_compass()
return movement
def is_moving(movement):
global last_movement
global move_counter
variance = 100
max_count = 100
if (movement > (last_movement + variance)) or (movement < (last_movement - variance)):
# print('Movement Detected')
move_counter = 0
else:
move_counter = move_counter + 1
# print('No Movement - Count = ' + str(move_counter))
last_movement = movement
if move_counter >= max_count:
return 'POWER SAVE ON'
else:
return 'POWER SAVE OFF - Standby Count = ' + str(move_counter)
while True:
time.sleep(1)
try:
print(get_compass())
print(is_moving(get_compass()))
except:
print('Compass Error - If persists power compass off and on & reboot script')