Проблема с чекбоксом
- Войдите на сайт для отправки комментариев
Пт, 23/06/2017 - 06:30
Здравствуйте. Вопрос простой, но никак не пойму в чем дело. Для снятия галочки с чекбокса приходится дважды нажимать на него.
#include <SPI.h>
#include <Ethernet.h>
#include <OneWire.h>
#include <DallasTemperature.h>
#include <iarduino_RTC.h>
// MAC address from Ethernet shield sticker under board
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(192, 168, 1, 198); // IP address, may need to change depending on network
EthernetServer server(80); // create a server at port 80
String HTTP_req; // stores the HTTP request
float getTemp; //запрос температуры
boolean LED_status = 0; // state of LED, off by default
boolean heating = 0; //
OneWire oneWire(12);
DallasTemperature sensors(&oneWire);
iarduino_RTC time(RTC_DS1307);
void setup()
{
Ethernet.begin(mac, ip); // initialize Ethernet device
server.begin(); // start to listen for clients
time.begin();
Serial.begin(9600); // for diagnostics
pinMode(5, OUTPUT); // LED on pin 5
pinMode(7, OUTPUT); // LED on pin 5
}
void loop()
{
sensors.requestTemperatures();
getTemp = sensors.getTempCByIndex(0);
EthernetClient client = server.available(); // try to get client
if (client) { // got client?
boolean currentLineIsBlank = true;
while (client.connected()) {
if (client.available()) { // client data available to read
char c = client.read(); // read 1 byte (character) from client
HTTP_req += c; // save the HTTP request 1 char at a time
// last line of client request is blank and ends with \n
// respond to client only after last line received
if (c == '\n' && currentLineIsBlank) {
// send a standard http response header
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println("Connection: close");
client.println();
// send web page
client.println("<!DOCTYPE html>");
client.println("<html>");
client.println("<head>");
client.println("<meta charset=\"UTF-8\">");
// client.println("<meta http-equiv=\"refresh\" content=\"30\">");
client.println("<title>Arduino LED Control</title>");
client.println("</head>");
client.println("<body>");
client.println("<h1> </h1>");
client.println("<p>Режим работы </p>");
//client.println("<form method=\"get\">");
ProcessCheckbox(client);
client.println("<p>Температура в аквариуме");
client.print(getTemp);
client.print(" ºC</p>");
client.print(time.gettime("H:i:s"));
client.println("</form>");
client.println("</body>");
client.println("</html>");
HTTP_req = ""; // finished with request, empty string
break;
}
// every line of text received from the client ends with \r\n
if (c == '\n') {
// last character on line of received text
// starting new line with next character read
currentLineIsBlank = true;
}
else if (c != '\r') {
// a text character was received from client
currentLineIsBlank = false;
}
} // end if (client.available())
} // end while (client.connected())
delay(1); // give the web browser time to receive the data
client.stop(); // close the connection
} // end if (client)
}
// switch LED and send back HTML for LED checkbox
void ProcessCheckbox(EthernetClient cl)
{
if (HTTP_req.indexOf("mode=man") > -1) { // see if checkbox was clicked
Serial.println("man");
cl.println("<form method=\"get\" name=\"mode\"> <input type=\"checkbox\" name=\"mode\" value=\"man\" checked=\"checked\" onclick=\"submit();\"> MAN </form>");
}
else {
Serial.println("auto");
cl.println("<form method=\"get\" name=\"mode\"> <input type=\"checkbox\" name=\"mode\" value=\"man\" onclick=\"submit();\" > AUTO </form>");
}
}
В мониторе пишет auto man man auto, хотя должно быть auto man auto
#include <SPI.h> #include <Ethernet.h> #include <OneWire.h> #include <DallasTemperature.h> #include <iarduino_RTC.h> // MAC address from Ethernet shield sticker under board byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; IPAddress ip(192, 168, 1, 198); // IP address, may need to change depending on network EthernetServer server(80); // create a server at port 80 String HTTP_req; // stores the HTTP request float getTemp; //запрос температуры boolean LED_status = 0; // state of LED, off by default boolean heating = 0; // OneWire oneWire(12); DallasTemperature sensors(&oneWire); iarduino_RTC time(RTC_DS1307); void setup() { Ethernet.begin(mac, ip); // initialize Ethernet device server.begin(); // start to listen for clients time.begin(); Serial.begin(9600); // for diagnostics pinMode(5, OUTPUT); // LED on pin 5 pinMode(7, OUTPUT); // LED on pin 5 } void loop() { sensors.requestTemperatures(); getTemp = sensors.getTempCByIndex(0); EthernetClient client = server.available(); // try to get client if (client) { // got client? boolean currentLineIsBlank = true; while (client.connected()) { if (client.available()) { // client data available to read char c = client.read(); // read 1 byte (character) from client HTTP_req += c; // save the HTTP request 1 char at a time // last line of client request is blank and ends with \n // respond to client only after last line received if (c == '\n' && currentLineIsBlank) { // send a standard http response header client.println("HTTP/1.1 200 OK"); client.println("Content-Type: text/html"); client.println("Connection: close"); client.println(); // send web page client.println("<!DOCTYPE html>"); client.println("<html>"); client.println("<head>"); client.println("<meta charset=\"UTF-8\">"); // client.println("<meta http-equiv=\"refresh\" content=\"30\">"); client.println("<title>Arduino LED Control</title>"); client.println("</head>"); client.println("<body>"); client.println("<h1> </h1>"); client.println("<p>Режим работы </p>"); //client.println("<form method=\"get\">"); ProcessCheckbox(client); client.println("<p>Температура в аквариуме"); client.print(getTemp); client.print(" ºC</p>"); client.print(time.gettime("H:i:s")); client.println("</form>"); client.println("</body>"); client.println("</html>"); HTTP_req = ""; // finished with request, empty string break; } // every line of text received from the client ends with \r\n if (c == '\n') { // last character on line of received text // starting new line with next character read currentLineIsBlank = true; } else if (c != '\r') { // a text character was received from client currentLineIsBlank = false; } } // end if (client.available()) } // end while (client.connected()) delay(1); // give the web browser time to receive the data client.stop(); // close the connection } // end if (client) } // switch LED and send back HTML for LED checkbox void ProcessCheckbox(EthernetClient cl) { if (HTTP_req.indexOf("mode=man") > -1) { // see if checkbox was clicked Serial.println("man"); cl.println("<form method=\"get\" name=\"mode\"> <input type=\"checkbox\" name=\"mode\" value=\"man\" checked=\"checked\" onclick=\"submit();\"> MAN </form>"); } else { Serial.println("auto"); cl.println("<form method=\"get\" name=\"mode\"> <input type=\"checkbox\" name=\"mode\" value=\"man\" onclick=\"submit();\" > AUTO </form>"); } }ну это вопрос по HTML больше, чем по ардуино. Что могу предположить - у вас форма и чекбокс называются одинаково, попробуйте назвать форму и сам чекбокс разными именами
Название формы тут ни какой роли играть не должно. Еслиб скриптом на клиенте обрабатывали, то еще как-то можно предположить, да и то врядтли. А так - до сервера оно не доходит в запросе.
Уберите или измените значение value у чекбокса в строке 099. Хотя, по идее, при снятии галочки оно не должно отсылаться, но мало ли.
И лишнее закрытие формы в строке 70
Название формы появилось много позже, при поиске проблемы. Оно никак не влияет на чекбокс, и изначально его не было. Значение value менял по всякому - результата 0. Лишнее закрытие формы в строке 70 было убрано, после добавления сюда кода. Но сообщение здесь отредактировать не получилось. Спасибо.
Ну тогда сделайте вывод всего клиентского запроса в сериал, и смотрите что он там шлет по вашим кликам.
Скорее всего условие "mode=man" вы ловите по реферу. Если так, то решение в правильной обработке запроса клиента. Я вообще из запроса в переменную для разбора обычно читаю от GET и до конца этой строки, все остальное "вычитываю в пустоту". Так и оперативки под буфер меньше надо (на 328 чипах очень скоро с этим столкнетесь) и всякие лишние ненужности обрабатывать ненадо.