This post is older than 2 years and might not be relevant anymore
More Info: Consider searching for newer posts
This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

event data disappears in app_scheduler()

I'm trying to send some data to a custom event handler function using app_scheduler. The problem I am having is the data I am sending is not being received.

I expect this is a C syntax issue on my part. Alas my C skills are weak, so any help is much appreciated!

Here are some code snippets to show what I'm doing and the results I am getting:

Defines and event type declaration:

#define SCHED_MAX_EVENT_DATA_SIZE       sizeof(app_timer_event_t)
#define SCHED_QUEUE_SIZE                10

typedef struct
{
    uint8_t   evt_id;
    uint8_t   value;
} tag_evt_t;

My event handler looks like this:

static void sfst_tag_app_event_handler(void *p_tag_event, uint16_t size)
{
    tag_evt_t *tag_evt = (tag_evt_t*)p_tag_event;
    RTT_PRINTF("TAG EVT RCV:  ID=%x VAL=%x\n", tag_evt->evt_id, tag_evt->value);
}

My code to place the event on the app_handler() queue looks like this:

tag_evt_t  *p_tag_evt;

p_tag_evt->evt_id = 0x05;
p_tag_evt->value  = 0x22;

RTT_PRINTF("TAG EVT SEND: ID=%x VAL=%x\n", p_tag_evt->evt_id, p_tag_evt->value);

err_code =  app_sched_event_put(p_tag_evt, sizeof(tag_evt_t), sfst_tag_app_event_handler);
APP_ERROR_CHECK(err_code);

The output looks like this: image description

Parents
  • tag_evt_t * p_tag_evt;
    

    Two errors there - firstly you're allocating a pointer to the data, but not allocating actual space for the data, that pointer starts pointing to some random piece of memory. You're fortunate that you're not getting a hard fault writing to illegal memory or writing over your code. You want

    tag_evt_t tag_evt;
    

    and pass the address of it to your function &tag_evt

    But that's no good either as that variable is on the stack, it's local to the function, so as soon as you leave the function the memory is no-longer valid. By the time your event handler is called the stack will have overwritten the data, probably.

    If you only have one at any time, make the variable static, else use malloc() and free()

    static tag_evt_t tag_evt;

  • Thank you very much. All fixed now!

Reply Children
No Data
Related