-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwinddirection.ino
84 lines (72 loc) · 2.54 KB
/
winddirection.ino
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
/*
This Arduino sketch controls a personal weather station and use an ethernet shield to upload data to wunderground.com.
Details about the weather station can be found at http://www.avanux.de/space/Arduino/Wetterstation.
*/
//////////////
// Variables
//////////////
const long WIND_DIRECTION_AVG_INTERVAL_SECONDS = 120;
// voltage (mV) over wind vane every 22.5 degree according to wind vane vendor specification
const int windDirectionVoltageForDirection[] = {
3840, 1980, 2250, 410, 450, 320, 900, 620, 1400, 1190, 3080, 2930, 4620, 4040, 4330, 3430};
unsigned long windDirectionAvgValues;
unsigned long windDirectionAvgValueSum;
unsigned long windDirectionAvgIntervalBegin;
//////////////
// Set up
//////////////
void setupWindDirection()
{
}
//////////////
// Loop
//////////////
void loopWindDirection(unsigned long now)
{
int windDirectionRead = analogReadSmoothed(windDirectionPin);
int windDirectionVoltage = map(windDirectionRead, 0, 1023, 0, 5000);
#ifdef DEBUG_WS
Serial.print(F("wind direction: read="));
Serial.print(windDirectionRead);
Serial.print(F(" voltage="));
Serial.println(windDirectionVoltage);
#endif
windDirection = getWindDirection(windDirectionVoltage);
#ifdef INFO_WS
Serial.print(F("Wind direction="));
Serial.println(windDirection);
#endif
// calculate average
windDirectionAvgValues++;
windDirectionAvgValueSum += windDirection;
if(now - windDirectionAvgIntervalBegin > WIND_DIRECTION_AVG_INTERVAL_SECONDS * 1000 || windDirectionAvgIntervalBegin > now) {
windDirectionAvg = windDirectionAvgValueSum / windDirectionAvgValues;
#ifdef INFO_WS
Serial.print(F("Wind direction ("));
Serial.print(WIND_DIRECTION_AVG_INTERVAL_SECONDS);
Serial.print(F(" s): "));
Serial.println(windDirectionAvg);
#endif
windDirectionAvgIntervalBegin = now;
windDirectionAvgValues = 0;
windDirectionAvgValueSum = 0;
}
}
int getWindDirection(int measuredVoltage) {
int windDirectionIndex = -1;
// measuredVoltage will not exactly match sepcified voltages
// therefore we use an increasing range around each voltage value until we find a match
for(int range=10; range<1000; range+=10) {
for(int i=0; i<16; i++) {
int directionVoltage = windDirectionVoltageForDirection[i];
if(directionVoltage - range < measuredVoltage && measuredVoltage < directionVoltage + range) {
windDirectionIndex = i;
break;
}
}
if(windDirectionIndex > -1) {
break;
}
}
return windDirectionIndex * 22.5;
}