Официальный сайт компании Arduino по адресу arduino.cc
Ethernet Shield. Мигает светодиод при включении через ссылку.
- Войдите или зарегистрируйтесь, чтобы получить возможность отправлять комментарии
Пт, 21/06/2019 - 01:06
У меня Arduino Mega и я с трудом смог "написать" код для включения и выключение светодиода(реле). Но проблема в том что когда я нажимаю сылку и она ссылает меня на 192.168.1.147/$1 светодиод не просто включается, он включается примерно на пол секунды после выключается на пол секунды и окончательно включается. Если ещё раз нажать "Включить" то он выключится на пол секунды и включится. Я вставлю свой код, там есть код на авторизацию если что. Если можете, объясните такое странное поведение ну и помогите исправить. Спасибо.
/* * Web Server * * A simple web server with basic HTTP authentication * * Circuit: * Ethernet shield attached to Arduino board * Analog inputs attached to pins A0 through A5 (optional) */ #include <SPI.h> #include <Ethernet.h> boolean newInfo = 0; // Enter a MAC address and IP address for your controller below. // The IP address will be dependent on your local network: byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; IPAddress ip(192,168,1,147); // Initialize the Ethernet server library // with the IP address and port you want to use // (port 80 is default for HTTP): EthernetServer server(80); void setup() { // Open serial communications and wait for port to open: Serial.begin(9600); // start the Ethernet connection and the server: Ethernet.begin(mac, ip); server.begin(); Serial.print("server is at "); Serial.println(Ethernet.localIP()); } void SendOKpage(EthernetClient &client) { // send a standard http response header client.println("HTTP/1.1 200 OK"); client.println("Content-Type: text/html"); client.println("Connnection: close"); client.println(); client.println("<a href=\"/$1\">Включить</a>"); client.println("<a href=\"/$2\">Выключить</a>"); } void SendAuthentificationpage(EthernetClient &client) { client.println("HTTP/1.1 401 Authorization Required"); client.println("WWW-Authenticate: Basic realm=\"Secure Area\""); client.println("Content-Type: text/html"); client.println("Connnection: close"); client.println(); client.println("<!DOCTYPE HTML>"); client.println("<HTML> <HEAD> <TITLE>Error</TITLE>"); client.println(" </HEAD> <BODY><H1>401 Unauthorized.</H1></BODY> </HTML>"); } char linebuf[80]; int charcount=0; boolean authentificated=false; void loop() { // listen for incoming clients EthernetClient client = server.available(); if (client) { Serial.println("new client"); memset(linebuf,0,sizeof(linebuf)); charcount=0; authentificated=false; // an http request ends with a blank line boolean currentLineIsBlank = true; while (client.connected()) { if (client.available()) { char c = client.read(); // ------------------------------------------------------------------------------------------------------ if (newInfo && c == ' '){ //если переменная новой информации = 1 и "с", в которой записан запрос, равен пустой строке newInfo = 0; //то обнуляем переменную поступления новой информации } if (c == '$'){ // если переменная "с", несущая отправленный нам запрос, содержит символ $ // "$" подразумевает разделение получаемой информации (символов) newInfo = 1; //то пришла новая информация, ставим метку новой информации в 1 } if (newInfo == 1){ //если есть новая информация Serial.println (c); if (c == '1'){ //и "с" содержит 1 Serial.println ("Включить"); digitalWrite (8, HIGH); //то зажигаем светодиод } if (c == '2'){ //если "с" содержит 2 Serial.println ("Выключить"); digitalWrite (8, LOW); //гасим светодиод } } // ----------------------------------------------------------------------------------------------------- linebuf[charcount]=c; if (charcount<sizeof(linebuf)-1) charcount++; Serial.write(c); // if you've gotten to the end of the line (received a newline // character) and the line is blank, the http request has ended, // so you can send a reply if (c == '\n' && currentLineIsBlank) { if (authentificated) SendOKpage(client); else SendAuthentificationpage(client); break; } if (c == '\n') { // you're starting a new line currentLineIsBlank = true; if (strstr(linebuf,"Authorization: Basic")>0 && strstr(linebuf,"скрыт пароль")>0) authentificated=true; memset(linebuf,0,sizeof(linebuf)); charcount=0; } else if (c != '\r') { // you've gotten a character on the current line currentLineIsBlank = false; } } } // give the web browser time to receive the data delay(1); // close the connection: client.stop(); Serial.println("client disonnected"); } }