-
Notifications
You must be signed in to change notification settings - Fork 0
/
TekWeatherReader.ino
373 lines (312 loc) · 8.97 KB
/
TekWeatherReader.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
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
// Tekventure Weather Sensor Reader
// Arduino Mega w/ Arduino Ethernet Shield
// Reads Sparkfun weather sensor mast and BME280 sensor
// Includes
#include <SPI.h>
#include <Wire.h>
#include <Ethernet.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BME680.h>
#include <bme68x.h>
#include <bme68x_defs.h>
#include <arduino-timer.h>
#include <ArduinoHttpClient.h>
#include <SD.h>
#define SEALEVELPRESSURE_HPA (1023.03)
Adafruit_BME680 BME; // BME680 object
auto SecondTimer = timer_create_default(); // Timer objects
auto MinuteTimer = timer_create_default();
auto DayTimer = timer_create_default();
// Pins
const byte WSpeedPin = 3;
const byte WDirPin = A0;
const byte RainPin = 2;
const byte ResetPin = 4;
// Global Variables
int LastWindTime = 0;
int LastRainTime = 0;
int WindTick = 0;
int RainTick = 0;
int WindDirection = 0;
int LastWindDirection = 0;
long Second = 0;
long Minute = 0;
long LastWind = 0;
float RainMinute = 0.0;
float RainHour = 0.0;
float RainDay = 0.0;
int EthernetTryCount = 0;
float Humidity = 0.0; // Humidity in percent
float TempF = 0.0; // Temp in Farenheit
float TempC = 0.0; // Temp in Celsius
float Pressure = 0.0; // Temp in Pascals
float Dewpoint = 0.0; // Dewpoint in Farenheit
float WindSpeed = 0.0; // Wind speed MPH
float WindGust = 0.0;
float WindSpeedArray[60]; // Used to average values over a minute
float WindDirectionArray[60];
float TempArray[60];
// URL for WUnderground
char UploadURL[] = "weatherstation.wunderground.com";
// MAC address and IP for the Ethernet Shield, uses static IP on router
byte mac[] = {
0xAA, 0xBB, 0xCC, 0xDD, 0x23, 0x35
};
IPAddress ip(192, 168, 1, 23);
//EthernetServer server(80); // Ethernet objects
EthernetClient EClient;
HttpClient Client = HttpClient(EClient, UploadURL, 80); // HTTPclient library to avoid WUnderground errors
File LogFile;
void setup() {
Serial.begin(9600);
// Set up interrupt pins
pinMode(WSpeedPin, INPUT_PULLUP);
pinMode(RainPin, INPUT_PULLUP);
pinMode(ResetPin, OUTPUT);
// Start BME280
SPI.begin();
BMEStart();
// Interrupts
attachInterrupt(digitalPinToInterrupt(WSpeedPin), WindIRQ, FALLING);
attachInterrupt(digitalPinToInterrupt(RainPin), RainIRQ, FALLING);
// Initialize timers
SecondTimer.every(1000, SecondElapsed);
MinuteTimer.every(60000, MinuteElapsed);
DayTimer.every(86400000, DayElapsed);
// Setup windspeed array
for (int i=0; i<60; i++)
{
WindSpeedArray[i] = -1.0;
WindDirectionArray[i] = 0;
}
InitEthernet();
}
void loop() {
// Check ethernet status
if (Ethernet.linkStatus() == LinkOFF) {
// Ethernet fucked off again
InitEthernet();
} else {
// Keep DCHP alive
Ethernet.maintain();
// All we do in loop is tick the timers
SecondTimer.tick();
MinuteTimer.tick();
DayTimer.tick();
}
}
void InitEthernet() {
// Connect ethernet
delay(500);
EthernetTryCount++;
Ethernet.init(10);
// start the Ethernet connection
Ethernet.begin(mac);
}
void BMEStart() {
BME.begin();
BME.setTemperatureOversampling(BME680_OS_8X);
BME.setHumidityOversampling(BME680_OS_2X);
BME.setPressureOversampling(BME680_OS_4X);
BME.setIIRFilterSize(BME680_FILTER_SIZE_3);
}
void UpdateBME() {
// Polls BME sensor and sets values
if (! BME.performReading()) {
return;
// restart BME
BMEStart();
}
Humidity = BME.humidity;
Pressure = BME.pressure;
TempC = BME.temperature;
TempF = (TempC * 1.8) + 32; // Convert temp C to F
float DewPointC = 0;
if (TempC != 0 && Humidity != 0)
{
// Calculate dew point
float k;
k = log(Humidity / 100) + (17.62 * TempC) / (243 + TempC);
DewPointC = 243.12 * k / (17.62 - k);
Dewpoint = (DewPointC * 1.8) + 32;
}
}
void WindIRQ() {
// Interrupt from the wind sensor ticking over
if (millis() - LastWindTime > 30)
{
LastWindTime = millis();
WindTick++;
}
}
void RainIRQ() {
// Interrupt from rain bucket dumping
if (millis() - LastRainTime > 30)
{
LastRainTime = millis();
RainTick++;
RainMinute += 0.011;
RainHour += 0.011;
RainDay += 0.011;
}
}
float GetWindspeed() {
// Get current wind speed
float Delta = millis() - LastWind;
Delta /= 1000.0;
float CurrentWindSpeed = (float)WindTick / Delta;
WindTick = 0;
LastWind = millis();
CurrentWindSpeed *= 1.492;
return (CurrentWindSpeed);
}
int GetWindDirection() {
unsigned int adc;
adc = analogRead(WDirPin);
// Hacky shit found from trial and error
if (adc > 38 && adc < 42) return (90);
if (adc > 62 && adc < 70) return (135);
if (adc > 94 && adc < 100) return (180);
if (adc > 164 && adc < 170) return (45);
if (adc > 270 && adc < 275) return (225);
if (adc > 427 && adc < 430) return (0);
if (adc > 595 && adc < 599) return (315);
if (adc > 735 && adc < 742) return (270);
return LastWindDirection; // If all else fails send last second
}
bool SecondElapsed(void *) {
// Executed every second
// Update BME values
UpdateBME();
TempArray[Second] == TempC;
// Check if this second's wind speed is greater than the gust value
WindSpeedArray[Second] = GetWindspeed();
if (WindSpeedArray[Second] > WindGust) {
WindGust = WindSpeedArray[Second];
}
WindDirectionArray[Second] = GetWindDirection();
LastWindDirection = WindDirectionArray[Second];
// Increment seconds variable probably not needed anymore
Second++;
return true;
}
bool MinuteElapsed(void *) {
// Executes every 60 seconds
Minute++;
Second = 0;
// Check BME data for sameness
int SameData = 0;
// Average 60 seconds of wind events and directions
float WindSpeedTotal = 0;
float WindDirectionTotal = 0;
for (int i=0; i<60; i++)
{
WindSpeedTotal += WindSpeedArray[i];
WindDirectionTotal += WindDirectionArray[i];
if (TempArray[constrain(i, 0, 60)] == TempArray[i]) { SameData++; }
}
WindSpeed = WindSpeedTotal / 60;
if (WindSpeed < 0) { WindSpeed = 0; }
WindDirection = WindDirectionTotal / 60;
if (SameData > 20) {
// restart BME
BMEStart();
}
/* Serial.print("Windspeed ");
Serial.println(WindSpeed);
Serial.print("Wind Gust ");
Serial.println(WindGust);
Serial.print("WindDirection ");
Serial.println(WindDirection);
Serial.print("Rain Minute ");
Serial.println(RainMinute); */
// Every minute we call upload
UploadData();
// Reset gust value
WindGust = 0.0;
// Reset rain counts for each hour
if (Minute == 60) {
// One hour has passed
RainHour = 0.0;
Minute = 0;
}
return true;
}
bool DayElapsed(void *) {
// 24hr elapsed, clear rain accum
RainMinute = 0.0;
RainHour = 0.0;
RainDay = 0.0;
return true;
}
void UploadData() {
// Sends data to Weather Underground
// Convert pressure from Pa to InMG
float OutPressure = Pressure * 0.00029530;
LogFile = SD.open("log.txt", FILE_WRITE);
// Build up GET request
String Request = "/weatherstation/updateweatherstation.php?ID=KINFORTW318&PASSWORD=Tfw37q2V&dateutc=now"
+ String("&winddir=") + String(WindDirection)
+ String("&windspeedmph=") + String(WindSpeed)
+ String("&windgustmph=") + String(WindGust)
+ String("&rainin=") + String(RainHour)
+ String("&dailyrainin=") + String(RainDay)
+ String("&baromin=") + String(OutPressure)
+ String("&humidity=") + String(Humidity)
+ String("&tempf=") + String(TempF)
+ String("&dewptf=") + String(Dewpoint)
+ String("&action=updateraw");
Serial.println(Request);
if (LogFile) {
String LogData = millis() + " - " + Request;
LogFile.println(LogData);
}
// Send request
Client.beginRequest();
Client.get(Request);
Client.endRequest();
// read the status code and body of the response
int statusCode = Client.responseStatusCode();
String response = Client.responseBody();
Serial.print("Status code: ");
Serial.println(statusCode);
Serial.print("Response: ");
Serial.println(response);
if (LogFile) {
String LogData = millis() + " - Status Code: " + (String)statusCode + " - Response: " + (String)response;
LogFile.println(LogData);
LogFile.close();
}
// Client.close();
}
/* void listenForEthernetClients() {
// listen for incoming clients
EthernetClient client = server.available();
if (client) {
Serial.println("Got a client");
// an http request ends with a blank line
bool currentLineIsBlank = true;
while (client.connected()) {
if (client.available()) {
char c = client.read();
if (c == '\n' && currentLineIsBlank) {
// send a standard http response header
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println();
client.print("<h1>FNORD</h1>");
break;
}
if (c == '\n') {
currentLineIsBlank = true;
} else if (c != '\r') {
currentLineIsBlank = false;
}
}
}
// give the web browser time to receive the data
delay(1);
// close the connection:
client.stop();
}
} */