J.Bryan
Posts: 42
Joined: Tue Aug 01, 2017 2:44 pm

Plotting "live" or "realtime" graph in C

Fri Mar 02, 2018 1:30 am

Hi all,

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.

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.

Code: Select all

#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

}

droleary
Posts: 158
Joined: Fri Feb 09, 2018 3:45 am
Location: Minneapolis, MN USA
Contact: Website Skype

Re: Plotting "live" or "realtime" graph in C

Fri Mar 02, 2018 4:15 pm

Not sure how live-live you'd like, but I came across this article a while ago and found it to be a pretty interesting approach: Render Multimedia in Pure C

bazza
Posts: 19
Joined: Thu Apr 17, 2014 8:26 am

Re: Plotting "live" or "realtime" graph in C

Fri Mar 09, 2018 8:20 pm

Try Qwt it supports a range of plot options.

Bazza

Return to “C/C++”

Who is online

Users browsing this forum: No registered users and 9 guests