In this lesson, we show an improved framework for creating a Client/Server connection between your Arduino and your desktop PC over WiFi. This will serve as the basis for our WiFi projects moving forward. On the arduino side, we have the following code to create the Server:
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 |
#include <WiFiS3.h> #include "secrets.h" WiFiUDP udp; int PORT = 12345; String myString; String stringArray[10]; String response = "ACK"; void setup() { Serial.begin(9600); Serial.print("Connecting to "); Serial.println(mySSID); WiFi.begin(mySSID, myPASS); while (WiFi.status() != WL_CONNECTED) { delay(100); Serial.print("."); } Serial.println("\nConnected to WiFi"); Serial.println(WiFi.localIP()); udp.begin(PORT); Serial.print("UDP Server started on port "); Serial.print(PORT); // put your setup code here, to run once: } void splitString() { int startIndex = 0; int indexCount = 0; int i; int j; myString = myString + ':'; for (i = 0; i < myString.length(); i = i + 1) { if (myString[i] == ':') { stringArray[indexCount] = myString.substring(startIndex, i); indexCount = indexCount + 1; startIndex = i + 1; } } for (j = 0; j < indexCount; j = j + 1) { Serial.println(stringArray[j]); } } void loop() { // put your main code here, to run repeatedly: if (udp.parsePacket()) { myString = udp.readStringUntil('\n'); Serial.println("Received : " + myString); udp.beginPacket(udp.remoteIP(), udp.remotePort()); udp.print(response); udp.endPacket(); Serial.println("SENT: " + response); splitString(); } } |
Remember, you must create a new tab, and include the following as your ‘secrets.h’ file
1 2 |
#define mySSID "YOUR WIFI NAME" #define myPASS "YOUR WIFI PASSWORD" |
And then, on the Desktop side, this will be your python ‘Client’ code:
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 |
import socket # Arduino’s IP address (from Arduino Serial Monitor) HOST = "192.168.88.33" # Use Your Arduino's IP. It will print when #You Run the Arduino Server Program PORT = 12345 # Must match Arduino’s UDP port # Create a UDP socket mySocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) mySocket.settimeout(5.0) # 5 seconds timeout for responses print("UDP Client started. Enter Data (or 'quit' to exit).") while True: # Prompt for Data myData = input("Enter Data String: ") if myData.lower() == 'quit': # Exit condition break # Send Data to the server myData=myData+'\n' myDataEncoded=myData.encode() mySocket.sendto(myDataEncoded, (HOST, PORT)) print('Sent '+myData+' to HOST',HOST,PORT) # Try to get a response, skip on timeout try: response, server_address = mySocket.recvfrom(1024) print("Server response:", response.decode()) except socket.timeout: print("No response received from server within 5 seconds") # Close the socket mySocket.close() print("Socket closed") |