使用ESP_NOW与循环和延迟



我正试图从一个esp32接收数据到另一个。我还用delays做了一些looping,用于读取传感器数据和开关继电器冷却。该设备还使用ESPAsyncWebServer作为API服务器(不包括在代码的大小)。我正在接收POST请求API中的一个eps32的数据。我想改变这一点,以便能够接收esp_now。我正在做一些实验,但由于delay方法在循环中,数据接收延迟。是否有一种方法可以使这个异步,例如上面的ESPA?

我还尝试了一种比较milis()(时间)来等待循环的方法,但我认为这太"消耗资源"了。任务,让它像漩涡一样永远在循环中全速比较。

是我的循环它只是一个带有一些变量和延迟函数的简单循环,例如


void loop() {
if (WiFi.status() == WL_CONNECTED) {
float temp_check = dht.readTemperature();
if (temp_check == 0) {
delay(1000);
temp_check = dht.readTemperature();
}
if (temp_check > 32.0 && *cooling_switch_p == false) {
Serial.println("[ INF ] Too high temperature, switch on a cooling system");
digitalWrite(COOLING_RELAY, LOW);
*cooling_switch_p = true;
}
else if (temp_check < 30.0  && *cooling_switch_p == true) {
Serial.println("[ INF ] Normal temperature, switch off a cooling system");
digitalWrite(COOLING_RELAY, HIGH);
*cooling_switch_p = false;
}
Serial.print("[ DBG ] Light Switch: ");
Serial.println(String(light_switch));
Serial.println("");
Serial.print("[ DBG ] Pump Switch: ");
Serial.println(String(pump_switch));
Serial.println("");
delay(5000);
}
else {
Serial.println("[ ERR ] Wifi not connected. Exiting program");
delay(9999);
exit(0);
}
}

我假设您正在尝试传感器数据从这个设备发送到另一个设备,同时或多或少准确地保持5秒采样间隔。你可以自己用两个线程创建一个简单的异步架构。

现有的线程(由Arduino创建)运行当前的loop(),每5秒读取一次传感器。您添加第二个线程,该线程处理将样本传输到其他设备。第一个线程通过FreeRTOS队列将示例发送给第二个线程;第二个线程立即开始传输。第一个线程继续关注自己的事务,而不等待传输完成。

使用FreeRTOS文档创建任务和队列:

#include <task.h>
#include <queue.h>
#include <assert.h>
TaskHandle_t hTxTask;
QueueHandle_t hTxQueue;
constexpr size_t TX_QUEUE_LEN = 10;
// The task which transmits temperature samples to wherever needed
void txTask(void* parm) {
while (true) {
float temp;
// Block until a sample is posted to queue
const BaseType_t res = xQueueReceive(hTxQueue, static_cast<void*>(&temp), portMAX_DELAY);
assert(res);
// Here you write your code to send the temperature to other device
// e.g.: esp_now_send(temp);
}
}
void setup() {
// Create the queue
hTxQueue = xQueueCreate(TX_QUEUE_LEN, sizeof(float));
assert(hTxQueue);
// Create and start the TX task
const BaseType_t res = xTaskCreate(txTask, "TX task", 8192, nullptr, tskIDLE_PRIORITY, &hTxTask);
assert(res);
// ... rest of your setup()
}
void loop() {
if (WiFi.status() == WL_CONNECTED) {
float temp_check = dht.readTemperature();
// Post fresh sample to queue
const BaseType_t res = xQueueSendToBack(hTxQueue, &temp_check, 0);
if (!res) {
Serial.println("Error: TX queue full!");
}
// ... Rest of your loop code
}
}

最新更新