为什么我从课堂上的 FreeRTOS 任务中获得错误的参数

问题描述 投票:0回答:1

我的问题:

我想将参数交给类中的FreeRTOS任务。我正在使用带有 Arduino IDE 的 ESP32 板。我尝试此操作时得到 0.00 作为输出。这是一个代码示例:

class testClass {
  public:
    testClass(/*parameters*/){
      //Do some stuff...
    }
  private:
    TaskHandle_t testTask;

    static void testTaskFunction (void * pvParameters) {
      float *number = (float *) pvParameters; 

      String stringifiedNumber;
      stringifiedNumber = String(*number);

      Serial.println(stringifiedNumber); // Output 2
      Serial.println(*number); // Output 3

      vTaskDelete(NULL); // Must be there, otherwise there will be an error because the function is finished but the task still exists. Here the task is deleted and the function is aborted.
    }

  public:
    void testFunction (float number) {
      Serial.println(number); // Output 1

      xTaskCreatePinnedToCore(
        testTaskFunction, // Function to implement the task 
        "testTask", // Name of the task
        10000,  // Stack size in words
        (void *) &number,  // Task input parameter
        2,  // Priority of the task
        &testTask,  // Task handle.
        0); // Core where the task should run
    }
};

testClass testInstance1;
testClass testInstance2;


void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
}

void loop() {
  // put your main code here, to run repeatedly:  
  for (float i = -20; i < 30; i += 0.1) {
    testInstance1.testFunction(i);
    delay(1000);
    testInstance2.testFunction(i + 21);
    delay(1000);
  }
}

输出(无注释):

ets Jun  8 2016 00:22:57

rst:0x1 (POWERON_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
configsip: 0, SPIWP:0xee
clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
mode:DIO, clock div:1
load:0x3fff0030,len:1416
load:0x40078000,len:14804
load:0x40080400,len:4
load:0x40080404,len:3356
entry 0x4008059c
-20.00 // Output 1 (testInstance1)
0.00 //   Output 2 (testInstance1)
0.00 //   Output 3 (testInstance1)
1.00 //   Output 1 (testInstance2)
0.00 //   Output 2 (testInstance2)
0.00 //   Output 3 (testInstance2)
-19.90 // ...
0.00
0.00
1.10
0.00
0.00
-19.80
0.00
0.00
1.20
0.00
0.00
-19.70
0.00
0.00
1.30
0.00
0.00
-19.60
0.00
0.00
1.40
0.00
0.00
-19.50
0.00
0.00
1.50
0.00
0.00
-19.40
0.00
0.00
1.60
0.00
0.00
-19.30
0.00
0.00
1.70
0.00
0.00

我尝试过的:

我已经删除了该类的另一个实例,瞧,它可以工作了。但这对我来说不是可能的解决方案。我也尝试过更改延迟的持续时间,但没有成功。

你能说我做错了什么吗?请帮助我。

c++ arduino esp32 freertos arduino-esp32
1个回答
0
投票

testFunction
中,您将
number
的地址作为任务输入参数传递,但
number
驻留在堆栈上。当您的任务执行时,堆栈上的值早已消失。尝试按值传递
number

© www.soinside.com 2019 - 2024. All rights reserved.