ESP32 Freezes After 12 Hours - arduino

Good afternoon, I want to make a continuously operable gateway that measures temperature with esp32.
The device sends data via MQTT every 1.5 seconds.
Esp freezes after 12 - 24 hours.
I read that some users operate the device every 6-7 months without resetting, how can I operate the device for a long time without resetting it?
Note1: As a workaround in the code I reset the device with MQTT, Ethernet and ESP.restart () every 12 hours before it can freeze.
Note2: LEDs indicate that the system is working.
Red lights when ethernet or MQTT cannot be connected.
Blue indicates trying to connect to MQTT or ethernet.
Green indicates that the system is active. When the device was frozen, the green led was still on.
Versions of libraries I use:
Arduino IDE == 1.8.14
ESP Library Version == 1.0.6
MQTT Library Version == 2.5.0
ESP Library Version == 2.0.9
ESP Link: https://www.direnc.net/esp32-wroom-32u-wifi-bluetooth-gelistirme-modulu-en
The code:
#include <UIPEthernet.h>
#include <ArduinoJson.h>
#include <MQTT.h>
#include <DHT.h>
//////////////////////// ETHERNET CONFİG //////////////////////////
byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
//////////////////////// ETHERNET CONFİG //////////////////////////
//////////////////////// LED & DHT22 CONFİG //////////////////////////
byte red = 2;
byte green = 0;
byte blue = 4;
byte temp = 15;
#define DHTTYPE DHT22
DHT dht = DHT(temp, DHTTYPE);
//////////////////////// LED & DHT22 CONFİG //////////////////////////
//////////////////////// MQTT CONFİG //////////////////////////
#define mqttServer IPAddress(xxx,xxx,xx,xxx)
const char* mqttUser = "test";
const char* mqttPassword = "test";
const char* deviceId = "Ai-Sens 1";
//////////////////////// MQTT CONFİG //////////////////////////
unsigned long lastMillis = 0;
byte x;
byte y;
EthernetClient net;
MQTTClient client;
//Receives an external reset command every 12 hours
void callback(String &topic, String &payload) {
if (payload == "1")
{
ESP.restart(); // This is just a workaround to avoid the freezing issue
}
}
void setup_eth() {
delay(10);
digitalWrite(blue, HIGH); // turn the LED on
//Serial.print("connecting ethernet...");
if (Ethernet.begin(mac) == 0) {
// Serial.println("Failed to configure Ethernet using DHCP");
for (;;)
;
}
Ethernet.begin(mac, Ethernet.localIP());
digitalWrite(blue, LOW);
}
void connect() {
//Serial.print("connecting mqtt...");
digitalWrite(blue, HIGH);
while (!client.connected()) {
if (client.connect(deviceId, mqttUser, mqttPassword)) {
// Subscribe
//client.subscribe("esp/data1");
} else {
delay(500);
}
}
//Serial.println("\nconnected!");
digitalWrite(blue, LOW);
//client.subscribe("esp/data1");
}
void setup() {
//Serial.begin(115200);
pinMode(red, OUTPUT);
pinMode(green, OUTPUT);
pinMode(blue, OUTPUT);
digitalWrite(red, LOW);
digitalWrite(green, LOW);
digitalWrite(blue, LOW);
dht.begin();
setup_eth();
client.setHost(mqttServer, 1883);
client.setKeepAlive(90);
client.begin(mqttServer, net);
connect();
}
void loop() {
client.loop();
delay(10);
client.subscribe("esp/rst");
client.onMessage(callback);
StaticJsonBuffer<300> JSON;
JsonObject& JSONencoder = JSON.createObject();
if (millis() - lastMillis > 1500) {
digitalWrite(green, LOW);
digitalWrite(blue, LOW);
digitalWrite(red, LOW);
if (!client.connected()) {
digitalWrite(red, HIGH);
if (y == 5) {
//Serial.println("Reboot System Now....");
ESP.restart();
y = 0;
}
y++;
connect();
}
if (Ethernet.linkStatus() == LinkON) {
// Serial.println("On");
digitalWrite(green, HIGH);
}
else {
digitalWrite(red, HIGH);
if (x == 5) {
//Serial.println("Reboot System Now....");
ESP.restart();
x = 0;
}
x++;
}
lastMillis = millis();
//Serial.println(Ethernet.maintain ());
JSONencoder["DEVICE = "] = deviceId;
JSONencoder["USER = "] = mqttUser;
JSONencoder["TEMP = "] = dht.readTemperature();
JSONencoder["HUMD = "] = dht.readHumidity();
JSONencoder["STATE = "] = true;
char JSONmessageBuffer[100];
JSONencoder.printTo(JSONmessageBuffer, sizeof(JSONmessageBuffer));
client.publish("esp/data1", JSONmessageBuffer);
}
}

It would be helpful to have the output of device from the moment it reboots - this might describe what caused it.
Without that, the best guess is that you're depleting the RAM. To check for this, you should periodically print out the available heap space (the FreeRTOS function to do it is xPortGetFreeHeapSize()).
I notice that with each iteration of loop() you do things which should be done only once - the calls to subscribe() and onMessage() are very likely not needed every time you want to publish data, and they likely allocate new heap memory to store the relevant context.

My bet is that you are restarting the device too much. You need to implement different failure modes and different fail-safes than restarting the device on each issue. Likely the device is in a funny state while restart is triggered and then using the device after restart might not behave the way the drivers expect from the device and get stuck.
And I would also remove the comments with the printf and replace it with a #ifdef
then having #define VERBOSE_DEBUG_PRINT so you can enable/disable the debugging quickly.
Another thing I would do is add to the loop this:
Serial.println(ESP.getFreeHeap());
If this is changing between the iterations of the loop, then that is not a good sign and something might be leftover.
I would go over the MQTT library documentation and examples as you might be abusing the library and calling things more frequently or in unexpected places as it was intended. And there might be side effect that I might work most of the times but once in a while either leak a bit of a heap, or get stuck.
You are asking about other projects being able to run without crashes, then look at them and how they are using the MQTT. My guess is that they do not restart device in so many branches and do calls like subscribe in a specific place (like inside the connect, but not inside the main loop). Likely you might be subscribing too much and leaking the memory.
Is 500ms delay for reconection good enough, doesn't it leave the device sometimes in a funny state, it might have be a race condition which happens only sometimes, would increase existing delays by 4x (like 500 to 2000) and add new delays in some places just in case the device expects sometime after the command, and was not expecting to be used in such way like its here (stuff in the loop etc...)

Related

How can I create an automated GPS tracker using A9G AI Thinker module?

I have an AI Thinker A9G module connected to an ESP8266 D1 mini. I have the following script to send and receive AT commands to/from the module. The idea is to get a SMS with the Google maps GPS location of the module onto my mobile phone.
// GPS tracker with AI Thinker A9G module and AZ Delivery D1 Mini ESP8266 module
#include <SoftwareSerial.h>
#define rxPin D7
#define txPin D8
SoftwareSerial A9modem(rxPin, txPin); // Pins D7 Rx and D8 Tx are used as used as software serial pins
String incomingData; // For storing incoming serial data
String gpsData; // For storing location data
char msg;
char call;
void setup()
{
Serial.begin(115200); // Baud rate for serial monitor
A9modem.begin(115200); // Baud rate for GSM shield
Serial.println("GPS/GSM A9G BEGIN");
Serial.println("Enter character for control option: ");
Serial.println("h : to disconnect a call");
Serial.println("s : to send a message");
Serial.println("r : to receive a message");
Serial.println("c : to make a call");
Serial.println("l : to read location");
Serial.println("d : to disconnect gps");
Serial.println();
delay(100);
// Set SMS mode to text mode
A9modem.print("AT+CMGF=1\r");
delay(100);
// Set GSM module to TP show the output on serial out
A9modem.print("AT+CNMI=2,2,0,0,0\r");
delay(100);
}
void loop()
{
ReceiveMessage();
gpsData = incomingData.substring(33, 52);
Serial.print("Location: ");
Serial.println(gpsData);
delay(2000);
if (Serial.available() > 0)
switch(Serial.read())
{
case 's':
SendMessage();
break;
case 'r':
ReceiveMessage();
break;
case 'c':
MakeCall();
break;
case 'h':
HangupCall();
break;
case 'l':
ReadLocation();
break;
case 'd':
DisconnectGps();
break;
}
}
void ReceiveMessage()
{
if (A9modem.available() > 0)
{
incomingData = A9modem.readString(); // Get the data from the serial port
Serial.print(incomingData);
delay(100);
}
}
void SendMessage()
{
A9modem.println("AT+CMGF=1"); // Sets the GSM Module into text mode
delay(1000); // Delay of one second
A9modem.println("AT+CMGS=\"xxxxxxxxxxxxx\"\r"); // Replace your mobile number here
delay(1000);
String sms = "http://maps.google.com/maps?q=" + gpsData; // Create the SMS location string
A9modem.println(sms);
delay(100);
A9modem.println((char)26); // ASCII code of CTRL+Z
delay(1000);
}
void MakeCall()
{
A9modem.println("ATD+xxxxxxxxxxxxx;"); // Replace your mobile number here
Serial.println("Calling "); // Print response over serial port
delay(1000);
}
void HangupCall()
{
A9modem.println("ATH");
Serial.println("Hangup Call");
delay(1000);
}
void DisconnectGps()
{
A9modem.println("AT+GPS=0");
Serial.println("Disconnect GPS");
delay(1000);
}
void ReadLocation()
{
A9modem.println("AT+GPS=1");
delay(1000);
A9modem.println("AT+LOCATION=2"); // Check location every two seconds
delay(2000);
}
So if I use the commands "l" and "s" in Arduino IDE serial monitor everything is working well but I don't know how to change the code in a way that I get a fully automated GPS tracker. The idea is the following: Power on starts the tracker. When gpsData string is not empty the first SMS will be send to my mobile phone. The next SMS follows 20 minutes later and so on until power is switched off. Could you help please?
Thanks in advance!
Finally I came up with this solution but I'm not very happy with it (it is working but I have to restart the module from time to time because there are no GPS data). There are 3 reasons for this: There is no error handling for the GPS function, I set the delays in a more ore less random way to get everything working but I don't know if the values make sense and I don't know if the substring() function is the best way to get the location from the serial response.
// GPS tracker with AI Thinker A9G module and AZ Delivery D1 Mini
ESP8266 module
#include <SoftwareSerial.h>
#define rxPin D7
#define txPin D8
SoftwareSerial A9modem(rxPin, txPin); // Pins D7 Rx and D8 Tx are used as used as software serial pins
String incomingData; // For storing incoming serial data
String gpsData; // For storing location data
int runGps = 1;
int sendSms = 0;
void setup()
{
pinMode(LED_BUILTIN, OUTPUT); // Use builtin LED for correct GPS status
Serial.begin(115200); // Baud rate for serial monitor
A9modem.begin(115200); // Baud rate for GSM shield
// Set SMS mode to text mode
A9modem.print("AT+CMGF=1\r");
delay(300);
// Set GSM module to TP show the output on serial out
A9modem.print("AT+CNMI=2,2,0,0,0\r");
delay(1000);
Serial.end();
delay(500);
}
void loop()
{
Serial.begin(115200);
ReceiveMessage(); // Start a new serial stream
gpsData = incomingData.substring(33, 52); // Strip all unnessesary data from the stream
Serial.print("Location: "); // Check if the location data are correct
Serial.println(gpsData);
delay(1000);
if(runGps == 1) { // Start GPS
ReadLocation();
delay(20000); // Wait for GPS to be ready
}
if(gpsData.length() == 19 && sendSms == 0) { // If the location string is correct send SMS
if (isdigit(gpsData.charAt(0))) { // Check if the stream starts with a number
SendMessage();
digitalWrite(LED_BUILTIN, HIGH);
delay(300);
digitalWrite(LED_BUILTIN, LOW);
delay(300);
digitalWrite(LED_BUILTIN, HIGH);
delay(300);
digitalWrite(LED_BUILTIN, LOW);
delay(300);
digitalWrite(LED_BUILTIN, HIGH);
}
}
if(runGps == 0 && sendSms == 1) {
runGps = 1;
sendSms = 0;
delay(6000); // Make sure that all SMS serial communication is over
while (A9modem.available()) {
A9modem.read(); // Delete all data from serial buffer
}
delay(300000); // If SMS was sent wait 5 minutes before running the main loop again
Serial.end();
delay(500);
}
}
void ReceiveMessage()
{
if (A9modem.available() > 0)
{
incomingData = A9modem.readString(); // Get the data from the serial port
Serial.print(incomingData);
delay(500);
}
}
void SendMessage()
{
sendSms = 1; // Stop starting the SendMessage function
A9modem.println("AT+CMGF=1"); // Sets the GSM Module into text mode
delay(1000);
A9modem.println("AT+CMGS=\"xxxxxxxxxx\"\r"); // Replace your mobile number here
delay(1000);
String sms = "http://maps.google.com/maps?q=" + gpsData; // Create the SMS string
A9modem.println(sms);
delay(500);
A9modem.println((char)26); // ASCII code of CTRL+Z
delay(500);
}
void ReadLocation()
{
runGps = 0; // Stop starting the ReadLocation function
A9modem.println("AT+GPS=1");
delay(1000);
A9modem.println("AT+LOCATION=2"); // Check location every two seconds
delay(2000);
}
Try turning ON the NMEA stream from the A9G. Say you want to get the NMEA data every t seconds, you can add and then call the following function once in the void setup()
void TurnOnNMEA(int t)
{
if(t > 3600)
t = 3600; // Because the max time is 3600s
A9modem.print("AT+GPSRD=");
A9modem.println(t);
while(!A9modem.available()); // wait till the A9G sends a response
char c;
while(A9modem.available())
{
c = A9modem.read();
Serial.print(c);
delay(2); // Time needed for the next character
}
}
This will start the NMEA data stream every t seconds which you can print using the following function,
void ReadNMEA()
{
char c; // Read each character from the stream as it comes
if(A9modem.available())
{
c = A9modem.read();
Serial.print(c);
delay(2); // Time needed for the next character
}
}
Parsing and decoding the NMEA is a bit tricky thing to do. There is a lot of information inside it and the decoding depends on what you want to do with it. If you just want the location, you can parse the $GNGGA line.
When parsing the data, DO NOT USE Arduino String() class. It is a very bad idea when handling this kind of stream. Instead, use char array.

Arduino IRremote Send and Receive simultaneously

I'm currently working on a lasertag game with several weapons.
I would like to use one arduino nano in each weapon. It should be able to receive the IR-signals of the opponents as well as send IR-signals if a button is triggered.
So now there comes my problem:
I implemented an interrupt for the IR-receiver pin, so that an opponent's shot is always detected even when I'm shooting.
When the button is permanently pressed, the IR LED will shoot every 300 milliseconds (the send-function takes approximately 70ms and I implemented a delay of 230ms).
Unfortunately, the Nano won't detect any signal of the receiver in those 300ms.
However, if I disconnect the IR-LED everything seems to work perfectly.
Now I'm wondering, why the IR-LEDs connection has an effect on the functionality of my code.
Do you know any way I could solve this problem?
Here you can see the entire code I implemented:
#define IR_SEND_PIN 3
#define BUTTON_PIN 10
#define LED_PIN 12
#include <IRremote.hpp>
#include <Arduino.h>
uint8_t sAddress = 0;
uint8_t sCommand = 0x59;
uint8_t sRepeats = 0;
volatile uint8_t hitData;
void setup() {
IrSender.begin();
IrReceiver.begin(IR_RECEIVE_PIN);
pinMode(LED_PIN, OUTPUT);
pinMode(BUTTON_PIN, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(IR_RECEIVE_PIN), HIT, CHANGE);
}
void HIT() {
if (IrReceiver.decode()) {
hitData = IrReceiver.decodedIRData.command;
}
IrReceiver.resume();
}
void loop() {
if (digitalRead(BUTTON_PIN) == LOW) {
IrSender.sendNEC(sAddress, sCommand, sRepeats);
delay(120);
}
if (hitData == sCommand) { // indicates received signal 0x59
hitData = 0x00;
IrReceiver.resume();
digitalWrite(LED_PIN, HIGH);
delay(8);
digitalWrite(LED_PIN, LOW);
}
}```

Broker messages that recurs with nodeMCU

I’m having some problem with a home automation project of mine. I bought a nodeMCU v3 from aliexpress that i want to control my blinds with.
This is the code I’m using on it. I use the Arduino IDE to push this code in to the nodeMCU.
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <SimpleTimer.h>
// MQTT Server
const char* ssid = "****";
const char* password = "****";
const char* mqtt_server = "****";
char message_buff[100];
int photoValue = 0;
int rainValue = 0;
int photo = A0;
int rain = D6;
int relayUp = D7;
int relayDown= D8;
long interval = 10000;
long previousMillis = 0;
WiFiClient espClient;
PubSubClient client(espClient);
void setup_wifi() {
delay(10);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
}
}
void setup() {
pinMode(photo, INPUT);
pinMode(rain, INPUT);
pinMode(relayUp, OUTPUT);
pinMode(relayDown, OUTPUT);
digitalWrite(relayUp ,LOW);
digitalWrite(relayDown, LOW);
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
if (client.connect("ESP8266Client")) {
client.subscribe("home/relayBlinds");
} else {
delay(5000);
}
}
}
void loop() {
if (!client.connected()) {
// Connect (or reconnect) to mqtt broker on the openhab server
reconnect();
}
// Read Photo- and Rain-sensors
photoValue = analogRead(photo);
rainValue = analogRead(rain);
// publish Temperature reading every 10 seconds
unsigned long currentMillis = millis();
if (currentMillis - previousMillis > interval) {
previousMillis = currentMillis;
// publish Photo
String pubStringPhoto = String(photoValue);
pubStringPhoto.toCharArray(message_buff, pubStringPhoto.length()+1);
client.publish("home/photo", message_buff);
// publish Rain
String pubStringRain = String(rainValue);
pubStringRain.toCharArray(message_buff, pubStringRain.length()+1);
client.publish("home/rain", message_buff);
}
client.loop();
}
void callback(char* topic, byte* payload, unsigned int length) {
// MQTT inbound Messaging
int i = 0;
// create character buffer with ending null terminator (string)
for(i=0; i<length; i++) {
message_buff[i] = payload[i];
}
message_buff[i] = '\0';
String msgString = String(message_buff);
if (msgString == "BLINDSUP") {
digitalWrite(relayUp ,HIGH);
delay(5000);
digitalWrite(relayUp ,LOW);
} else if (msgString == "BLINDSDOWN") {
digitalWrite(relayDown ,HIGH);
delay(5000);
digitalWrite(relayDown ,LOW);
}
}
The plan was to have a Raspberry Pi with openHAB as a controller. I have used several guides to setup mosquitto and openHAB and i always get the same result.
So this is what happens: the nodeMCU connects to my Wifi and publishes both the rain and photo values. I can read them in the openHAB GUI without problems.
When i press the activation button in openHAB to publish BLINDSUP or BLINDSDOWN the messages arrives without any problems and i can see the message on my mosquitto terminal. Now is when the unexpected result starts happening. The same message gets delivered multiple times to my nodeMCU without it showing up in the mosquitto terminal.
I have been trying to find out why it would act this way and I think it is because the line:
if (!client.connected()) {
is false and the nodeMCU reconnects and gets the same message somehow. But it is always the first message. If I send BLINDSUP and then BLINDSDOWN it will only register BLINDSUP forever.
I'm really out of ideas how to fix this and would appreciate any help, thanks.
URL to the nodeMCU if that helps anyhow: nodeMCU
Try connecting to MQTT broker with a clean session. Probably you published the topic with the retain flag set to true.
If you do like this, the broker will deliver the last retained message when the nodeMCU connects to the broker and subscribes to the retained topic.

LED on Arduino won't turn on / off based on condition

I have an Arduino UNO R3 that reads a specific value from my Web Page.
I have an LED attached to the PIN 13 & GND of my Arduino.
When the Arduino reads 1 from my Web Page, it should turn the LED ON. When it reads 0, it should turn it off.
Following is the code for that:
#include "SIM900.h"
#include <SoftwareSerial.h>
#include "inetGSM.h"
InetGSM inet;
#define ledPin 13
char msg[165];
char store[2];
char a;
char b;
char* disp;
boolean started=false;
void setup()
{
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, LOW);
//Serial connection.
Serial.begin(9600);
Serial.println("GSM Shield testing.");
//Start configuration of shield with baudrate.
//For http uses is raccomanded to use 4800 or slower.
if (gsm.begin(2400)) {
Serial.println("\nstatus=READY");
started=true;
} else Serial.println("\nstatus=IDLE");
if(started)
{
//GPRS attach, put in order APN, username and password.
//If no needed auth let them blank.
if (inet.attachGPRS("TATA.DOCOMO.INTERNET", "", ""))
Serial.println("status=ATTACHED");
else Serial.println("status=ERROR");
delay(1000);
//TCP Client GET, send a GET request to the server and
//save the reply.
//Print the results.
}
}
void loop()
{
inet.httpGET("www.boat.esy.es", 80, "/retrieve.php", msg, 165);
disp = strstr(msg,"\r\n\r\n");
disp = disp+4;
a = disp[0];
b = disp[1];
Serial.println(b);
if(b=='1')
{
digitalWrite(ledPin, HIGH);
}
if(b=='0');
{
digitalWrite(ledPin, LOW);
}
}
Problem here is, when I disable the digitalWrite(ledPin,LOW), that is when I comment it out, the LED turns on & stays that way.
But the moment I enable it & load the code on my Arduino, it won't even turn on.
I'm wondering if it's a logical error or something else. Because the turning on & off of the LED depends completely on the conditions being satisfied. And for now, my Web Page returns only 1, hence the LED should stay on. But when I include both digitalWrite(ledPin, HIGH) and digitalWrite(ledPin, LOW) in the same code and run it, it doesn't work. I can see the Serial printing out the messages associated with the LED ON, but I don't see the LED turning ON.
Thank You for your time!!
First of all you have a semicolon that I think should not be in your second if-statement?
if(b=='0'); <--
{
digitalWrite(ledPin, LOW);
}
Start by trying to remove that and see if there is a difference.

BLUNO Distance Monitoring Project

I'm trying to do a project where BLUNO (Arduino UNO + BLE) will connect to an iBeacon and make use of the RSSI detected.
I've already made contact between the BLUNO and the iBeacon through the AT commands. I can get RSSI result in the Arduino IDE serial monitor when I ping it with AT commands.
My problem now is in sending those AT commands through an Arduino sketch. I know I've to use Serial Communication, but my Serial.Available function never returns more than 0.
void setup() {
pinMode(13, OUTPUT);
Serial.begin(115200);
Serial.print("+++\r\n");
Serial.print("AT+RSSI=?\r\n");
}
void loop(){
if(Serial.available()){
digitalWrite(13, HIGH);
delay(5000);
}
}
What is irritating me is that I can connect BLUNO to my iPhone and get the RSSI on the serial monitor through AT commands. But that above code doesn't work!
Any help?
I'm almost done with the whole project for now.
my mistake in the last code was the initiation part that has to be done before the AT commands. The right way is
Serial.begin(115200); //Initiate the Serial comm
Serial.print("+");
Serial.print("+");
Serial.print("+"); // Enter the AT mode
delay(500); // Slow down and wait for connection establishment
instead of
Serial.print("+++\r\n");
so yeah the rest is kind of alright. Keep in mind that this BLE thing REALLY sucks in terms of accuracy in locating a beacon. The RSSI reading keep fluctuating and the calculated distance using the simplified equation here somewhere on Stack overflow is REALLY unreliable.
So yeah keep that in mind yo!
Here's my full code just for reference.
// while the AT connection is active, the serial port between the pc and the arduino is occuipied.
// You can manipluate the data on arduino, but to display on the serial monitor you need to exit the AT mode
char Data[100];
char RAW[3];
int INDEX;
char Value = '-';
void setup() {
pinMode(13, OUTPUT); // This the onboard LED
pinMode(8, OUTPUT); // This is connected to the buzzer
Serial.begin(115200); //Initiate the Serial comm
Serial.print("+");
Serial.print("+");
Serial.print("+"); // Enter the AT mode
delay(500); // Slow down and wait for connectin establishment
}
void loop(){
Serial.println("AT+RSSI=?"); // Ask about the RSSI
for(int x=0 ; Serial.available() > 0 ; x++ ){ // get the Enter AT mode words
//delay(20); // Slow down for accuracy
Data[x] = Serial.read(); // Read and store Data Byte by Byte
if (Data[x] == Value ) // Look for the elemnt of the array that have "-" that's the start of the RSSI value
{
INDEX=x;
}
}
//Serial.println("AT+EXIT");
RAW[0] = Data[INDEX]; // Copy the RSSI value to RAW Char array
RAW[1] = Data[INDEX+1];
RAW[2] = Data[INDEX+2];
RAW[3] = Data[INDEX+3];
int RSSI = atoi(RAW); //Convert the Array to an integer
//Serial.println(RSSI);
//delay(200); // Give the program time to process. Serial Comm sucks
double D = exp(((RSSI+60)/-10)); //Calculate the distance but this is VERY inaccurate
//Serial.println(D);
if (D>1.00) // If the device gets far, excute the following>>
{
digitalWrite(13, HIGH);
digitalWrite(8, HIGH);
delay(500);
digitalWrite(13, LOW);
digitalWrite(8, LOW);
delay(500);
}
}

Resources