注釈

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

参加する理由は?

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

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

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

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

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

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

WiFi制御LED(アクセスポイント)

このプロジェクトでは、Webインターフェースを通じてLEDライトを制御することができます。ArduinoボードはWiFiアクセスポイントとして機能し、独自のローカルネットワークを作成します。そのネットワークにWebブラウザで接続すると、ボードのピン13に接続されたLEDをオン/オフするオプションが表示されます。プロジェクトは、シリアルモニターを通じてLEDの状態をリアルタイムでフィードバックし、デバッグと操作の流れを容易に理解できるようにします。

1. コードのアップロード

elite-explorer-kit-main\r4_new_feature\01-wifi_ap のパス下にある 01-wifi_ap.ino ファイルを開くか、このコードを Arduino IDE にコピーします。

注釈

Wi-Fi®サポートは、Arduino UNO R4 Coreに付属の内蔵 WiFiS3 ライブラリを通じて有効になります。コアをインストールすると、 WiFiS3 ライブラリも自動的にインストールされます。

arduino_secrets.h を作成または変更し、 SECRET_SSIDSECRET_PASS をWi-Fiアクセスポイントの名前とパスワードに置き換えます。ファイルには次のように記載されている必要があります:

//arduino_secrets.h header file
#define SECRET_SSID "yournetwork"
#define SECRET_PASS "yourpassword"
arduino_secrets.h
//arduino_secrets.h header file
#define SECRET_SSID "your_ssid"
#define SECRET_PASS "your_password"
01-wifi_ap.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 create a new access point (with no password).
  6  It will then launch a new server and print out the IP address
  7  to the Serial Monitor. From there, you can open that address in a web browser
  8  to turn on and off the LED on pin 13.
  9
 10  If the IP address of your board is yourAddress:
 11    http://yourAddress/H turns the LED on
 12    http://yourAddress/L turns it off
 13
 14  created 25 Nov 2012
 15  by Tom Igoe
 16  adapted to WiFi AP by Adafruit
 17
 18  Find the full UNO R4 WiFi RTC documentation here:
 19  https://docs.arduino.cc/tutorials/uno-r4-wifi/wifi-examples#access-point
 20 */
 21
 22
 23#include "WiFiS3.h"
 24
 25#include "arduino_secrets.h" 
 26
 27///////please enter your sensitive data in the Secret tab/arduino_secrets.h
 28char ssid[] = SECRET_SSID;        // your network SSID (name)
 29char pass[] = SECRET_PASS;        // your network password (use for WPA, or use as key for WEP)
 30int keyIndex = 0;                 // your network key index number (needed only for WEP)
 31
 32int led =  LED_BUILTIN;
 33int status = WL_IDLE_STATUS;
 34WiFiServer server(80);
 35
 36void setup() {
 37  //Initialize serial and wait for port to open:
 38  Serial.begin(9600);
 39  while (!Serial) {
 40    ; // wait for serial port to connect. Needed for native USB port only
 41  }
 42  Serial.println("Access Point Web Server");
 43
 44  pinMode(led, OUTPUT);      // set the LED pin mode
 45
 46  // check for the WiFi module:
 47  if (WiFi.status() == WL_NO_MODULE) {
 48    Serial.println("Communication with WiFi module failed!");
 49    // don't continue
 50    while (true);
 51  }
 52
 53  String fv = WiFi.firmwareVersion();
 54  if (fv < WIFI_FIRMWARE_LATEST_VERSION) {
 55    Serial.println("Please upgrade the firmware");
 56  }
 57
 58  // by default the local IP address will be 192.168.4.1
 59  // you can override it with the following:
 60  WiFi.config(IPAddress(192,48,56,2));
 61
 62  // print the network name (SSID);
 63  Serial.print("Creating access point named: ");
 64  Serial.println(ssid);
 65
 66  // Create open network. Change this line if you want to create an WEP network:
 67  status = WiFi.beginAP(ssid, pass);
 68  if (status != WL_AP_LISTENING) {
 69    Serial.println("Creating access point failed");
 70    // don't continue
 71    while (true);
 72  }
 73
 74  // wait 10 seconds for connection:
 75  delay(10000);
 76
 77  // start the web server on port 80
 78  server.begin();
 79
 80  // you're connected now, so print out the status
 81  printWiFiStatus();
 82}
 83
 84
 85void loop() {
 86  
 87  // compare the previous status to the current status
 88  if (status != WiFi.status()) {
 89    // it has changed update the variable
 90    status = WiFi.status();
 91
 92    if (status == WL_AP_CONNECTED) {
 93      // a device has connected to the AP
 94      Serial.println("Device connected to AP");
 95    } else {
 96      // a device has disconnected from the AP, and we are back in listening mode
 97      Serial.println("Device disconnected from AP");
 98    }
 99  }
100  
101  WiFiClient client = server.available();   // listen for incoming clients
102
103  if (client) {                             // if you get a client,
104    Serial.println("new client");           // print a message out the serial port
105    String currentLine = "";                // make a String to hold incoming data from the client
106    while (client.connected()) {            // loop while the client's connected
107      delayMicroseconds(10);                // This is required for the Arduino Nano RP2040 Connect - otherwise it will loop so fast that SPI will never be served.
108      if (client.available()) {             // if there's bytes to read from the client,
109        char c = client.read();             // read a byte, then
110        Serial.write(c);                    // print it out to the serial monitor
111        if (c == '\n') {                    // if the byte is a newline character
112
113          // if the current line is blank, you got two newline characters in a row.
114          // that's the end of the client HTTP request, so send a response:
115          if (currentLine.length() == 0) {
116            // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
117            // and a content-type so the client knows what's coming, then a blank line:
118            client.println("HTTP/1.1 200 OK");
119            client.println("Content-type:text/html");
120            client.println();
121
122            // the content of the HTTP response follows the header:
123            client.print("<p style=\"font-size:7vw;\">Click <a href=\"/H\">here</a> turn the LED on<br></p>");
124            client.print("<p style=\"font-size:7vw;\">Click <a href=\"/L\">here</a> turn the LED off<br></p>");
125
126            // The HTTP response ends with another blank line:
127            client.println();
128            // break out of the while loop:
129            break;
130          }
131          else {      // if you got a newline, then clear currentLine:
132            currentLine = "";
133          }
134        }
135        else if (c != '\r') {    // if you got anything else but a carriage return character,
136          currentLine += c;      // add it to the end of the currentLine
137        }
138
139        // Check to see if the client request was "GET /H" or "GET /L":
140        if (currentLine.endsWith("GET /H")) {
141          digitalWrite(led, HIGH);               // GET /H turns the LED on
142        }
143        if (currentLine.endsWith("GET /L")) {
144          digitalWrite(led, LOW);                // GET /L turns the LED off
145        }
146      }
147    }
148    // close the connection:
149    client.stop();
150    Serial.println("client disconnected");
151  }
152}
153
154void printWiFiStatus() {
155  // print the SSID of the network you're attached to:
156  Serial.print("SSID: ");
157  Serial.println(WiFi.SSID());
158
159  // print your WiFi shield's IP address:
160  IPAddress ip = WiFi.localIP();
161  Serial.print("IP Address: ");
162  Serial.println(ip);
163
164  // print where to go in a browser:
165  Serial.print("To see this page in action, open a browser to http://");
166  Serial.println(ip);
167
168}

2. コードの説明

  1. 必要なライブラリのインポート

    Wi-Fi機能のための WiFiS3 ライブラリと、パスワードなどの機密データのための arduino_secrets.h をインポートします。

    #include "WiFiS3.h"
    #include "arduino_secrets.h"
    
  2. 設定と変数の初期化

    Wi-Fi SSID、パスワード、キーインデックスを定義すると共に、LEDピンとWi-Fiステータスを初期化します。

    char ssid[] = SECRET_SSID;
    char pass[] = SECRET_PASS;
    int keyIndex = 0;
    int led =  LED_BUILTIN;
    int status = WL_IDLE_STATUS;
    WiFiServer server(80);
    
  3. setup() 関数

    シリアル通信を初期化し、Wi-Fiモジュールを設定します。

    void setup() {
    
      // ... setup code ...
      // Create access point
      status = WiFi.beginAP(ssid, pass);
      // ... error handling ...
      // start the web server on port 80
      server.begin();
    }
    

    また、uno R4 wifiのファームウェアが最新であるかどうかを確認します。最新版でない場合は、アップグレードの促進が表示されます。ファームウェアのアップグレードについては、 UNO R4 WiFiボードのラジオモジュールファームウェアの更新 を参照してください。

    ...
    String fv = WiFi.firmwareVersion();
    if (fv < WIFI_FIRMWARE_LATEST_VERSION) {
        Serial.println("Please upgrade the firmware");
    }
    ...
    

    ArduinoのデフォルトIPを変更するために、以下のコードを修正することも検討してください。

    WiFi.config(IPAddress(192,48,56,2));
    
  4. メイン loop() 関数

    Arduinoのコードにおける loop() 関数はいくつかの重要な操作を行います。具体的には以下のような操作です:

    1. アクセスポイントへのデバイスの接続または切断のチェック。

    2. HTTPリクエストを行うクライアントの受信待ち。

    3. クライアントのデータの読み取りと、そのデータに基づいたアクションの実行(例えば、LEDのオン/オフ)。

    ここで、これらのステップをより理解しやすくするために、 loop() 関数を詳しく見ていきましょう。

    1. Wi-Fiステータスのチェック

      コードは最初にWi-Fiのステータスが変わったかどうかをチェックします。デバイスが接続または切断された場合、シリアルモニターにそれに応じた情報が表示されます。

      if (status != WiFi.status()) {
        status = WiFi.status();
        if (status == WL_AP_CONNECTED) {
          Serial.println("Device connected to AP");
        } else {
          Serial.println("Device disconnected from AP");
        }
      }
      
    2. クライアントの受信待ち

      WiFiClient client = server.available(); はクライアントの受信待ちを行います。

      WiFiClient client = server.available();
      
    3. クライアントリクエストの処理

      クライアントの受信待ちを行い、HTMLウェブページを提供します。ユーザーが提供されたウェブページ上の「Click here to turn the LED on」または「Click here to turn the LED off」というリンクをクリックすると、ArduinoサーバーにHTTP GETリクエストが送信されます。具体的には、LEDを点灯させるためのURL「http://yourAddress/H」と、LEDを消灯させるためのURL「http://yourAddress/L」にアクセスされます。

      WiFiClient client = server.available();
      if (client) {
        // ...
        client.println("HTTP/1.1 200 OK");
        client.println("Content-type:text/html");
        client.println();
        client.print("<p style=\"font-size:7vw;\">Click <a href=\"/H\">here</a> turn the LED on<br></p>");
        client.print("<p style=\"font-size:7vw;\">Click <a href=\"/L\">here</a> turn the LED off<br></p>");
        // ...
      }
      

      ArduinoのコードはこれらのGETリクエストを受信します。受信したテキスト行(HTTPヘッダー)の最後に GET /H と検出した場合、ピン13に接続されたLEDをHIGHに設定し、LEDを点灯させます。同様に、 GET /L と検出した場合、LEDをLOWに設定し、LEDを消灯させます。

      while (client.connected()) {            // loop while the client's connected
        delayMicroseconds(10);                // This is required for the Arduino Nano RP2040 Connect - otherwise it will loop so fast that SPI will never be served.
        if (client.available()) {             // if there's bytes to read from the client,
          char c = client.read();             // read a byte, then
          Serial.write(c);                    // print it out to the serial monitor
          if (c == '\n') {                    // if the byte is a newline character
            ...
            }
            else {      // if you got a newline, then clear currentLine:
              currentLine = "";
            }
          }
          else if (c != '\r') {    // if you got anything else but a carriage return character,
            currentLine += c;      // add it to the end of the currentLine
          }
      
          // Check to see if the client request was "GET /H" or "GET /L":
          if (currentLine.endsWith("GET /H")) {
            digitalWrite(led, HIGH);               // GET /H turns the LED on
          }
          if (currentLine.endsWith("GET /L")) {
            digitalWrite(led, LOW);                // GET /L turns the LED off
          }
        }
      

参照