udp-diffusion.ino

Arduino MKR WiFi 1010 · File : udp-diffusion.ino · Language : Arduino · Use case : Découvrir et discuter entre cartes sur le LAN

Several MKR WiFi 1010 boards on the same network can discover each other without a server: this sketch broadcasts an announcement every five seconds over UDP and prints the neighbours'. The base of a local sensor mesh or peer-to-peer home automation.

Hardware

An Arduino MKR WiFi 1010 (SAMD21 microcontroller, WINC1500 Wi-Fi module, no Bluetooth, USB or LiPo power on J6). Two MKR WiFi 1010 boards (or one board + a test PC) on the same WiFi LAN.

Wiring

No wiring; 255.255.255.255 broadcast works on classic home WiFi (not on client-isolated networks).

How it works

WiFiUDP binds port 4210; parsePacket reads incoming announcements, beginPacket to the broadcast address sends to all. The uptime spots a board that keeps rebooting.

Running it

Install Arduino SAMD Boards and the WiFi101 library, select the board, upload. Wi-Fi runs on 2.4 GHz only: check that your access point is not 5 GHz only.

Variants

Replace broadcast with a 239.x multicast address to cross some routers, or add a role election to designate a relay.

udp-diffusion.ino

// Decouverte par broadcast UDP : les MKR WiFi s'annoncent toutes les 5 s.
// Trame : "mkr-<ip courte>;<uptime>" sur le port 4210.
#include <SPI.h>
#include <WiFi101.h>

const char SSID[] = "MonReseau";
const char PASS[] = "motdepassewifi";

WiFiUDP udp;
const int PORT = 4210;
unsigned long dernier = 0;

void setup() {
  Serial.begin(9600);
  WiFi.begin(WPA_PASS_PHRASE, SSID, PASS);
  while (WiFi.status() != WL_CONNECTED) delay(100);
  Serial.println(WiFi.localIP());
  udp.begin(PORT);
}

void loop() {
  // 1) écho des annonces recues
  int taille = udp.parsePacket();
  if (taille) {
    char buf[64];
    int n = udp.read(buf, sizeof(buf) - 1);
    buf[n > 0 ? n : 0] = 0;
    Serial.print(udp.remoteIP());
    Serial.print(" : ");
    Serial.println(buf);
  }
  // 2) annonce periodique en broadcast
  if (millis() - dernier >= 5000) {
    dernier = millis();
    udp.beginPacket(IPAddress(255, 255, 255, 255), PORT);
    udp.print("mkr-");
    udp.print(WiFi.localIP()[3]);
    udp.print(";up=");
    udp.print(millis() / 1000);
    udp.endPacket();
  }
}

← Back to the board