用c语言写一个x轴刻度为时间,y轴刻度为数据的实时曲线波形demo
时间: 2023-12-10 21:39:42 浏览: 75
dd,四轴c语言源码,c语言
这个任务需要用到图形库,比如OpenGL或者SDL2,因为C语言本身并没有提供绘图功能。我以SDL2为例,给出一个基本的实时曲线波形demo:
```c
#include <stdio.h>
#include <stdlib.h>
#include <SDL2/SDL.h>
#define WIDTH 640
#define HEIGHT 480
#define MAX_POINTS 100
typedef struct {
float x, y;
} Point;
int main(int argc, char *argv[]) {
SDL_Window *window;
SDL_Renderer *renderer;
SDL_Event event;
Point points[MAX_POINTS];
int i, num_points = 0;
float y_scale, x_scale;
Uint32 last_time = SDL_GetTicks();
Uint32 current_time, delta_time;
float t = 0, dt = 0.01;
if (SDL_Init(SDL_INIT_VIDEO) != 0) {
fprintf(stderr, "SDL_Init Error: %s\n", SDL_GetError());
return EXIT_FAILURE;
}
window = SDL_CreateWindow("Real-time Plot", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, WIDTH, HEIGHT, SDL_WINDOW_SHOWN);
if (window == NULL) {
fprintf(stderr, "SDL_CreateWindow Error: %s\n", SDL_GetError());
SDL_Quit();
return EXIT_FAILURE;
}
renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
if (renderer == NULL) {
SDL_DestroyWindow(window);
fprintf(stderr, "SDL_CreateRenderer Error: %s\n", SDL_GetError());
SDL_Quit();
return EXIT_FAILURE;
}
y_scale = HEIGHT / 2.0;
x_scale = WIDTH / (float)MAX_POINTS;
while (1) {
current_time = SDL_GetTicks();
delta_time = current_time - last_time;
last_time = current_time;
while (SDL_PollEvent(&event)) {
if (event.type == SDL_QUIT) {
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
return EXIT_SUCCESS;
}
}
points[num_points].x = num_points * x_scale;
points[num_points].y = y_scale * (1 + sin(t));
num_points = (num_points + 1) % MAX_POINTS;
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
SDL_RenderClear(renderer);
SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);
for (i = 0; i < num_points; i++) {
SDL_RenderDrawPoint(renderer, points[i].x, HEIGHT - points[i].y);
}
SDL_RenderPresent(renderer);
t += dt;
SDL_Delay(10);
}
}
```
这个demo使用了SDL2库来创建窗口和渲染器,并且每10毫秒更新一次绘图。
我们将y轴的刻度范围设置为[-1, 1],然后将[-1, 1]映射到[0, HEIGHT/2]。x轴的刻度范围为[MAX_POINTS],然后将[0, MAX_POINTS]映射到[0, WIDTH]。
每次更新时,我们添加一个新的点到数组中,同时删除最早的点。然后我们使用SDL_RenderDrawPoint()函数将所有点绘制到屏幕上。
最后,我们使用SDL_Delay()函数来控制更新速率,以保证每10毫秒更新一次。
阅读全文