Search code examples
pointersstructparametersarduinofreertos

Passing a struct as parameter to xTaskCreate - <Arduino_FreeRTOS.h>


When passing my struct to the function xTaskCreate and run it on my Arduino Uno I get a 0 as pin output and 1283 as delay output from the toggle_LED-function. Before, in the setup-function the data is correct. But when I pass it to the function and print from there the data is incorrect and as you can guess, none of my LEDs blink. Kind of a rookie when it comes to pointers, so what am I missing here? It compiles without errors, but doesn't work as expected.

#include <Arduino_FreeRTOS.h>

#define RED_PIN 6
#define YELLOW_PIN 7
#define GREEN_PIN 8


typedef struct LED_struct{
  int sPIN;
  int sDELAY;
} sLEDS;

bool debug_flag = true;

void setup() {
  Serial.begin(9600);
  sLEDS sRED = {RED_PIN, 500};
  sLEDS sYELLOW = {YELLOW_PIN, 200};
  sLEDS sGREEN = {GREEN_PIN, 1000};

  Serial.println("SETUP: ");
  Serial.println(sRED.sPIN);
  Serial.println(sRED.sDELAY);
  Serial.println(sYELLOW.sPIN);
  Serial.println(sYELLOW.sDELAY);
  Serial.println(sGREEN.sPIN);
  Serial.println(sGREEN.sDELAY);

  xTaskCreate(toggle_LED, "Toggle LED via struct", 128, &sRED, 1, NULL);
  xTaskCreate(toggle_LED, "Toggle LED via struct", 128, &sYELLOW, 1, NULL);
  xTaskCreate(toggle_LED, "Toggle LED via struct", 128, &sGREEN, 1, NULL);
}

void toggle_LED(struct LED_struct *xStruct){
  pinMode(RED_PIN, OUTPUT);
  pinMode(YELLOW_PIN, OUTPUT);
  pinMode(GREEN_PIN, OUTPUT);

  while(1){
    if (debug_flag == true) {
      Serial.println("DEBUG: ");
      Serial.print("PIN: ");
      Serial.println(xStruct->sPIN);
      Serial.print("DELAY: ");
      Serial.println(xStruct->sDELAY);
    }

    digitalWrite(xStruct->sPIN, HIGH);
    delay(250);
    digitalWrite(xStruct->sPIN, LOW);
    delay(xStruct->sDELAY);
  }
}

void loop() {
}

I've tried both with a local struct within the toggle_LED-function and without as I have it now.


Solution

  • These structures

    sLEDS sRED = {RED_PIN, 500};
    sLEDS sYELLOW = {YELLOW_PIN, 200};
    sLEDS sGREEN = {GREEN_PIN, 1000};
    

    are local variables which are (temporary) placed on the stack and out of scope when setup() ends. Their memory is reused for other purposes.

    Try

    static const sLEDS sRED = {RED_PIN, 500};
    static const sLEDS sYELLOW = {YELLOW_PIN, 200};
    static const sLEDS sGREEN = {GREEN_PIN, 1000};
    

    or place the structures at the file level (outside any function).