Below is both a sketch and Python script to implement a simple UDP server residing on your PC and a client residing on the Arduino R4 WIFI.
Client Sketch
/*
WiFi UDP Send data
*/
#include <WiFiS3.h>
int status = WL_IDLE_STATUS;
char ssid[] = ""; // your network SSID (name)
char pass[] = ""; // your network password (use for WPA, or use as key for WEP)
char remote_pc_ip[] = "192.168.1.231";
int keyIndex = 0; // your network key index number (needed only for WEP)
char SendBuffer[] = "1"; // a string to send back
WiFiUDP Udp;
void setup() {
//Initialize serial and wait for port to open:
Serial.begin(115200);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
// check for the WiFi module:
if (WiFi.status() == WL_NO_MODULE) {
Serial.println("Communication with WiFi module failed!");
// don't continue
while (true)
;
}
String fv = WiFi.firmwareVersion();
if (fv < WIFI_FIRMWARE_LATEST_VERSION) {
Serial.println("Please upgrade the firmware");
}
// 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");
Serial.println("\nStarting connection to server...");
// if you get a connection, report back via serial:
Udp.begin(50008);
}
void loop() {
// if there's data available, read a packet
// send a reply, to the IP address and port that sent us the packet we received
Udp.beginPacket(remote_pc_ip, 50007);
Udp.write(SendBuffer);
Udp.endPacket();
SendBuffer[0]++;
delay(1000);
}
Before compiling and uploading, you must enter your SSID, password, and PC IP address at the top of the sketch.
Python Server
import socket
ServerSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
host = '0.0.0.0'
port = 50007
try:
ServerSocket.bind((host, port))
except socket.error as e:
print(str(e))
while True:
data, address = ServerSocket.recvfrom(2048)
data_str = data.decode('utf-8')
try:
# print(f"data : {data_str}, address : {address}")
print(f'data received: {data_str}')
except:
print(f"invalid value, data : {data_str}, address : {address}")
if not data:
print("no data")
break
connection.close()
No modifications are necessary for the server.
Start the server and then power up the Uno R4. The value should increase by one every second.