Nota
Ciao, benvenuto nella community SunFounder Raspberry Pi & Arduino & ESP32 Enthusiasts su Facebook! Approfondisci Raspberry Pi, Arduino ed ESP32 con altri appassionati.
Perché unirsi?
Supporto Esperto: Risolvi problemi post-vendita e sfide tecniche con l’aiuto della nostra community e del nostro team.
Impara & Condividi: Scambia consigli e tutorial per migliorare le tue competenze.
Anteprime Esclusive: Ottieni l’accesso anticipato agli annunci di nuovi prodotti e anteprime esclusive.
Sconti Speciali: Goditi sconti esclusivi sui nostri prodotti più recenti.
Promozioni e Concorsi Festivi: Partecipa a concorsi e promozioni festive.
👉 Pronto a esplorare e creare con noi? Clicca [Qui] e unisciti oggi stesso!
Simple Webserver
Questo semplice programma Arduino è progettato per creare un server web WiFi di base, permettendo agli utenti di controllare lo stato di accensione e spegnimento di un LED sulla scheda Arduino tramite un browser web.
Esegui il Codice
Nota
Puoi aprire il file
01_simple_webserver.inonel percorsoelite-explorer-kit-main\iot_project\01_simple_webserverdirettamente.Oppure copia questo codice nell’IDE Arduino.
Nota
Nel codice, SSID e password sono memorizzati in arduino_secrets.h. Prima di caricare questo esempio, devi modificarli con le tue credenziali WiFi. Inoltre, per motivi di sicurezza, assicurati che queste informazioni siano mantenute riservate quando condividi o memorizzi il codice.
#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)
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}
Dopo aver caricato il codice, sarai in grado di vedere l’indirizzo IP nel monitor seriale. Puoi inserire questo indirizzo IP nel tuo browser web per accendere/spegnere il LED integrato.
Come funziona?
Ecco una spiegazione del codice:
File di Intestazione e Variabili Globali:
#include "WiFiS3.h": Include la libreria WiFi per la connessione e la gestione del WiFi. Questa libreria è inclusa con Arduino UNO R4 Core, quindi non è necessaria un’installazione aggiuntiva.#include "arduino_secrets.h": Include i dati sensibili di connessione WiFi come SSID e password.ssid,pass,keyIndex: Queste sono le credenziali di rete utilizzate per la connessione WiFi.led,status,server: Definiscono il pin del LED, lo stato del WiFi e l’oggetto del server web.
setup():Inizia la comunicazione seriale.
Verifica la presenza del modulo WiFi.
Controlla se la versione del firmware del modulo WiFi è aggiornata.
Tenta di connettersi alla rete WiFi.
Avvia il server web.
Stampa lo stato del WiFi.
loop():Controlla nuove connessioni client web.
Se ci sono connessioni client, legge le loro richieste HTTP in arrivo.
In base alle richieste, puoi controllare lo stato di accensione/spegnimento del LED. Ad esempio, se la richiesta è «GET /H,» accenderà il LED; se è «GET /L,» spegnerà il LED.
Invia una risposta HTTP per istruire l’utente su come controllare il LED.
Disconnetti il client.
printWifiStatus():Stampa l’SSID del WiFi connesso.
Stampa l’indirizzo IP della scheda Arduino.
Stampa l’intensità del segnale ricevuto.
Spiega come visualizzare questa pagina in un browser web.