Help with Uderstanding This CODE!

:slight_smile: I came across this code via you-tube and it makes leds on or off with an android app. I am struggling to know how this works and what does here volatile do. we can declare variables as int, bool, const, byte unsigned long etc,. what is the importance of volatile. I reference section I read about Volatile it loads value of variable from RAM instead from a register which can be inaccurate in some conditions like interrupts. Any one interested to help is highly Appreciated …
what are these : k1 = 0,CC1=0,RX1 = 0,D = 0;
volatile char MY_DATA1[60]; ???

volatile char MY_DATA1[60];
volatile unsigned char k1 = 0,CC1=0,RX1 = 0,D = 0;
void setup()
{
// relay out put pin control.//
pinMode(A0,OUTPUT);
pinMode(A1,OUTPUT);
pinMode(A2,OUTPUT);
pinMode(A3,OUTPUT);
digitalWrite(A0,HIGH);
digitalWrite(A1,HIGH);
digitalWrite(A2,HIGH);
digitalWrite(A3,HIGH);
// Initial setup //
Serial.begin(9600);
// Initial ESP8266 //
ESP8266_INIT();
}
void loop()
{
// receive data from ESP8266 //
if(Serial.available())
{
MY_DATA1[k1] = Serial.read(); // read receive data from wi-fi module.
CC1 = MY_DATA1[k1];
if(CC1 == ':')D = k1;// check weather data scan start or not.
k1++;
if(CC1 == '\n'){k1=0;RX1 = 1;} // chaeck new line character are receive or not.
}
// Processing  data which are receiving  from ESP8266 //
if(RX1 == 1)
{
if(MY_DATA1[D] == ':')
{
MY_DATA1[D] = '0';
if(MY_DATA1[D+1] == 'F')
{
MY_DATA1[D+1] = '0';

if(MY_DATA1[D+2] == 'A')//switch 1 on
{
MY_DATA1[D+2] = '0';

digitalWrite(A0,LOW);
RX1 = 0;
}
else if(MY_DATA1[D+2] == 'B')//switch 1 off
{
MY_DATA1[D+2] = '0';
digitalWrite(A0,HIGH);
RX1 = 0;
}
else if(MY_DATA1[D+2] == 'C')//switch 2 on
{
MY_DATA1[D+2] = '0';
digitalWrite(A1,LOW);
RX1 = 0;
}
else if(MY_DATA1[D+2] == 'D')//switch 1 off
{
MY_DATA1[D+2] = '0';
digitalWrite(A1,HIGH);
RX1 = 0;
}
else if(MY_DATA1[D+2] == 'E')//switch 3 on
{
MY_DATA1[D+2] = '0';
digitalWrite(A2,LOW);
RX1 = 0;
         }
else if(MY_DATA1[D+2] == 'F')//switch 1 off
{
MY_DATA1[D+2] = '0';
digitalWrite(A2,HIGH);
RX1 = 0;
}
else if(MY_DATA1[D+2] == 'G')//switch 1 on
{
MY_DATA1[D+2] = '0';
digitalWrite(A3,LOW);
RX1 = 0;
}
else if(MY_DATA1[D+2] == 'H')//switch 1 off
{
MY_DATA1[D+2] = '0';
digitalWrite(A3,HIGH);
RX1 = 0;
}
    }
}
RX1 = 0;
}
}
void ESP8266_INIT()// initializing wi-fi module.
{
Serial.println("AT");// check AT mode.
delay(1000);
Serial.println("AT+RST");//RESET module.
delay(3000);
Serial.println("AT+CWSAP=\"YOUNUS \",\"87654321\",3,2");//set the ssid and password."Home Automation","2231anto",3,2

delay(1500);
Serial.println("AT+CWMODE=3");// set ESP8266 in MODE 3 (Both mode AP+station).
delay(1400);
Serial.println("AT+CIPMUX=1");// set ESP8266 in MUX 1 (allow multiple connection).
delay(1400);
Serial.println("AT+CIPSERVER=1,80");// start communication ESP8266 on PORT80.
delay(1500);
}

Explanation of Volatile

Can you give a link to that Youtube video ?

The sketch should not have 'volatile' for those variables, that is a mistake.

The "MY_DATA1" is used as a buffer to store the incoming data in.
The "k1", "CC1", "RX1" and "D" are variables that are used to understand the incoming data.

I would write it this way:

char buffer[60];
byte k1 = 0;
byte CC1 = 0;
byte RX1 = 0;
byte D = 0;

But I would probably use all 'char' or all 'byte' for them, and I would not declare them global but local (except the buffer).

When you find random code online, that does not mean that the code is good.
When something is wrong with a Arduino library on Github, then a "issue" can be made. Even when it is not fixed, then others with the same problem can check the issues. The examples on instructables.com or in a Youtube video are often not very good. Some have a personal blog with Arduino code, but when I write a message about a bug, then they often ignore my message and the bug stays.

The code you posted does just some serial output and receive some serial-input.

How would any kind of android-app ever be able to send/receive via a serial-interface?

Does this code do anything more than the serial-output??

:slight_smile: Hi all reply to you all :
This code works good and accepts commands only from a WiFi socket widget App on play store. I send 192.168.4.1:80/FA Up to --------FH it accepts. I tried my own built apps to send the same data but arduino does not respond to them but arduino receives them as indicated by built in led of WiFi and arduino.

74younus:
:slight_smile: Hi all reply to you all :
This code works good and accepts commands only from a WiFi socket widget App on play store. I send 192.168.4.1:80/FA Up to --------FH it accepts. I tried my own built apps to send the same data but arduino does not respond to them but arduino receives them as indicated by built in led of WiFi and arduino.

From this answer I can see that you have learned nothing about how to improve your postings.
I'm a guy who really likes to help. In your case my "Help" goes to all the others users.
From postings you made in the past I have the experience that

  • you don't answer questions from users that are trying to help you through asking back
  • You don't post full sketches that would allow to do a good analysis.
  • You keep on hopping around posting new questions with almost no relation to the questions before.
    So to all the other users: if you enjoy to do a training on your patience with users acting like described above go ahead answering.
    If you don't enjoy it spend your time answering questions of other users that are able to answer in detail and are able to answer questions you have to them.
    @younus: I will follow your postings just throwing in short-worded answers because I'm curious how long it will take you to change your posting-behavior.

StefanL38:
@younus: I will follow your postings just throwing in short-worded answers because I'm curious how long it will take you to change your posting-behavior.

Actually I had not read your #1 reply link now I did and It helped a lot to understand volatile now I want why other like CC1, K1, D, R1 my data =[60]
Can't I use other letters to represent them and why my data = [60] why not [. x ]

post your complete sketch. I don't understand your question. Write your question in your native language and let do google-translate the translation

तुम बहुत बड़े आलसी आदमी हो!
मैंने लिखा है कि आपको अपनी मातृभाषा में अपने प्रश्न लिखने चाहिए और फिर आपको Google को स्वयं अनुवाद करने देना चाहिए।

74younus खुद अंग्रेजी में अनुवाद करता है।
और फिर एक बहुत विस्तृत विवरण, कृपया। कम से कम 200 शब्द

tum bahut bade aalasee aadamee ho!
mainne likha hai ki aapako apanee maatrbhaasha mein apane prashn likhane chaahie aur phir aapako googlai ko svayan anuvaad karane dena chaahie.

74younus khud angrejee mein anuvaad karata hai.
aur phir ek bahut vistrt vivaran, krpaya. kam se kam 200 shabd

tum bahut bade aalasee aadamee ho!
mainne likha hai ki aapako apanee maatrbhaasha mein apane prashn likhane chaahie aur phir aapako googlai ko svayan anuvaad karane dena chaahie.

74younus khud angrejee mein anuvaad karata hai.
aur phir ek bahut vistrt vivaran, krpaya. kam se kam 200 shabd

Your link is considered to be very helpful. Now tell me what cc1, k1, r1 d can not be written with any other words? What does my data[60] mean here?
Translated

What does my data[60] mean here?

volatile char MY_DATA1[60];

An array of chars that can hold 60 values available globally throughout the sketch. The volatile indicates that its contents may be changed in circumstances that the compiler cannot predict and causes the compiler to store the array in memory rather than in processor registers

Now tell me what cc1, k1, r1 d can not be written with any other words?

volatile unsigned char k1 = 0,CC1=0,RX1 = 0,D = 0;

Four individual unsigned char variables named k1, CC1, RX1 and D all initialised with a value of zero available globally throughout the sketch. I am not sure what you are asking but that could also be written as

volatile unsigned char k1 = 0;
volatile unsigned char CC1=0;
volatile unsigned char RX1 = 0;
volatile unsigned char D = 0;

if that is more understandable or different names could be used for the variables if that suits you as long as the corresponding names are used throughout the sketch

UKHeliBob:
if that is more understandable or different names could be used for the variables if that suits you as long as the corresponding names are used throughout the sketch

Thank you i got it..
Question : If i need to send A or FA to make A0 high or low why do this code checks for something CC1 == : ,CC== \n ??? why those unnecessary checks......?

if(Serial.available())
{
MY_DATA1[k1] = Serial.read(); // read receive data from wi-fi module.
CC1 = MY_DATA1[k1];
if(CC1 == ':')D = k1;// check weather data scan start or not.
k1++;
if(CC1 == '\n'){k1=0;RX1 = 1;} // chaeck new line character are receive or not.
}
// Processing  data which are receiving  from ESP8266 //
if(RX1 == 1)
{
if(MY_DATA1[D] == ':')
{
MY_DATA1[D] = '0';
if(MY_DATA1[D+1] == 'F')
{
MY_DATA1[D+1] = '0';

if(MY_DATA1[D+2] == 'A')//switch 1 on
{
MY_DATA1[D+2] = '0';

digitalWrite(A0,LOW);
RX1 = 0;
}

this conversation needs a higher entertainment to factual ratio:

The Andoid-app you are using sends its data via WiFi. To jump over the internal virus-checking of the ESP-chip it has to send AND CHECK this additional characters. There is no other way to jump through the WLAN-serial-Brickwall. It's like Harry Potter has to run against the brickwall to reach track-line 8_3/4. Hope you enjoy the interspersed entertainment nonsense.

StefanL38:
this conversation needs a higher entertainment to factual ratio:

The Andoid-app you are using sends its data via WiFi. To jump over the internal virus-checking of the ESP-chip it has to send AND CHECK this additional characters. There is no other way to jump through the WLAN-serial-Brickwall. It's like Harry Potter has to run against the brickwall to reach track-line 8_3/4. Hope you enjoy the interspersed entertainment nonsense.

thank you,
Actually I am trying to learn all esp related codes with arduino so I can design an App that can controll arduino pins through WiFi. My next code will be ready in which i send data with a Wifi terminal App from playstore and it works for some esp codes but i face issues with arduino codes. Help from anyone is highly appreciated.

This code is very exciting as it performs two tasks : sends AT commands to ESP to Change its parameters like said, password, mode, MUX etc. and also sets program of arduino to make leds at pins 9 and 10 on and off with android App that I have. I tried it and its sends me response but does not change status of android pins. This is challenging one let’s see who solves it. I face problems to make this code work!

#include <SoftwareSerial.h>
 
#define DEBUG true
 
SoftwareSerial esp8266(2,3); // rx, tx
// This means that you need to connect the TX pin of the esp to the Arduino's pin 2
// and the RX pin of the esp to the Arduino's pin 3
int relay1 = 9;
int relay2 = 10;



int flag1 = 0;
int flag2 = 0;


void setup()
{
Serial.begin(9600);
esp8266.begin(9600); // your esp's baud rate might be different
pinMode(relay1,OUTPUT);
pinMode(relay2,OUTPUT);


digitalWrite(relay1, LOW);
digitalWrite(relay2, LOW);




sendCommand("AT+RST\r\n",2000,DEBUG); // reset module
sendCommand("AT+CWMODE=2\r\n",1000,DEBUG); // configure as access point
//sendCommand("AT+CWJAP=\"mySSID\",\"myPassword\"\r\n",3000,DEBUG);
//delay(10000);
sendCommand("AT+CIFSR\r\n",1000,DEBUG); // get ip address
sendCommand("AT+CIPMUX=1\r\n",1000,DEBUG); // configure for multiple connections
sendCommand("AT+CIPSERVER=1,80\r\n",1000,DEBUG); // turn on server on port 80
Serial.println("Server Ready");
}
 
void loop()
{
char pinNumber = '0';
char secondNumber = '0';
if(esp8266.available()) // check if the esp is sending a message
{


//delay(1000); // wait for the serial buffer to fill up (read all the serial data)


// get the connection id so that we can then disconnect
char connectionId = '0'; //esp8266.read(); // subtract 48 because the read() function returns
// the ASCII decimal value and 0 (the first decimal number) starts at 48
esp8266.find("pin="); // advance cursor to "pin="
char pinNumber = (esp8266.read()); // get first number i.e. if the pin 13 then the 1st number is 1
Serial.println("pin number:");
Serial.print(pinNumber);

char secondNumber = (esp8266.read());
Serial.println("second number:");
Serial.println(secondNumber);
String content ="" ;

// relay1 
if((pinNumber == '1')&&(secondNumber == '1') && ( flag1 == 0))
{
 digitalWrite(relay1, HIGH);
 content = "relay1 is ON ";
 flag1 = 1;

}

if((pinNumber == '1')&&(secondNumber == '8') && (flag1 == 1) )
{
 digitalWrite(relay1, LOW);
  content = "Relay1 is OFF ";
flag1 = 0;

 
} 

// relay2 
if((pinNumber == '2')&&(secondNumber == '3') && ( flag2 == 0))
{
 digitalWrite(relay2, HIGH);
 content = "relay2 is ON ";
 flag2 = 1;

}

if((pinNumber == '6')&&(secondNumber == '6') && (flag2 == 1) )
{
 digitalWrite(relay2, LOW);
  content = "Relay2 is OFF ";
flag2 = 0;

 
} 


// feedback 
if((pinNumber == '5')&&(secondNumber == '5') )
{
  if (digitalRead(relay1) )
  content += "Relay1 = ON"; 
  else 
  content += "Relay1 = OFF"; 


    if (digitalRead(relay2) )
  content += " Relay2 = ON"; 
  else 
  content += " Relay2 = OFF"; 

}
//******************************************


sendHTTPResponse(connectionId,content);
// make close command
String closeCommand = "AT+CIPCLOSE=";
closeCommand+=connectionId; // append connection id
closeCommand+="\r\n";
sendCommand(closeCommand,1000,DEBUG); // close connection

}
}

/*
* Name: sendData
* Description: Function used to send data to ESP8266.
* Params: command - the data/command to send; timeout - the time to wait for a response; debug - print to Serial window?(true = yes, false = no)
* Returns: The response from the esp8266 (if there is a reponse)
*/
String sendData(String command, const int timeout, boolean debug)
{
String response = "";
int dataSize = command.length();
char data[dataSize];
command.toCharArray(data,dataSize);
esp8266.write(data,dataSize); // send the read character to the esp8266
if(debug)
{
Serial.println("\r\n====== HTTP Response From Arduino ======");
Serial.write(data,dataSize);
Serial.println("\r\n========================================");
}
long int time = millis();
while( (time+timeout) > millis())
{
while(esp8266.available())
{
// The esp has data so display its output to the serial window
char c = esp8266.read(); // read the next character.
response+=c;
}
}
if(debug)
{
Serial.print(response);
}
return response;
}
 
/*
* Name: sendHTTPResponse
* Description: Function that sends HTTP 200, HTML UTF-8 response
*/
void sendHTTPResponse(char connectionId, String content)
{
// build HTTP response
String httpResponse;
String httpHeader;
// HTTP Header
httpHeader = "HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=UTF-8\r\n";
httpHeader += "Content-Length: ";
httpHeader += content.length();
httpHeader += "\r\n";
httpHeader +="Connection: close\r\n\r\n";
httpResponse = httpHeader + content + " "; // There is a bug in this code: the last character of "content" is not sent, I cheated by adding this extra space
sendCIPData(connectionId,httpResponse);
}
 
/*
* Name: sendCIPDATA
* Description: sends a CIPSEND=<connectionId>,<data> command
*
*/
void sendCIPData(char connectionId, String data)
{
String cipSend = "AT+CIPSEND=";
cipSend += connectionId;
cipSend += ",";
cipSend +=data.length();
cipSend +="\r\n";
sendCommand(cipSend,1000,DEBUG);
sendData(data,1000,DEBUG);
}
 
/*
* Name: sendCommand
* Description: Function used to send data to ESP8266.
* Params: command - the data/command to send; timeout - the time to wait for a response; debug - print to Serial window?(true = yes, false = no)
* Returns: The response from the esp8266 (if there is a reponse)
*/
String sendCommand(String command, const int timeout, boolean debug)
{
String response = "";
esp8266.print(command); // send the read character to the esp8266
long int time = millis();
while( (time+timeout) > millis())
{
while(esp8266.available())
{
// The esp has data so display its output to the serial window
char c = esp8266.read(); // read the next character.
response+=c;
}
}
if(debug)
{
Serial.print(response);
}
return response;
}
  if (esp8266.available()) // check if the esp is sending a message

Just because there is at least one character is available it does not mean that the whole message is available but you go ahead and blindly read several characters

UKHeliBob:

  if (esp8266.available()) // check if the esp is sending a message

Just because there is at least one character is available it does not mean that the whole message is available but you go ahead and blindly read several characters

while i concentrated on why you wrote i checked this code again from “if (serial.available())” command and I found TWO mistakes there :

//delay(1000); // wait for the serial buffer to fill up (read all the serial data)
// get the connection id so that we can then disconnect
char connectionId = '0'; //esp8266.read(); // subtract 48 because the read() function returns
// the ASCII decimal value and 0 (the first decimal number) starts at 48

See //delay(1000); and //esp8266.read(); these were commented out i corrected those and included in the code and now the code worked. This is called real help and cooperation i appreciate this.
Thank you.

:slight_smile: Now I want to design my own App to control this code from android phone

How to send these commands if you have any Idea or shall I turn to a different forum?

if((pinNumber == '1')&&(secondNumber == '1') && ( flag1 == 0))

How to send these commands if you have any Idea or shall I turn to a different forum?

Do you mean what format should the commands have or how to actually send them ?

UKHeliBob:
Do you mean what format should the commands have or how to actually send them ?

I heve built apps for bluetooth and thats simple in format , we have just to send texxt r numbers like 1,2....so on

But this is esp8266 I have also use apps for esp and sent commands but the format is tricky one
I do not know in which format to use.