Nota

Ciao, benvenuto nella Community degli appassionati di SunFounder Raspberry Pi & Arduino & ESP32 su Facebook! Approfondisci Raspberry Pi, Arduino e ESP32 con altri appassionati.

Perché unirsi?

  • Supporto Esperto: Risolvi problemi post-vendita e sfide tecniche con l’aiuto della nostra community e del team.

  • Impara & Condividi: Scambia consigli e tutorial per migliorare le tue competenze.

  • Anteprime Esclusive: Ottieni accesso anticipato alle nuove presentazioni di prodotto e anticipazioni.

  • Sconti Speciali: Approfitta di sconti esclusivi sui nostri prodotti più recenti.

  • Promozioni Festive e Giveaway: Partecipa a giveaway e promozioni speciali per le festività.

👉 Pronto ad esplorare e creare con noi? Clicca [Qui] e unisciti oggi!

LED Controllato via WiFi (Punto di Accesso)

Questo progetto ti permette di controllare una luce LED attraverso un’interfaccia web. La scheda Arduino funge da punto di accesso WiFi, creando una propria rete locale a cui puoi connetterti con un browser web. Una volta connesso, puoi navigare all’indirizzo IP del dispositivo utilizzando il browser web, dove troverai opzioni per accendere e spegnere un LED (collegato al pin 13 della scheda). Il progetto fornisce un feedback in tempo reale sullo stato del LED tramite il Monitor Seriale, rendendo più facile il debug e la comprensione del flusso operativo.

1. Carica il codice

Apri il file 01-wifi_ap.ino nel percorso elite-explorer-kit-main\r4_new_feature\01-wifi_ap, oppure copia questo codice nell”Arduino IDE.

Nota

Il supporto Wi-Fi® è abilitato tramite la libreria integrata WiFiS3 che viene fornita con il nucleo Arduino UNO R4. Installando il nucleo si installa automaticamente la libreria WiFiS3.

È necessario ancora creare o modificare arduino_secrets.h, sostituendo SECRET_SSID e SECRET_PASS con il nome e la password del tuo punto di accesso WiFi. Il file dovrebbe contenere:

// File header arduino_secrets.h
#define SECRET_SSID "tuarete"
#define SECRET_PASS "tuo_password"
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. Spiegazione del codice

  1. Importazione delle Librerie Necessarie

    Importa la libreria WiFiS3 per le funzionalità WiFi e arduino_secrets.h per i dati sensibili come le password.

    #include "WiFiS3.h"
    #include "arduino_secrets.h"
    
  2. Configurazione e Inizializzazione delle Variabili

    Definisci SSID WiFi, password e indice della chiave insieme al pin del LED e allo stato WiFi.

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

    Inizializza la comunicazione seriale e configura il modulo WiFi.

    void setup() {
    
      // ... codice di setup ...
      // Crea il punto di accesso
      status = WiFi.beginAP(ssid, pass);
      // ... gestione degli errori ...
      // avvia il server web sulla porta 80
      server.begin();
    }
    

    Verifichiamo anche se la versione del firmware del WiFi uno R4 è aggiornata. Se non è l’ultima versione, verrà visualizzato un messaggio di aggiornamento. Puoi fare riferimento a Aggiorna il firmware del modulo radio sulla tua scheda UNO R4 WiFi per l’aggiornamento del firmware.

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

    Potresti voler modificare il seguente codice per poter cambiare l’IP predefinito di Arduino.

    WiFi.config(IPAddress(192,48,56,2));
    
  4. Funzione Principale loop()

    La funzione loop() nel codice Arduino esegue diverse operazioni chiave, specificamente:

    1. Verifica se un dispositivo si è connesso o disconnesso dal punto di accesso.

    2. Ascolta i client in arrivo che effettuano richieste HTTP.

    3. Legge i dati del client ed esegue azioni basate su quei dati, come accendere o spegnere un LED.

    Qui, suddividiamo la funzione loop() per rendere questi passaggi più comprensibili.

    1. Verifica dello Stato WiFi

      Il codice verifica innanzitutto se lo stato WiFi è cambiato. Se un dispositivo si è connesso o disconnesso, il monitor seriale visualizzerà le informazioni di conseguenza.

      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. Ascolto dei Client in Arrivo

      WiFiClient client = server.available(); attende i client in arrivo.

      WiFiClient client = server.available();
      
    3. Gestione delle Richieste del Client

      Ascolta i client in arrivo e fornisce loro la pagina HTML. Quando un utente clicca sui link «Clicca qui per accendere il LED» o «Clicca qui per spegnere il LED» sulla pagina web servita, viene inviata una richiesta GET HTTP al server Arduino. In particolare, gli URL «http://tuoIndirizzo/H» per accendere il LED e «http://tuoIndirizzo/L» per spegnerlo verranno utilizzati.

      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>");
        // ...
      }
      

      Il codice Arduino ascolta queste richieste GET in arrivo. Quando rileva GET /H alla fine di una riga in ingresso (intestazione HTTP), imposta il LED collegato al pin 13 su HIGH, accendendolo effettivamente. Allo stesso modo, se rileva GET /L, imposta il LED su LOW, spegnendolo.

      while (client.connected()) {            // loop mentre il client è connesso
        delayMicroseconds(10);                // Questo è necessario per Arduino Nano RP2040 Connect - altrimenti loopa così velocemente che SPI non verrà mai servito.
        if (client.available()) {             // se ci sono byte da leggere dal client,
          char c = client.read();             // leggi un byte, quindi
          Serial.write(c);                    // stampalo sul monitor seriale
          if (c == '\n') {                    // se il byte è un carattere di nuova riga
            ...
            }
            else {      // se hai ricevuto una nuova riga, cancella 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
          }
        }
      

Reference