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
|
from gpiozero import MCP3008
import time
import math
adc = MCP3008(channel=0)
count = 0
"""
volts key pairs created with the below + known values from datasheet
# create voltage divider for use with MCP3008 ADC
def volt_div(r1, r2, vIn):
vOut = (vIn * r2)/(r1 + r2)
return round(vOut,3)
# calculate vOut values for each wind direction using known resistances from datasheet, 3.3 V from RPi and 4.7K ohm resistor
resistances = [33000, 6570, 8200, 891, 1000, 688, 2200, 1410, 390, 3140, 16000, 14120, 120000, 42120, 64900, 21880]
for i in range(len(resistances)):
print(resistances[i],volt_div(4700, resistances[i], 3.3))
4.7K resistor
volts = {0.4: "0.0 N",
1.4: "22.5 NNE",
1.2: "45.0 NE",
2.8: "67.5 ENE",
2.7: "90.0 E",
2.9: "112.5 ESE",
2.2: "135.0 SE",
2.5: "157.5 SSE",
1.8: "180.0 S",
2.0: "202.5 SSW",
0.7: "225.0 SW",
0.8: "247.5 WSW",
0.1: "270.0 W",
0.3: "292.5 WNW",
0.2: "315.0 NW",
0.6: "337.5 NNW"}
"""
# 5K resistor
volts = {1.87: 0.0,
2.04: 22.5,
0.79: 45.0,
0.80: 45.0,
0.88: 67.5,
0.13: 90.0,
0.36: 112.5,
0.24: 135.0,
0.62: 157.5,
0.44: 180.0,
1.44: 202.5,
1.27: 225.0,
2.81: 247.5,
2.76: 270.0,
2.91: 292.5,
2.31: 315.0,
2.59: 337.5}
def getAverage(angles):
sinSum = 0.0
cosSum = 0.0
for angle in angles:
r = math.radians(angle)
sinSum += math.sin(r)
cosSum += math.cos(r)
flen = float(len(angles))
s = sinSum / flen
c = cosSum / flen
arc = math.degrees(math.atan(s / c))
average = 0.0
if s > 0 and c > 0:
average = arc
elif c <0:
average = arc + 180
elif s < 0 and c > 0:
average = arc + 360
return 0.0 if average == 360 else average
def getValue(length=5):
data = []
startTime = time.time()
while time.time() - startTime <= length:
wind = round(adc.value*3.3,2)
if not wind in volts: # keep only good measurements
print("Unknown value: " + str(wind))
else:
data.append(volts[wind])
return getAverage(data)
getValue()
|