Помогите пожалуйста разобраться с сервером на ардуино

Тема в разделе "Arduino & Shields", создана пользователем SDV, 20 май 2018.

  1. SDV

    SDV Нерд

    Подскажите пожалуйста. Имеется следующее железо ArduinoMega + Ethernet Shield W5100 + фоторезистор.
    Мини задача - создать сервер, что бы можно было контролировать состояние освещенности с любого устройства по интернету.
    Переделал пример в следующий скетч:
    Код (C++):
    [code]
    #include <SPI.h>
    #include <Ethernet.h>
    #include <Wire.h>
    #include <TimeLib.h>
    #include <DS1307RTC.h>


    // 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, 177);

    // 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);
      while (!Serial) {
        ; // wait for serial port to connect. Needed for Leonardo only
      }


      // start the Ethernet connection and the server:
      Ethernet.begin(mac, ip);
      server.begin();
      Serial.print("server is at ");
      Serial.println(Ethernet.localIP());
    }


    void loop() {
      // listen for incoming clients
      EthernetClient client = server.available();
      if (client) {
        Serial.println("new client");
        // an http request ends with a blank line
        boolean currentLineIsBlank = true;
        while (client.connected()) {
          if (client.available()) {
            char c = client.read();
            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) {
              // send a standard http response header
              client.println("HTTP/1.1 200 OK");
              client.println("Connection: close");  // the connection will be closed after completion of the response
              client.println();
              client.println("<!DOCTYPE HTML>");
              client.println("<html>");
              client.println("<meta http-equiv='refresh' content='5'/>");
              client.println("<meta http-equiv='content-type' content='text/html; charset=UTF-8'>");
              client.println("<title>Сервер датчика освещенности</title>");
              int sensePin = 0;
              int val = analogRead(sensePin);
              val = constrain(val, 650, 975);
              int sdv = map(val,650,975,1,0);
              client.print("Состояние освещенности = ");
              client.print(sdv);
              client.println("<br />");
              client.println("</html>");
              break;
            }
            if (c == '\n') {
              // you're starting a new line
              currentLineIsBlank = true;
            }
            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 disconnected");
      }
    }

     
    Суть вопроса в следующем. Когда ардуинка питается от USBподключенному к компьютеру на котором осуществляется просмотр порта через ArduinoIDE показания фоторезистора можно наблюдать в браузере по заданному IP. Когда запитываю ардуинку от блока питания, показания фоторезистора в браузере пропадаю и страничка по IP вообще не открывается.
    Подскажите где я туплю? Я ведь нуб еще)
     
  2. Yatskov

    Yatskov Нуб

    та же проблема:
    Ethernet Shield W5100 подключен к роутеру, ардуинка при подключении к компу по USB шлет данные по MQTT. пробовал подключать отдельным питанием (не от компа) через штыревой разъем, через микро usb с подключением к зарядке от телефона на 2А. результата нет. только при подключении микро USB - USB компа работает.
    проблема с самим шилдом или кривыми руками (кодом)?
     
  3. SDV

    SDV Нерд

    У меня проблема решилась когда на БП выставил выходное напряжение на 5 В вместо 9 В.
     
  4. Yatskov

    Yatskov Нуб