· 6 years ago · Jan 28, 2020, 06:12 PM
1
2
3#include <SoftwareSerial.h>
4
5#define RX 2
6#define TX 3
7String AP = "invalid"; // AP NAME
8String PASS = "029144653Ss@$#"; // AP PASSWORD
9String API = "BVCIS8QBD2XSWGGQ"; // Write API KEY
10String HOST = "api.thingspeak.com";
11String PORT = "80";
12String field = "field3";
13int countTrueCommand;
14int countTimeCommand;
15boolean found = false;
16float valSensor = 1;
17int measurePin = A0;
18int ledPower = 12;
19
20int samplingTime = 280;
21int deltaTime = 40;
22int sleepTime = 9680;
23
24float voMeasured = 0;
25float calcVoltage = 0;
26float dustDensity = 0;
27SoftwareSerial esp8266(RX, TX);
28
29
30void setup() {
31 Serial.begin(9600);
32 pinMode(ledPower, OUTPUT);
33 esp8266.begin(115200);
34 sendCommand("AT", 5, "OK");
35 sendCommand("AT+CWMODE=1", 5, "OK");
36 sendCommand("AT+CWJAP=\"" + AP + "\",\"" + PASS + "\"", 20, "OK");
37}
38
39void loop() {
40 valSensor = getSensorData();
41
42
43 String getData = "GET /update?api_key=" + API + "&" + field + "=" + String(valSensor);
44 sendCommand("AT+CIPMUX=1", 5, "OK");
45 sendCommand("AT+CIPSTART=0,\"TCP\",\"" + HOST + "\"," + PORT, 15, "OK");
46 sendCommand("AT+CIPSEND=0," + String(getData.length() + 4), 4, ">");
47 esp8266.println(getData); delay(1500); countTrueCommand++;
48 sendCommand("AT+CIPCLOSE=0", 5, "OK");
49 delay(60000);
50}
51
52
53
54float getSensorData() {
55
56 digitalWrite(ledPower, LOW); // power on the LED
57 delayMicroseconds(samplingTime);
58
59 voMeasured = analogRead(measurePin); // read the dust value
60
61 delayMicroseconds(deltaTime);
62
63 digitalWrite(ledPower, HIGH); // turn the LED off
64 delayMicroseconds(sleepTime);
65
66
67 calcVoltage = voMeasured * (5.0 / 1024);
68
69 dustDensity = 0.17 * calcVoltage - 0.1;
70 dustDensity *= 1000;
71 Serial.print("Raw Signal Value (0-1023): ");
72 Serial.print(voMeasured);
73
74 Serial.print(" - Voltage: ");
75 Serial.print(calcVoltage);
76
77 Serial.print(" - Dust Density: ");
78 Serial.println(dustDensity);
79 return dustDensity;
80}
81
82
83
84
85void sendCommand(String command, int maxTime, char readReplay[]) {
86 Serial.print(countTrueCommand);
87 Serial.print(". at command => ");
88 Serial.print(command);
89 Serial.print(" ");
90 while (countTimeCommand < (maxTime * 1))
91 {
92 esp8266.println(command);//at+cipsend
93 if (esp8266.find(readReplay)) //ok
94 {
95 found = true;
96 break;
97 }
98
99 countTimeCommand++;
100 }
101
102 if (found == true)
103 {
104 Serial.println("OYI");
105 countTrueCommand++;
106 countTimeCommand = 0;
107 }
108
109 if (found == false)
110 {
111 Serial.println("Fail");
112 countTrueCommand = 0;
113 countTimeCommand = 0;
114 }
115
116 found = false;
117}