我正在嘗試從一個esp32接收資料到另一個。我還做了一些looping
與delays
用于讀取傳感器資料和開關通/斷繼電器冷卻。此設備還ESPAsyncWebServer
用作 API 服務器(不包含在代碼中的大小)。我現在正在從一個eps32接收資料以POST
請求 API。我想改變這一點,以便能夠收到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);
}
}
uj5u.com熱心網友回復:
我假設您正在嘗試將傳感器資料從這個設備發送到另一個設備,同時或多或少地準確地保持 5 秒的采樣間隔。您可以使用 2 個執行緒自己創建一個簡單的異步架構。
現有執行緒(由 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
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/329666.html
標籤:C 循环 延迟 ESP32 arduinoide
上一篇:C :函式指標陣列