ESP32 使用WIFI UDP协议通信
- ESP32主: 读取光敏传感器数值, 并通过UDP发送
- ESP32从: 读取主机发送的数值, 并显示在OLED显示屏上
实际效果
- 左边为ESP32, 连接OLED, 为STA模式从机
- 右边为ESP32, 连接光敏传感器, 为AP+STA主机, 可连接外网和连接从机
ESP32 主 - AP/STA 发送数据
文章来源:https://www.toymoban.com/news/detail-538490.html
#define STASSID "209"
#define STAPSK "xinxi209"
#include <WiFi.h>
#include <WiFiUDP.h>
const char AP_NameChar[] = "WIFI-SSID";
const char WiFiAPPSK[] = "WIFI-PSK";
IPAddress ESP8266ip1(192,168,4,2);
IPAddress ESP8266ip2(192,168,4,3);
IPAddress ESP8266ip(192,168,4,255);
unsigned int localPort =8080;
unsigned int remotePort=8080;
char incomingPacket[537];
char A;
WiFiUDP Udp;
volatile int lightData;
void setup(){
Serial.begin(9600);
WiFi.mode(WIFI_AP_STA);
WiFi.softAP(AP_NameChar, WiFiAPPSK);
WiFi.begin(STASSID, STAPSK);
Udp.begin(localPort);
Serial.println();
Serial.println("Started ap. Local ip: " + WiFi.localIP().toString());
lightData = -1;
pinMode(36, INPUT);
pinMode(36, INPUT);
Serial.begin(9600);
}
void loop(){
lightData = 100 - round((String(analogRead(36)).toInt() / 4095.0) * 100);
Serial.println(lightData);
if (lightData < 40) {
Udp.beginPacket("192.168.4.2",remotePort);
Udp.print(lightData);
Udp.endPacket();
} else {
Udp.beginPacket("192.168.4.2",remotePort);
Udp.print(lightData);
Udp.endPacket();
}
delay(1000);
}
ESP32 从 - STA 接受数据显示数据
文章来源地址https://www.toymoban.com/news/detail-538490.html
#define STASSID "WIFI-SSID"
#define STAPSK "WIFI-PSK"
#include <WiFi.h>
#include <WiFiUdp.h>
#include <U8g2lib.h>
#include <SPI.h>
unsigned int localPort =8080;
unsigned int remotePort=8080;
char incomingPacket[537];
char A;
WiFiUDP Udp;
U8G2_SSD1306_128X64_NONAME_1_4W_SW_SPI u8g2(U8G2_R0, 18,23,4, 16, 17);
String lightData;
void page1() {
u8g2.setFont(u8g2_font_timR24_tf);
u8g2.setFontPosTop();
u8g2.setCursor(0,20);
u8g2.print(lightData);
}
void setup(){
Serial.begin(9600);
WiFi.mode(WIFI_STA);
WiFi.begin(STASSID, STAPSK);
while (WiFi.status() != WL_CONNECTED)
{
Serial.print(".");
delay(500);
}
delay(1000);
Serial.println();
Serial.print("Connected! IP address: ");
Serial.println(WiFi.localIP());
Serial.printf("UDP server on port ", localPort);
Udp.begin(localPort);
u8g2.begin();
lightData = "-1";
u8g2.firstPage();
do
{
page1();
}while(u8g2.nextPage());
u8g2.enableUTF8Print();
}
void loop(){
int packetSize = Udp.parsePacket();
if (packetSize)
{
Serial.printf("Received %d bytes from %s, port %d\n", packetSize, Udp.remoteIP().toString().c_str(), Udp.remotePort());
int len = Udp.read(incomingPacket, 536);
if (len > 0)
{
incomingPacket[len] = 0;
Serial.printf("UDP packet contents: %s\n", incomingPacket);
String COM=incomingPacket;
lightData = COM;
u8g2.firstPage();
do
{
page1();
}while(u8g2.nextPage());
}
}
}
到了这里,关于ESP32 直接使用WIFI进行UDP通信, 将光敏电阻传感器数值, 显示在OLED上 - 米思齐/Arduino的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!