-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.ino
107 lines (87 loc) · 2.43 KB
/
server.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
#include <SPI.h>
#include <LoRa.h>
#include <ArduinoJson.h>
#define NSS 4
#define RST 5
#define DI0 2
#define Fan 12
// Create a JSON document to hold the incoming data
DynamicJsonDocument doc(2048);
// Create variables to store sensor data
String LoRaData;
float h, tc, tf;
// Function prototypes
void initializeLora();
void readPacket();
void deserializePacket(String jsonPacket);
void processPacket();
// =========================================================
void setup() {
Serial.begin(115200);
pinMode(Fan, OUTPUT);
// Initialize LoRa communication
setupLora();
}
// =========================================================
void loop() {
// Read and process LoRa packets
readPacket();
processPacket();
delay(50);
}
// =========================================================
// Initialize LoRa communication
void setupLora(){
Serial.println("LoRa Sender");
LoRa.setPins(NSS, RST, DI0);
while (!LoRa.begin(433E6)) {
Serial.print(".");
delay(500);
}
LoRa.setSyncWord(0xF1);
Serial.println("LoRa Initializing Successful!");
}
// =========================================================
// Read LoRa packet
void readPacket(){
int packetSize = LoRa.parsePacket();
if (packetSize) {
Serial.print("Received packet: ");
while (LoRa.available())
LoRaData = LoRa.readString();
Serial.println(LoRaData);
deserializePacket(LoRaData);
}
}
// =========================================================
// Deserialize JSON packet
void deserializePacket(String jsonPacket){
// Deserialize the JSON document
DeserializationError error = deserializeJson(doc, jsonPacket);
// Test if parsing succeeds.
if (error) {
Serial.print(F("deserializeJson() failed: "));
Serial.println(error.f_str());
return;
}
// Extract sensor data from JSON
h = doc["Humidity"];
tc = doc["Temperature_C"];
tf = doc["Temperature_F"];
Serial.print("Humidity: ");
Serial.println(h);
Serial.print("Temperature_C: ");
Serial.println(tc);
Serial.print("Temperature_F: ");
Serial.println(tf);
}
// =========================================================
// Process the sensor data and control the fan
void processPacket(){
// packet process
if(h > 30 && tc >32)
digitalWrite(Fan, HIGH); // Turn on the fan
else
digitalWrite(Fan, LOW); // Turn off the fan
delay(5);
}