![](/media/cache/img/default_profile.jpg.50x50_q85.jpg)
Finished project.
Fork of ReferredCoursework2016 by
Diff: buffer.cpp
- Revision:
- 90:38dfa3f350aa
- Child:
- 91:cd9fcd45ecf6
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/buffer.cpp Thu Aug 17 02:42:30 2017 +0000 @@ -0,0 +1,79 @@ +/*buffer.cpp creates the circular buffer array and contains functions +responsible for pushing new data on to the queue and also pulling data +from it. It also contains the function to workout the moving average of +the 10 values stored within the circular buffer*/ + +#include "mbed.h" +#include "rtos.h" +#include "buffer.h" + +//Creates a struct array, using the custom struct that holds the acceleration measurements. +AccelData circular_buffer_array[10]; + +int rear = 0; +int front = 0; +int32_t sumX; +int32_t sumY; +int32_t sumZ; +int32_t averageX; +int32_t averageY; +int32_t averageZ; + +//Pushes data on to buffer using modulo operation. +void log_push(AccelData data) { + + rear = (rear + 1) % 10; + + if (rear == front) { + front = (front + 1) % 10; + } + + circular_buffer_array[rear] = data; + +} + +//Retrieves a single data struct using the argument to specify which. +AccelData log_get(int index) +{ + + AccelData record; + record = circular_buffer_array[(front + index) % 10]; + + return record; + +} + +/*This function loops through the array and calculates the average. +It clears the sum totals each time around so that the average is +updated with the new value pushed on to the buffer, creating a +moving average*/ +void print_averages(){ + + while(1){ + + for (int i = 0; i < 10; i++) { + + AccelData entry = log_get(i); + sumX += entry.x; + sumY += entry.y; + sumZ += entry.z; + + /*The two lines below can be uncomented to show the circular buffer working by + outputting the contents of the buffer every time a peice of data is pushed on to it. + This also makes it possible to verify the average is correct.*/ + + //printf("LSM6DS0 [acc/mg]: %6ld, %6ld, %6ld\r\n", entry.x, entry.y, entry.z); + //printf("\r\n"); + + } + + averageX = sumX / 10; + averageY = sumY / 10; + averageZ = sumZ / 10; + printf("average [acc/mg]: %6ld, %6ld, %6ld\r\n", averageX, averageY, averageZ); + printf("\r\n"); + sumX = 0; + sumY = 0; + sumZ = 0; +} +}