Arduino NANO ENC28J60 и WEB и LCD 1602

Тема в разделе "Arduino & Shields", создана пользователем blackcatw, 5 июн 2016.

  1. blackcatw

    blackcatw Нерд

    Собрал устройство, которое запрашивает IP адрес и отображает его на LCD 1602 ну и плюсом долно это устройство давать ответ и отображать температуру и влажность.
    Код (C++):
    #include <LiquidCrystal.h>

    #include <EtherCard.h>
    #include "DHT.h"
    #include <avr/pgmspace.h>

    // настройки Ethernet

    #define DHTPIN 9
    #define BUF_SIZE 512
    #define DHTTYPE DHT11   // DHT 11

    byte mac[] = { 0x00, 0x04, 0xA3, 0x21, 0xCA, 0x38 }; // MAC-адрес

    byte fixed = false; // =false: пробовать получить адрес по DHCP,
                       //         в случае неудачи использовать статический;
                       // =true:  сразу использовать статический

    uint8_t ip[] = { 169, 254, 8, 200 };     // Статический IP-адрес
    uint8_t subnet[] = { 255, 255, 0, 0 };   // Маска подсети
    uint8_t gateway[] = { 192, 168, 1, 1 }; // Адрес шлюза
    uint8_t dns[] = { 192, 168, 1, 1 };     // Адрес DNS-сервера (необязателен)

    byte Ethernet::buffer[BUF_SIZE];
    static BufferFiller bfill;  // used as cursor while filling the buffer

    const char okHeader[] PROGMEM = "HTTP/1.0 200 OK\r\n"
                                    "Content-Type: text/html\r\n"
                                    "Pragma: no-cache\r\n"
    ;
    const char authorLink[] PROGMEM =  "</pre><hr>Read about me <a href= 'http://next-telecom.pro'> link </a>"
    ;

    char H[6], T[6], F[6], Hic[6], Hif[6];

    // initialize the library with the numbers of the interface pins
    //                   RS RW E  D4 D5 D6 D7
    LiquidCrystal lcd(2, 3, 4, 5, 6, 7, 8);


    DHT dht(DHTPIN, DHTTYPE);

    void setup(void)
    {
        Serial.begin(57600);
        delay(2000);

    lcd.begin(16, 2);
    // Print a message to the LCD.
    lcd.print("definition IP address");  
      delay(5000);
        /* Проверяем, что контроллер Ethernet доступен для работы */
        Serial.println("Initialising the Ethernet controller");
        if (ether.begin(sizeof Ethernet::buffer, mac, 10) == 0) {
            Serial.println( "Ethernet controller NOT initialised");
            while (true);
        }

        // Пытаемся получить адрес динамически
        Serial.println("Attempting to get an IP address using DHCP");
        if (ether.dhcpSetup()) {
            ether.printIp("Got an IP address using DHCP: ", ether.myip);
            lcd.clear();
            lcd.setCursor(0, 0);
            lcd.print("Got an IP address using DHCP");
        } else {
            // Если DHCP не доступен, используем статический ip-адрес
            ether.staticSetup(ip, gateway, dns);
            ether.printIp("DHCP FAILED, using fixed address: ", ether.myip);
            lcd.clear();
            lcd.setCursor(0, 0);
            lcd.print("NO DHCP");      
            fixed = true;
        }
    }

     


    static void homePage (BufferFiller& buf) {
     
      buf.emit_p(PSTR("$F\r\n"
       "<!DOCTYPE HTML PUBLIC '-//W3C//DTD HTML 4.01 Transitional//EN'\r\n " \
       "'http://www.w3.org/TR/html4/loose.dtd'> \r\n" \
       "<html xmlns='http://www.w3.org/1999/xhtml'> \r\n" \
       "<head> \r\n" \
       " <meta http-equiv='Content-Type' content='text/html; charset=utf-8' /> \r\n" \
       "<title>Arduino WEB term</title>\r\n" \
        "</head> <pre>\r\n"), okHeader);
     
      delay(1000); // на конвертацию
     
      // ищем устройства и выводим результаты
      // Reading temperature or humidity takes about 250 milliseconds!
      // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
      float h = dht.readHumidity(); // Влажность
      // Read temperature as Celsius (the default)
      float t = dht.readTemperature(); // Температура по цельсию
      // Read temperature as Fahrenheit (isFahrenheit = true)
      float f = dht.readTemperature(true); // Видимо температура по фарингейту
     
      if (isnan(h) || isnan(t) || isnan(f)) {
        Serial.println("Failed to read from DHT sensor!"); // Ну если нет никаких значений, значит ошибка
        return;
      }

      // Compute heat index in Fahrenheit (the default)
      float hif = dht.computeHeatIndex(f, h); // Что-то определяется по фарингейту?
      // Compute heat index in Celsius (isFahreheit = false)
      float hic = dht.computeHeatIndex(t, h, false); // Что-то определяется по цельсию....

      delay(2000);
      buf.emit_p(PSTR("<body> <h1>Влажность $D \n</h1>\r\n" \
            "<h1>Температура в Цельсиях $D \n</h1>\r\n" \
            "<h1>Температура по Фарингейту  $D \n</h1>\r\n" \
            "<h1>$D and $D</h1>\r\n </body> \r\n </html>"),
            dtostrf(h,5,2,H), dtostrf(t,5,2,T), dtostrf(f,5,2,F), dtostrf(hic,5,2,Hic), dtostrf(hif,5,2,Hif) );
       
      buf.emit_p(authorLink);
    }


    void loop(void)
    {
      word len = ether.packetReceive();
      word pos = ether.packetLoop(len);
      if (pos) {
        bfill = ether.tcpOffset();
        char* data = (char *) Ethernet::buffer + pos;
        Serial.println(data); // распечатываем запрос для отладки
       
        if (strncmp("GET / ", data, 6) == 0)
          homePage(bfill);
        else
          bfill.emit_p(PSTR(
            "HTTP/1.0 401 Unauthorized\r\n"
            "Content-Type: text/html\r\n"
            "\r\n"
            "<h1>401 Unauthorized</h1>"));
           
        // отправить ответ клиенту
        ether.httpServerReply(bfill.position());
      }

    lcd.setCursor(0, 0);
    lcd.print("IP:");
    for (byte thisByte = 0; thisByte < 4; thisByte++) {
        // print the value of each byte of the IP address:
        lcd.print(ether.myip[thisByte], DEC);
        lcd.print(".");
      }

    // lcd.print(ether.myip,HEX);
    lcd.setCursor(0, 1);
    lcd.print("Gtw:");
    for (byte thisByte = 0; thisByte < 4; thisByte++) {
        // print the value of each byte of the IP address:
        lcd.print(ether.gwip[thisByte], DEC);
        lcd.print(".");
      }
    // lcd.print(ether.gwip,CHR);

      delay(5000);
    }
    И на дисплее всё отражается, и IP присваивается. Но вот как WEB сервер не отвечает.
    Стал разбираться и увидел некоторые "разности" в подключении шилда...
    [​IMG]
    Вот тут занят 2 пин.
    [​IMG]
    А тут 8 пин
    А в редми от шилда
    И так как у меня lcd(2, 3, 4, 5, 6, 7, 8); то я впал в ступор... Может что-то не верно подключил?
    Arduino NANO у меня вставляется прямо в шилд. Всё остальное на макетке.
     

    Вложения:

  2. blackcatw

    blackcatw Нерд

    Кто-нибудь может что-то подсказать?