The MQ-2 smoke sensor came in the mail a couple days ago, so I finally got started on the main part of the programming - getting the smoke detector to trigger an event. This, naturally, turned out to be far more complicated than it should have been. I'll try to break this down in the order that the problems arose.
The output of the MQ-2 sensor is an analog pin, with the voltage increasing when smoke is in the air. Simple enough, except that the reading tends to float a bit depending on the air quality. This meant that if I set a hard threshold value, the sensor output could slowly climb until it triggered a false alarm. Alternatively, if the reading floated too low, actual smoke might not kick it up high enough to trigger the alarm. To solve this, I created an array of integers to hold the previous 50 readings and set a baseline value at the average of those values. This way the baseline would naturally update as the sensor readings floated, and I could detect rapid changes in the sensor by comparing to this baseline.
This seemed to be working alright, so I linked it up to the SMS program I found online
, which I had already tested. (I looked into using Twilio, but as I got started it seemed like it was overkill for what I was trying to do. I decided to use IFTTT instead since I already had their service hooked up to my phone.) When I merged the two programs, I had a very strange issue: After initializing the array of 50 readings and setting a baseline, the input from the sensor consistently gave a value of exactly 4073, well above the normal range. It worked perfectly while collecting those first 50 values, but after that it just... gave up. After about an hour of rereading the code, printing all sorts of values to the serial console, and commenting out other parts, I realized that the sensor worked fine until I connected to WiFi. After some googling, I found out that lots of analog pins on the ESP32 simply don't work once you're connected to WiFi. Once I moved it to a pin that wasn't affected by this problem, everything worked fine again. Until...
Occasionally, the sensor will spike for a single reading, for no reason. This meant that I would get a text every couple minutes about a false alarm, which wasn't going to fly. To solve this, I just made sure the alarm wouldn't trigger unless there were 3 consecutive high readings. And with that, it seems to be working perfectly, and I'm just waiting on the other parts to arrive in the mail. Here's the loop function after all the changes listed above: