I am trying to generate a live graph in C where my y-axis's data is measured realtime/live to debug my robot. Does anyone know how to create a "live" plot? I tried gnuplot
as below, however the graph is only showing 1 point. I am open to any other method to generate the live chart too. Currently, my raspberry pi is setup as a wifi server, so it is not possible for me to dump all my x
and y
axis to the cloud or services online to plot the graph.
I also tried the suggestion here. Although I had all the library setup properly and compiled successfully but nothing is being displayed.
My data is always 2 float value for the x
and y
-axis. Will the while(1)
cause any problem since I am not able to know the maximum value of my x
-axis's value?
Thank You.
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <sys/time.h>
#define DT 0.005 //5ms
int mymillis();
int timeval_subtract(struct timeval *result, struct timeval *t2, struct timeval *t1);
void plot_graph(FILE* p, float x, float y);
int main() {
int startInt = mymillis();
struct timeval tvBegin, tvEnd, tvDiff;
gettimeofday(&tvBegin, NULL);
int i = 1;
float x = 0.0;
float y = 0.0;
FILE *f = fopen("file.dat", "w");
if (f == NULL)
{
printf("Error opening file!\n");
exit(1);
}
FILE *p = popen("gnuplot", "w");
fprintf(p, "plot - with lines\n");
while (1)
{
startInt = mymillis();
//Do somethings over here e.g read sensor and filtering
y = generateX();//Function to generate y-axis data
x = (float i) * DT;//x-axis
plot_graph(p, x, y);
//Each loop should be at least 5ms.
while (mymillis() - startInt < (DT * 1000))
{
usleep(100);
}
i++;
}
return 0;
}
int mymillis()
{
struct timeval tv;
gettimeofday(&tv, NULL);
return (tv.tv_sec) * 1000 + (tv.tv_usec) / 1000;
}
int timeval_subtract(struct timeval *result, struct timeval *t2, struct timeval *t1)
{
long int diff = (t2->tv_usec + 1000000 * t2->tv_sec) - (t1->tv_usec + 1000000 * t1->tv_sec);
result->tv_sec = diff / 1000000;
result->tv_usec = diff % 1000000;
return (diff<0);
}
void plot_graph(FILE *p, float x, float y) {
fprintf(p,"plot '-'\n");
fprintf(p, "%f %f\n", x, y); // plot `a` points
fprintf(p,"e\n"); // finally, e
fflush(p); // flush the pipe to update the plot
}