k_fifo

Hello,

I'm am trying to use k_fifo_alloc_put and k_fifo get to add a then read data from queue (IoMonitorMessage custom object). However, when I add 2 objects to the queue and then attempt to read out it just repeats the second object twice and so on /so forth for more objects. It appears to be deleting the objects because after 2 iterations of reading the queue is empty, but I don't know why it's reading the last entry first and then again (or deleting the first entry). 

Here is an image where a put data in the queue:

Here is where I get from the queue: 

I'm pretty sure that f_fifo_alloc_put handles the memory so I don't think I need k_free. I gave it a try anyway and it gave a bus fault. Any help is appreciated! I'm using toolchain v2.6.1 if that matters

Parents
  • Hello,

    k_fifo_alloc_put() allocates space for the FIFO bookkeeping structure, which otherwise needs to be provided by the app when using k_fifo_put(). But in both cases, the FIFO item will only include a pointer reference to your message variable. To ensure each FIFO item has a unique pointer reference, you probably want to make a copy of the message data before adding it to your FIFO queue.

    Example:

    #include <zephyr/kernel.h>
    #include <zephyr/logging/log.h>
    
    #define LOG_MODULE_NAME fifo_test
    LOG_MODULE_REGISTER(LOG_MODULE_NAME);
    
    struct fifo_data_t {
    	void *fifo_reserved;
    	uint8_t temperature;
    	uint8_t humitidy;
    };
    
    static K_FIFO_DEFINE(fifo_queue);
    
    void timer_callback(struct k_timer *timer_id)
    {
    	static uint32_t temp;
    	static uint32_t humidity;
    	struct fifo_data_t *fifo_data;
    
    	temp = temp % 80;
    	humidity = humidity % 100;
    
    	temp++;
    	humidity++;
    
    	fifo_data = k_malloc(sizeof(*fifo_data));
    	if (!fifo_data) {
    		LOG_ERR("Unable to allocate buffer from heap");
    		return;
    	}
    
    	fifo_data->humitidy = humidity;
    	fifo_data->temperature = temp;
    
    	k_fifo_put(&fifo_queue, fifo_data);
    }
    
    K_TIMER_DEFINE(timer, timer_callback, NULL);
    
    int main(void)
    {
    	struct fifo_data_t *fifo_data;
    
    	k_timer_start(&timer, K_SECONDS(1), K_SECONDS(1));
    
    	while (1) {
    		fifo_data = k_fifo_get(&fifo_queue, K_FOREVER);
    		LOG_INF("Temperature %d, Humidity %d", fifo_data->temperature, fifo_data->humitidy);
    		k_free(fifo_data);
    	}
    }

    The SDK also provides the Data FIFO library if you prefer to statically allocate the memory for the FIFO.

    Best regards,

    Vidar

Reply Children
No Data
Related