Oggi vediamo come avvicinarci al mondo dell'Internet of Things (IoT) con Arduino, in particolare utilizzando un Arduino MKR1000 (o più probabilmente Genuino MKR1000 dato che siamo in Europa, tranquilli sono identici).
Questa piccola board è in commercio da circa un anno al costo di 30/40€ ed offre come vantaggi principali:
- Dimensioni contenute
- WiFi
- Bassi consumi
- Alimentazione sia tramite USB che tramite batteria LiPo
MKR1000 infatti ha un formato poco più grande di un Arduino Nano ma è basato sul System On Chip Atmel ATSAMW25, pensato proprio per il mondo IoT grazie all'integrazione del chip WiFi WINC1500. Ho trovato molto interessante la combinazione di fattore di forma ridotto, WiFi e possibilità di utilizzare una batteria LiPo per l'alimentazione (batteria a singola cella, 3.7V, 700mAh minimo). Questo permette di realizzare dispositivi contenuti ad alto potenziale capaci di interagire facilmente con l'ambiente che li circonda.
Installazione
Per iniziare ad usare la scheda, colleghiamola al computer con un cavo USB e utilizzando l'IDE Arduino (se non lo avete scaricatelo QUI) installiamo il supporto per le board SAMD. Per farlo occorre aprire il board manager da Tools->Boards->Board Manager e cercare "SAMD".
Se siete su Linux o OSX non dovrete installare alcun driver, se invece siete sotto Windows occorre un passo aggiuntivo: tramite il pannello di controllo andare su "Sistema e Sicurezza" e aprire il Device Manager. Sotto la voce "Porte" comparirà un dispositivo seriale: clicchiamoci con il tasto destro del mouse e scegliamo di aggiornare i driver. Tramite la ricerca manuale rechiamoci nella cartella dell'Arduino IDE e selezioniamo la cartella "Driver". Questo dovrebbe bastare per far riconoscere a Windows la vostra board.
To the Internet!
Siamo quasi pronti, a breve potremo mandare Arduino online! Nell'IDE impostiamo la board corretta (Tools->Board->Arduino/Genuino MKR1000) e scegliamo la porta COM corrispondente (Tools->Port).
L'Arduino e l'IDE sono già configurati, potete provare uno dei classici esempi (File->Esempi->Basic->Blink è il più semplice ed immediato) per verificarne il corretto funzionamento. Per rendere le cose più interessanti però installiamo la libreria WiFi101 cercandola nel "Library Manager" che si trova sotto Sketch->Include Library->Manage Libraries. Cercando "WiFi101" troverete la libreria corrispondente che vi aprirà le porte di internet.
Con la libreria installata, avremo accesso anche a svariati esempi interessanti. Vediamone un paio.
Scanner Wifi
Apriamo il file Esempi->WiFi101->ScanNetwork. Questo esempio ci insegna a trovare il MAC address del nostro dispositivo e ad effettuare una scansione delle reti disponibili. Il codice è riportato di seguito per semplicità.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 |
#include <SPI.h> #include <WiFi101.h> void setup() { //Initialize serial and wait for port to open: Serial.begin(9600); while (!Serial) { ; // wait for serial port to connect. Needed for native USB port only } // check for the presence of the shield: if (WiFi.status() == WL_NO_SHIELD) { Serial.println("WiFi shield not present"); // don't continue: while (true); } // Print WiFi MAC address: printMacAddress(); // scan for existing networks: Serial.println("Scanning available networks..."); listNetworks(); } void loop() { delay(10000); // scan for existing networks: Serial.println("Scanning available networks..."); listNetworks(); } void printMacAddress() { // the MAC address of your WiFi shield byte mac[6]; // print your MAC address: WiFi.macAddress(mac); Serial.print("MAC: "); Serial.print(mac[5], HEX); Serial.print(":"); Serial.print(mac[4], HEX); Serial.print(":"); Serial.print(mac[3], HEX); Serial.print(":"); Serial.print(mac[2], HEX); Serial.print(":"); Serial.print(mac[1], HEX); Serial.print(":"); Serial.println(mac[0], HEX); } void listNetworks() { // scan for nearby networks: Serial.println("** Scan Networks **"); int numSsid = WiFi.scanNetworks(); if (numSsid == -1) { Serial.println("Couldn't get a wifi connection"); while (true); } // print the list of networks seen: Serial.print("number of available networks:"); Serial.println(numSsid); // print the network number and name for each network found: for (int thisNet = 0; thisNet < numSsid; thisNet++) { Serial.print(thisNet); Serial.print(") "); Serial.print(WiFi.SSID(thisNet)); Serial.print("\tSignal: "); Serial.print(WiFi.RSSI(thisNet)); Serial.print(" dBm"); Serial.print("\tEncryption: "); printEncryptionType(WiFi.encryptionType(thisNet)); Serial.flush(); } } void printEncryptionType(int thisType) { // read the encryption type and print out the name: switch (thisType) { case ENC_TYPE_WEP: Serial.println("WEP"); break; case ENC_TYPE_TKIP: Serial.println("WPA"); break; case ENC_TYPE_CCMP: Serial.println("WPA2"); break; case ENC_TYPE_NONE: Serial.println("None"); break; case ENC_TYPE_AUTO: Serial.println("Auto"); break; } } |
Come codice è piuttosto semplice da comprendere e la libreria farà la maggior parte del lavoro per noi. Per ottenere l'indirizzo MAC basta utilizzare:
1 |
WiFi.macAddress(mac); |
Mentre per trovare le reti disponibili:
1 |
WiFi.scanNetworks(); |
Questa funzione ritorna il numero di reti rilevate e poi tramite i metodi WiFi.SSID(), WiFi.RSSI() e WiFi.encryptionType() potremo andare a vedere i dettagli delle singole reti (SSID, potenza del segnale e sicurezza) semplicemente passando un indice come parametro.
Connessione WiFi
Facciamo il grande passo: colleghiamoci ad una rete WiFi e scarichiamo un pagina da internet. Apriamo lo sketch Esempi->WiFi101->WiFiWebCient (riportato qui sotto).
Nelle prime righe occorre impostare il nome della rete e la password nelle variabili "ssid" e "pass" e sarete in grado di connettervi. Lo sketch tenterà quindi di stabilire una connessione con "www.google.com" e di fare una richiesta in GET. La risposta sarà quindi stampata sulla seriale.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 |
#include #include char ssid[] = "yourNetwork"; // your network SSID (name) char pass[] = "secretPassword"; // your network password (use for WPA, or use as key for WEP) int keyIndex = 0; // your network key Index number (needed only for WEP) int status = WL_IDLE_STATUS; // if you don't want to use DNS (and reduce your sketch size) // use the numeric IP instead of the name for the server: //IPAddress server(74,125,232,128); // numeric IP for Google (no DNS) char server[] = "www.google.com"; // name address for Google (using DNS) // Initialize the Ethernet client library // with the IP address and port of the server // that you want to connect to (port 80 is default for HTTP): WiFiClient client; void setup() { //Initialize serial and wait for port to open: Serial.begin(9600); while (!Serial) { ; // wait for serial port to connect. Needed for native USB port only } // check for the presence of the shield: if (WiFi.status() == WL_NO_SHIELD) { Serial.println("WiFi shield not present"); // don't continue: while (true); } // attempt to connect to WiFi network: while (status != WL_CONNECTED) { Serial.print("Attempting to connect to SSID: "); Serial.println(ssid); // Connect to WPA/WPA2 network. Change this line if using open or WEP network: status = WiFi.begin(ssid, pass); // wait 10 seconds for connection: delay(10000); } Serial.println("Connected to wifi"); printWiFiStatus(); Serial.println("\nStarting connection to server..."); // if you get a connection, report back via serial: if (client.connect(server, 80)) { Serial.println("connected to server"); // Make a HTTP request: client.println("GET /search?q=arduino HTTP/1.1"); client.println("Host: www.google.com"); client.println("Connection: close"); client.println(); } } void loop() { // if there are incoming bytes available // from the server, read them and print them: while (client.available()) { char c = client.read(); Serial.write(c); } // if the server's disconnected, stop the client: if (!client.connected()) { Serial.println(); Serial.println("disconnecting from server."); client.stop(); // do nothing forevermore: while (true); } } void printWiFiStatus() { // print the SSID of the network you're attached to: Serial.print("SSID: "); Serial.println(WiFi.SSID()); // print your WiFi shield's IP address: IPAddress ip = WiFi.localIP(); Serial.print("IP Address: "); Serial.println(ip); // print the received signal strength: long rssi = WiFi.RSSI(); Serial.print("signal strength (RSSI):"); Serial.print(rssi); Serial.println(" dBm"); } |
Con gli esempi che abbiamo visto dovreste essere in grado di iniziare a sviluppare in breve tempo i vostri progetti IoT. Fateci sapere nei commenti tutte le vostre idee più creative!