注釈

こんにちは、SunFounderのRaspberry Pi & Arduino & ESP32愛好家コミュニティへようこそ!Facebook上でRaspberry Pi、Arduino、ESP32についてもっと深く掘り下げ、他の愛好家と交流しましょう。

参加する理由は?

  • エキスパートサポート:コミュニティやチームの助けを借りて、販売後の問題や技術的な課題を解決します。

  • 学び&共有:ヒントやチュートリアルを交換してスキルを向上させましょう。

  • 独占的なプレビュー:新製品の発表や先行プレビューに早期アクセスしましょう。

  • 特別割引:最新製品の独占割引をお楽しみください。

  • 祭りのプロモーションとギフト:ギフトや祝日のプロモーションに参加しましょう。

👉 私たちと一緒に探索し、創造する準備はできていますか?[ ここ]をクリックして今すぐ参加しましょう!

シンプルなWebサーバー

このシンプルなArduinoプログラムは、基本的なWiFiウェブサーバーを作成するように設計されており、ユーザーはウェブブラウザを介してArduinoボード上のLEDのオンとオフを制御できます。

コードの実行

注釈

  • ファイル 01_simple_webserver.inoelite-explorer-kit-main\iot_project\01_simple_webserver のパスから直接開くことができます。

  • または、このコードをArduino IDEにコピーしてください。

注釈

コード内で、SSIDとパスワードは arduino_secrets.h に格納されています。この例をアップロードする前に、自分のWiFiの認証情報でそれらを修正する必要があります。さらに、コードを共有または保存する際には、この情報を機密に保つためのセキュリティ対策を講じてください。

arduino_secrets.h
#define SECRET_SSID "your_ssid"        // your network SSID (name)
#define SECRET_PASS "your_password"        // your network password (use for WPA, or use as key for WEP)
01_simple_webserver.ino
  1/*
  2  WiFi Web Server LED Blink
  3
  4  A simple web server that lets you blink an LED via the web.
  5  This sketch will print the IP address of your WiFi module (once connected)
  6  to the Serial Monitor. From there, you can open that address in a web browser
  7  to turn on and off the LED_BUILTIN.
  8
  9  If the IP address of your board is yourAddress:
 10  http://yourAddress/H turns the LED on
 11  http://yourAddress/L turns it off
 12
 13  This example is written for a network using WPA encryption. For
 14  WEP or WPA, change the WiFi.begin() call accordingly.
 15
 16  Circuit:
 17  * Board with NINA module (Arduino MKR WiFi 1010, MKR VIDOR 4000 and Uno WiFi Rev.2)
 18  * LED attached to pin 9
 19
 20  created 25 Nov 2012
 21  by Tom Igoe
 22
 23  Find the full UNO R4 WiFi Network documentation here:
 24  https://docs.arduino.cc/tutorials/uno-r4-wifi/wifi-examples#simple-webserver
 25 */
 26
 27#include "WiFiS3.h"
 28
 29#include "arduino_secrets.h" 
 30///////please enter your sensitive data in the Secret tab/arduino_secrets.h
 31char ssid[] = SECRET_SSID;        // your network SSID (name)
 32char pass[] = SECRET_PASS;    // your network password (use for WPA, or use as key for WEP)
 33int keyIndex = 0;                 // your network key index number (needed only for WEP)
 34
 35int led =  LED_BUILTIN;
 36int status = WL_IDLE_STATUS;
 37WiFiServer server(80);
 38
 39void setup() {
 40  Serial.begin(9600);      // initialize serial communication
 41  pinMode(led, OUTPUT);      // set the LED pin mode
 42
 43  // check for the WiFi module:
 44  if (WiFi.status() == WL_NO_MODULE) {
 45    Serial.println("Communication with WiFi module failed!");
 46    // don't continue
 47    while (true);
 48  }
 49
 50  String fv = WiFi.firmwareVersion();
 51  if (fv < WIFI_FIRMWARE_LATEST_VERSION) {
 52    Serial.println("Please upgrade the firmware");
 53  }
 54
 55  // attempt to connect to WiFi network:
 56  while (status != WL_CONNECTED) {
 57    Serial.print("Attempting to connect to Network named: ");
 58    Serial.println(ssid);                   // print the network name (SSID);
 59
 60    // Connect to WPA/WPA2 network. Change this line if using open or WEP network:
 61    status = WiFi.begin(ssid, pass);
 62    // wait 10 seconds for connection:
 63    delay(10000);
 64  }
 65  server.begin();                           // start the web server on port 80
 66  printWifiStatus();                        // you're connected now, so print out the status
 67}
 68
 69
 70void loop() {
 71  WiFiClient client = server.available();   // listen for incoming clients
 72
 73  if (client) {                             // if you get a client,
 74    Serial.println("new client");           // print a message out the serial port
 75    String currentLine = "";                // make a String to hold incoming data from the client
 76    while (client.connected()) {            // loop while the client's connected
 77      if (client.available()) {             // if there's bytes to read from the client,
 78        char c = client.read();             // read a byte, then
 79        Serial.write(c);                    // print it out to the serial monitor
 80        if (c == '\n') {                    // if the byte is a newline character
 81
 82          // if the current line is blank, you got two newline characters in a row.
 83          // that's the end of the client HTTP request, so send a response:
 84          if (currentLine.length() == 0) {
 85            // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
 86            // and a content-type so the client knows what's coming, then a blank line:
 87            client.println("HTTP/1.1 200 OK");
 88            client.println("Content-type:text/html");
 89            client.println();
 90
 91            // the content of the HTTP response follows the header:
 92            client.print("<p style=\"font-size:7vw;\">Click <a href=\"/H\">here</a> turn the LED on<br></p>");
 93            client.print("<p style=\"font-size:7vw;\">Click <a href=\"/L\">here</a> turn the LED off<br></p>");
 94            
 95            // The HTTP response ends with another blank line:
 96            client.println();
 97            // break out of the while loop:
 98            break;
 99          } else {    // if you got a newline, then clear currentLine:
100            currentLine = "";
101          }
102        } else if (c != '\r') {  // if you got anything else but a carriage return character,
103          currentLine += c;      // add it to the end of the currentLine
104        }
105
106        // Check to see if the client request was "GET /H" or "GET /L":
107        if (currentLine.endsWith("GET /H")) {
108          digitalWrite(LED_BUILTIN, HIGH);               // GET /H turns the LED on
109        }
110        if (currentLine.endsWith("GET /L")) {
111          digitalWrite(LED_BUILTIN, LOW);                // GET /L turns the LED off
112        }
113      }
114      
115    }
116    // close the connection:
117    client.stop();
118    Serial.println("client disconnected");
119  }
120}
121
122void printWifiStatus() {
123  // print the SSID of the network you're attached to:
124  Serial.print("SSID: ");
125  Serial.println(WiFi.SSID());
126
127  // print your board's IP address:
128  IPAddress ip = WiFi.localIP();
129  Serial.print("IP Address: ");
130  Serial.println(ip);
131
132  // print the received signal strength:
133  long rssi = WiFi.RSSI();
134  Serial.print("signal strength (RSSI):");
135  Serial.print(rssi);
136  Serial.println(" dBm");
137  // print where to go in a browser:
138  Serial.print("To see this page in action, open a browser to http://");
139  Serial.println(ip);
140}

コードをアップロードした後、シリアルモニタでIPアドレスを確認できます。このIPアドレスをウェブブラウザに入力することで、オンボードLEDをオン/オフに切り替えることができます。

../_images/01_webserver.png

どのように動作するのか?

以下はコードの説明です:

  1. ヘッダーファイルとグローバル変数:

    • #include 「WiFiS3.h」:WiFi接続および管理のためのWiFiライブラリを含みます。このライブラリはArduino UNO R4 Coreに含まれているので、追加のインストールは必要ありません。

    • #include 「arduino_secrets.h」:SSIDやパスワードなどの機密WiFi接続データを含みます。

    • ssid , pass , keyIndex:WiFi接続に使用されるネットワーク認証情報です。

    • led , status , server:LEDピン、WiFiステータス、ウェブサーバーオブジェクトを定義します。

  2. setup()

    • シリアル通信を開始します。

    • WiFiモジュールの存在を確認します。

    • WiFiモジュールのファームウェアバージョンが最新であるかを確認します。

    • WiFiネットワークに接続を試みます。

    • ウェブサーバーを開始します。

    • WiFiステータスを印刷します。

  3. loop()

    • 新しいウェブクライアント接続をチェックします。

    • クライアント接続がある場合は、そのHTTPリクエストを読み取ります。

    • リクエストに基づいて、LEDのオン/オフ状態を制御します。たとえば、リクエストが「GET /H」の場合はLEDをオンにし、「GET /L」の場合はオフにします。

    • HTTPレスポンスを送信して、LEDの制御方法をユーザーに指示します。

    • クライアントを切断します。

  4. printWifiStatus()

    • 接続されているWiFi SSIDを印刷します。

    • ArduinoボードのIPアドレスを印刷します。

    • 受信した信号強度を印刷します。

    • ウェブブラウザでこのページを表示する方法を説明します。