Answer the question
In order to leave comments, you need to log in
How to optimize arduino code?
Good time of the day. How can I increase the speed of code execution in arduino?
Actually the code itself:
#include <SoftwareSerial.h>
SoftwareSerial ESPport(2, 3);
////////////////////// RX, TX
// если у вас MEGA, то закомментируйте верхние две строчки и раскомментируйте нижеследующую.
// ESP подключите к Serial1 (18, 19), скорость можно сделать 57600
// HardwareSerial & ESPport = Serial1;
const int r1 = 4;
const int r2 = 5;
const int r3 = 6;
const int r4 = 7;
int r1State = HIGH;
int r2State = HIGH;
int r3State = HIGH;
int r4State = HIGH;
#define BUFFER_SIZE 128
char buffer[BUFFER_SIZE];
String vklotkl1;
String vklotkl2;
String vklotkl3;
String vklotkl4;
void setup()
{
pinMode(r1, OUTPUT);
pinMode(r2, OUTPUT);
pinMode(r3, OUTPUT);
pinMode(r4, OUTPUT);
Serial.begin(9600); // Терминал
ESPport.begin(9600); // ESP8266
clearSerialBuffer();
Serial.println("RESET 3,5 sek");
delay(200);
Serial.println(GetResponse("AT+RST",3400)); // перезагрузка ESP
delay(200);
Serial.println(GetResponse("AT+CWMODE=1",300)); // режим клиента
delay(200);
Serial.println(GetResponse("AT+CSYSWDTENABLE",300)); // сторож
delay(20);
connectWiFi("testap","passfortestap"); // подключаемся к домашнему роутеру (имя точки, пароль)
delay(200);
Serial.println(GetResponse("AT+CIPMODE=0",300)); // сквозной режим передачи данных.
delay(200);
Serial.println(GetResponse("AT+CIPMUX=1",300)); // multiple connection.
delay(200);
Serial.print("Start TCP-server: ");
delay(200);
Serial.println(GetResponse("AT+CIPSERVER=1,88", 300)); // запускаем ТСР-сервер на 88-ом порту
delay(200);
Serial.println(GetResponse("AT+CIPSTO=2", 300)); // таймаут сервера 2 сек
delay(200);
Serial.println(GetResponse("AT+CIFSR", 300)); // узнаём адрес
delay(200);
digitalWrite(r1,r1State);
digitalWrite(r2,r2State);
digitalWrite(r3,r3State);
digitalWrite(r4,r4State);
}
///////////////////основной цикл, принимает запрос от клиента///////////////////
void loop()
{
int ch_id, packet_len;
char *pb;
ESPport.readBytesUntil('\n', buffer, BUFFER_SIZE);
if(strncmp(buffer, "+IPD,", 5)==0)
{
sscanf(buffer+5, "%d,%d", &ch_id, &packet_len);
if (packet_len > 0)
{
pb = buffer+5;
while(*pb!=':') pb++;
pb++;
if(strncmp(pb, "GET / ", 6) == 0)
{
clearSerialBuffer();
otvet_klienty(ch_id);
}
//r1
if(strncmp(pb, "GET /a", 6) == 0)
{
clearSerialBuffer();
if(r1State == LOW)
{
r1State = HIGH;
vklotkl1 = "VKL";
}
else
{
r1State = LOW;
vklotkl1 = "OTKL";
}
digitalWrite(r1, r1State);
otvet_klienty(ch_id);
}
//r2
if(strncmp(pb, "GET /b", 6) == 0)
{
clearSerialBuffer();
if(r2State == LOW)
{
r2State = HIGH;
vklotkl2 = "VKL";
}
else
{
r2State = LOW;
vklotkl2 = "OTKL";
}
digitalWrite(r2, r2State);
otvet_klienty(ch_id);
}
//r3
if(strncmp(pb, "GET /c", 6) == 0)
{
clearSerialBuffer();
if(r3State == LOW)
{
r3State = HIGH;
vklotkl3 = "VKL";
}
else
{
r3State = LOW;
vklotkl3 = "OTKL";
}
digitalWrite(r3, r3State);
otvet_klienty(ch_id);
}
//r4
if(strncmp(pb, "GET /d", 6) == 0)
{
clearSerialBuffer();
if(r4State == LOW)
{
r4State = HIGH;
vklotkl4 = "VKL";
}
else
{
r4State = LOW;
vklotkl4 = "OTKL";
}
digitalWrite(r4, r4State);
otvet_klienty(ch_id);
}
}
}
clearBuffer();
}
//////////////////////формирование ответа клиенту////////////////////
void otvet_klienty(int ch_id)
{
String Header;
Header = "HTTP/1.1 200 OK\r\n";
Header += "Content-Type: text/html\r\n";
Header += "Connection: close\r\n";
String Content;
Content = "<html><body>";
Content += "<form action='a' method='GET'>r1 <input type='submit' value='VKL/OTKL'> " + vklotkl1 + "</form>";
Content += "<form action='b' method='GET'>r2 <input type='submit' value='VKL/OTKL'> " + vklotkl2 + "</form>";
Content += "<form action='c' method='GET'>r3 <input type='submit' value='VKL/OTKL'> " + vklotkl3 + "</form>";
Content += "<form action='d' method='GET'>r4 <input type='submit' value='VKL/OTKL'> " + vklotkl4 + "</form>";
Content += "</body></html>";
Header += "Content-Length: ";
Header += (int)(Content.length());
Header += "\r\n\r\n";
ESPport.print("AT+CIPSEND="); // ответ клиенту
ESPport.print(ch_id);
ESPport.print(",");
ESPport.println(Header.length()+Content.length());
delay(20);
if(ESPport.find(">"))
{
ESPport.print(Header);
ESPport.print(Content);
delay(200);
}
}
/////////////////////отправка АТ-команд/////////////////////
String GetResponse(String AT_Command, int wait)
{
String tmpData;
ESPport.println(AT_Command);
delay(wait);
while (ESPport.available() >0 )
{
char c = ESPport.read();
tmpData += c;
if ( tmpData.indexOf(AT_Command) > -1 )
tmpData = "";
else
tmpData.trim();
}
return tmpData;
}
//////////////////////очистка ESPport////////////////////
void clearSerialBuffer(void)
{
while ( ESPport.available() > 0 )
{
ESPport.read();
}
}
////////////////////очистка буфера////////////////////////
void clearBuffer(void) {
for (int i =0;i<BUFFER_SIZE;i++ )
{
buffer[i]=0;
}
}
////////////////////подключение к wifi/////////////////////
boolean connectWiFi(String NetworkSSID,String NetworkPASS)
{
String cmd = "AT+CWJAP=\"";
cmd += NetworkSSID;
cmd += "\",\"";
cmd += NetworkPASS;
cmd += "\"";
Serial.println(cmd);
Serial.println(GetResponse(cmd,6500));
}
Answer the question
In order to leave comments, you need to log in
1) Work with an array, not with variables r1, r2, etc. This will allow the use of loops.
2) Move all string constants to PROGMEM. This will save a lot of RAM.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question