/*
WOKWi test proj.: Raspberry Pi Pico C/C++ SDK (Project WITH CMakelist)
Author: Sergio A. González
For More Info Visit: https://icyte.conicet.gov.ar/investigadores
*/
#include <stdio.h>
#include "pico/stdlib.h"
#include <stdlib.h>
#include <math.h>
#include <time.h>
#define BUILTIN_LED PICO_DEFAULT_LED_PIN
#define WINDOW_SIZE 4096
#if ( defined(__GNUC__) || defined(__GNUG__) )
// GCC version in a string
char versionStringGCC[16];
#endif
typedef struct {
float *buffer;
uint16_t size;
uint16_t index;
float sum;
} RunningAverage_t;
// Function to initialize the RunningAverage struct
RunningAverage_t* createRunningAverage(int size) {
RunningAverage_t *ra = (RunningAverage_t*)malloc(sizeof(RunningAverage_t));
if (ra == NULL) {
return NULL; // Memory allocation failed
}
ra->buffer = (float*)malloc(size * sizeof(float));
if (ra->buffer == NULL) {
free(ra);
return NULL; // Memory allocation failed
}
ra->size = size;
ra->index = 0;
ra->sum = 0.0f;
for (int i = 0; i < size; i++) {
ra->buffer[i] = 0.0f;
}
return ra;
}
// Function to add a new value to the running average
void addValue(RunningAverage_t *ra, float newValue) {
ra->sum -= ra->buffer[ra->index];
ra->buffer[ra->index] = newValue;
ra->sum += newValue;
ra->index = (ra->index + 1) % ra->size;
}
// Function to get the current running average
float getAverage(RunningAverage_t *ra) {
return ra->sum / ra->size;
}
// Function to free the allocated memory
void freeRunningAverage(RunningAverage_t *ra) {
free(ra->buffer);
free(ra);
}
int main() {
uint16_t bufferSize = WINDOW_SIZE;
float data = 0.0f;
uint64_t i = 0;
RunningAverage_t *myRunningAverage = createRunningAverage(bufferSize);
stdio_init_all();
// Seed the random number generator once at the start of the program
srand(time(NULL));
// Format the version number into a string
snprintf(versionStringGCC, sizeof(versionStringGCC), "%d.%d.%d", __GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__);
/* Note: Last time I checked this was 14.2.0, being on the bleeding
* edge is certainly not a good thing regarding your C compiler.
*/
gpio_init(BUILTIN_LED);
gpio_set_dir(BUILTIN_LED, GPIO_OUT);
printf("Hello World From Pi Pico - Using USB CDC!:\n");
printf("GCC ver. in WOKWi: %s\n", versionStringGCC);
printf("Max rand Gen with this toolchain is: %d\n", RAND_MAX);
while (1)
{
gpio_put(BUILTIN_LED, 1);
sleep_ms(50);
data = rand(); // random never generated is an 'integer' stored as 'float'
printf("Random number (0 to RAND_MAX): %d\n", (int)data);
// we run the average on the saved float number
addValue(myRunningAverage, data);
printf("Running Average: %f\n", getAverage(myRunningAverage));
/* The moving average of a time series is not a measure of randomness quality but
* it can certainly highlight longer-term trends or cycles in a time series.
* it can help in identifying patterns that might indicate a lack of
* randomness (like trends or cycles).
* Use 'serial plotter' in WOKWi to see this.
*/
gpio_put(BUILTIN_LED, 0);
sleep_ms(100);
i++;
}
}