 # ESP-Now Remote Sensor 1 Example

Sep 6th, 2019
864
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1. #include <ESP8266WiFi.h>
2. #include <Wire.h>
3.
4. extern "C" {
5. #include <espnow.h>
6. }
7.
8. //Thermistor related:
9.
10. /* Here we have a few constants that make editing the code easier. I will go
11.    through them one by one.
12.
13.    A reading from the ADC might give one value at one sample and then a little
14.    different the next time around. To eliminate noisy readings, we can sample
15.    the ADC pin a few times and then average the samples to get something more
16.    solid. This constant is utilized in the readThermistor function.
17.    */
18. const int    SAMPLE_NUMBER      = 10;
19.
20. /* In order to use the Beta equation, we must know our other resistor
21.    within our resistor divider. If you are using something with large tolerance,
22.    like at 5% or even 1%, measure it and place your result here in ohms. */
23. const double BALANCE_RESISTOR   = 9970.0;
24.
25. // This helps calculate the thermistor's resistance (check article for details).
26. const double MAX_ADC            = 1023.0;
27.
28. /* This is thermistor dependent and it should be in the datasheet, or refer to the
29.    article for how to calculate it using the Beta equation.
30.    I had to do this, but I would try to get a thermistor with a known
31.    beta if you want to avoid empirical calculations. */
32. const double BETA               = 3950.0;
33.
34. /* This is also needed for the conversion equation as "typical" room temperature
35.    is needed as an input. */
36. const double ROOM_TEMP          = 298.15;   // room temperature in Kelvin
37.
38. /* Thermistors will have a typical resistance at room temperature so write this
39.    down here. Again, needed for conversion equations. */
40. const double RESISTOR_ROOM_TEMP = 10000.0;
41.
42. //===============================================================================
43. //  Variables
44. //===============================================================================
45. // Here is where we will save the current temperature
46. double currentTemperature = 0;
47.
48. //===============================================================================
49. //  Pin Declarations
50. //===============================================================================
51. //Inputs:
52. int thermistorPin = 0;  // Where the ADC samples the resistor divider's output
53.
54. // this is the MAC Address of the remote ESP server which receives these sensor readings
55. uint8_t remoteMac[] = {0x86, 0xF3, 0xEB, 0X62, 0x71, 0xEC};
56.
57. #define WIFI_CHANNEL 1
58. #define SLEEP_SECS 5  // 15 minutes
59. #define SLEEP_TIME 36e8 //6e7 // has to be number of seconds * 1000 * 1000 i.e. 10s is 10 * 1000 * 1000 = 10000000 or 1e7 ( 1 + 7 zeros) for testing 1e7, 6e7 = 60s & 36e8 is 1 hour
60. #define SEND_TIMEOUT 245  // 245 millis seconds timeout
61.
62. unsigned long entry;
63.
64. // keep in sync with ESP_NOW sensor struct
65. struct SensorData {
66.     String id; //Sensor Name
67.     int fieldT; // ThingSpeak Field Temperature
68.     int fieldH; // ThingSpeak Field Humidity
69.     float temp; // Temperature Variable
70.     int hum; // Humidity Variable
71. } sD;
72.
73. volatile boolean callbackCalled;
74.
75. unsigned long entry1 = millis();
76.
77. void setup() {
78.   Serial.begin(115200);
79.   sensor.begin();
80.   Serial.println();
81.   Serial.println();
82.   Serial.println("ESP_Now Controller");
83.   Serial.println();
84.   WiFi.mode(WIFI_STA);
85.   WiFi.disconnect();
86.
87.   Serial.printf("This mac: %s, ", WiFi.macAddress().c_str());
88.   Serial.printf("target mac: ");
89.   char macString = {0};
90.     sprintf(macString,"%02X:%02X:%02X:%02X:%02X:%02X", remoteMac, remoteMac, remoteMac, remoteMac, remoteMac, remoteMac);
91.     Serial.print(macString);
92.   Serial.printf(", on channel: %i\n", WIFI_CHANNEL);
93.
94.
95.   if (esp_now_init() != 0) {
96.     Serial.println("*** ESP_Now init failed");
97.     gotoSleep();
98.   }
99.   esp_now_set_self_role(ESP_NOW_ROLE_CONTROLLER);
100.
101.   unsigned long entry2 = millis();
102.   esp_now_add_peer(remoteMac, ESP_NOW_ROLE_SLAVE, WIFI_CHANNEL, NULL, 0);
103.
104.   unsigned long entry3 = millis();
105.
106.   esp_now_register_send_cb([](uint8_t* mac, uint8_t sendStatus) {
107.     Serial.println();
108.     Serial.printf("send_cb, send done, status = %i\n", sendStatus);
109.     callbackCalled = true;
110.   });
111.
112.   unsigned long entry4 = millis();
113.
114.   callbackCalled = false;
115.
116. }
117.
118. void loop() {
120.   sD.id = "H";
121.   sD.fieldT = 4;
122.   sD.temp = currentTemperature;
123.   u8 bs[sizeof(sD)];
124.   memcpy(bs, &sD, sizeof(sD));
125.   unsigned long entry = millis();
126.   esp_now_send(NULL, bs, sizeof(sD)); // NULL means send to all peers
127.
128.   Serial.print("Overall Time: ");
129.   Serial.println(millis() - entry1);
130.   Serial.print(sD.id); Serial.printf(" Temp = %0.2f", sD.temp); Serial.print("\u2103");
131.   ESP.deepSleep(SLEEP_TIME, WAKE_RF_DEFAULT);
132.   ESP.restart();
133. }
134.
135. void gotoSleep() {
136.   // add some randomness to avoid collisions with multiple devices
137.   int sleepSecs = SLEEP_SECS;// + ((uint8_t)RANDOM_REG32/2);
138.   Serial.printf("Up for %i ms, going to sleep for %i secs...\n", millis(), sleepSecs);
139.   ESP.deepSleep(sleepSecs * 1000000, RF_NO_CAL);
140. }
141.
143. {
144.   // variables that live in this function
145.   double rThermistor = 0;            // Holds thermistor resistance value
146.   double tKelvin     = 0;            // Holds calculated temperature
147.   double tCelsius    = 0;            // Hold temperature in celsius
148.   double adcAverage  = 0;            // Holds the average voltage measurement
149.   int    adcSamples[SAMPLE_NUMBER];  // Array to hold each voltage measurement
150.
151.   /* Calculate thermistor's average resistance:
152.      As mentioned in the top of the code, we will sample the ADC pin a few times
153.      to get a bunch of samples. A slight delay is added to properly have the
154.      analogRead function sample properly */
155.
156.   for (int i = 0; i < SAMPLE_NUMBER; i++)
157.   {
159.     delay(1);        // wait 10 milliseconds
160.   }
161.
162.   /* Then, we will simply average all of those samples up for a "stiffer"
163.      measurement. */
164.   for (int i = 0; i < SAMPLE_NUMBER; i++)
165.   {
167.   }
168.   adcAverage /= SAMPLE_NUMBER;        // . . . average it w/ divide
169.
170.   /* Here we calculate the thermistor’s resistance using the equation
171.      discussed in the article. */
173.
174.   /* Here is where the Beta equation is used, but it is different
175.      from what the article describes. Don't worry! It has been rearranged
176.      algebraically to give a "better" looking formula. I encourage you
177.      to try to manipulate the equation from the article yourself to get
178.      better at algebra. And if not, just use what is shown here and take it
179.      for granted or input the formula directly from the article, exactly
180.      as it is shown. Either way will work! */
181.   tKelvin = (BETA * ROOM_TEMP) /
182.             (BETA + (ROOM_TEMP * log(rThermistor / RESISTOR_ROOM_TEMP)));
183.
184.   /* I will use the units of Celsius to indicate temperature. I did this
185.      just so I can see the typical room temperature, which is 25 degrees
186.      Celsius, when I first try the program out. I prefer Fahrenheit, but
187.      I leave it up to you to either change this function, or create
188.      another function which converts between the two units. */
189.   tCelsius = tKelvin - 273.15;  // convert kelvin to celsius
190.
191.   tCelsius = round(tCelsius*10)/10.0;
192.
193.   return tCelsius;    // Return the temperature in Celsius
194. }