kaka 发表于 2022-6-3 11:58:40

用esp32通过wifi和processing的通信

拿到了Beetle ESP32-C3的试用,准备做关于一个感应人体播放视频的项目
为了这个项目先做了一些预研。
有了这个小项目
给ESP32烧写程序
/*
*This sketch sends a message to a TCP server
*
*/

#include <WiFi.h>
#include <WiFiMulti.h>

WiFiMulti WiFiMulti;

int k=1;

void setup()
{
    Serial.begin(115200);
    delay(10);
    pinMode(0, INPUT);
    // We start by connecting to a WiFi network
    WiFiMulti.addAP("wifi", "password");

    Serial.println();
    Serial.println();
    Serial.print("Waiting for WiFi... ");

    while(WiFiMulti.run() != WL_CONNECTED) {
      Serial.print(".");
      delay(500);
    }

    Serial.println("");
    Serial.println("WiFi connected");
    Serial.println("IP address: ");
    Serial.println(WiFi.localIP());

    delay(500);
}


void loop()
{
//    const uint16_t port = 80;
//    const char * host = "192.168.1.1"; // ip or dns
    const uint16_t port =10002;
    const char * host = "192.168.1.102"; // ip or dns

    Serial.print("Connecting to ");
    Serial.println(host);

    // Use WiFiClient class to create TCP connections
    WiFiClient client;

    if (!client.connect(host, port)) {
      Serial.println("Connection failed.");
      Serial.println("Waiting 5 seconds before retrying...");
      delay(5000);
      return;
    }

    // This will send a request to the server
    //uncomment this line to send an arbitrary string to the server
    //client.print("Send this data to the server");
    //uncomment this line to send a basic document request to the server
    //client.print("GET /index.html HTTP/1.1\n\n");
   
      client.write(k);
    delay(5000);
    k++;
int maxloops = 0;

//wait for the server's reply to become available
while (!client.available() && maxloops < 1000)
{
    maxloops++;
    delay(1); //delay 1 msec
}
if (client.available() > 0)
{
    //read back one line from the server
    String line = client.readStringUntil('\r');
    Serial.println(line);
}
else
{
    Serial.println("client.available() timed out ");
}

   // Serial.println("Closing connection.");
   // client.stop();

    //Serial.println("Waiting 5 seconds before restarting...");
    //delay(5000);
}然后用processing写一个服务器程序
import processing.net.*;

int port = 10002;      
Server myServer;      

void setup()
{
size(400, 400);
background(0);
myServer = new Server(this, port);
}

void draw()
{
// Get the next available client
Client thisClient = myServer.available();
// If the client is not null, and says something, display what it said
if (thisClient !=null) {
    int whatClientSaid = thisClient.read();
    //if (whatClientSaid != null) {
      println(whatClientSaid);
    //}
}
}来读取esp32传过来的数据。
页: [1]
查看完整版本: 用esp32通过wifi和processing的通信