如何使用http将字符串发送到ESP32

2024-06-14 08:19:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我的python代码应该发送“消息”

import requests
r = requests.post('http://192.168.0.100:7777',data="Hello")
print(r.text)

我的ESP32代码,我认为问题是由于错误的网址,因为我不确定我应该在那里使用什么IP。它是运行python代码的机器的IP吗?还是ESP32的IP?还是我完全错了?在

^{pr2}$

编辑:现在ESP应该充当服务器


Tags: 代码textimportip机器http消息hello
1条回答
网友
1楼 · 发布于 2024-06-14 08:19:00

当您发送GET/POST请求时,您必须输入目的地的IP,在本例中,是您的ESP32的IP。在

首先要注意的是,我的服务器.begin默认情况下,()正在作为访问点侦听192.168.4.1:80。在

现在,要创建一个异步服务器来保存带有json数据的GET和POST请求,可以使用如下函数:

文件http_server.h:

#include "WiFi.h"
#include "ESPAsyncWebServer.h"
#include "ArduinoJson.h"

#ifndef _HTTP_SERVER_
#define _HTTP_SERVER_

void setup_http_server();

#endif

文件http示例_服务器.cpp公司名称:

^{pr2}$

最后,如果您想通过移动/计算机直接连接到您的ESP32,则需要将其wifi连接配置为ACCESS_POINT。所以,你的setup()和{}在你的main.ino中可能看起来像:

文件主.ino公司名称:

#include "http_server.h"

void setup(){
     Serial.begin(9600);  // setup serial communication
     // Set WiFi to station(STA) and access point (AP) mode simultaneously 
     WiFi.mode(WIFI_AP_STA);
     delay(100); // Recommended delay
     WiFi.softAP("choose_some_ssid", "choose_some_password");

     // Remember to configure the previous server
     setup_http_server();  // starts the asyncronus https server*/
}

void loop(){
     delay(1000);
}

仅此而已。要检查一切是否正常,您可以使用密码chose_some_password将手机连接到wifi choose_some_ssid,打开浏览器并转到192.168.4.1/get_data,您将得到“我在这里”作为响应。在

正如您在问题中所说,如果您想用python发送帖子,您可以:

import requests
r = requests.post('http://192.168.4.1:80/set_data', data="{'number':55}") // remember that you get the keyword 'number' in the server side
print(r.text) // should print "Some message"

更多信息可在https://techtutorialsx.com/2018/10/12/esp32-http-web-server-handling-body-data/上找到 希望有帮助!在

相关问题 更多 >