源码见附件
视频
5396e7d77fde8e7be8681cc36d78b88f
b站视频
视频号
基于tinygl+mpu6050的3D角度计Demo (qq.com)
前面我们移植了tinygl可以进行3D显示了,结合之前获取的mpu6050的角度信息,我们就可以3D动态显示角度的变化过程。实现水准(角度计)的Demo。
角度显示
char text[64];
/* 获取角度 */
int16_t accel[3];
mpu6050_itf_get_accel(accel);
accel[0] /= 4096;
accel[1] /= 4096;
accel[2] /= 4096;
/* 加速度计算角度
θx=α1180/π=[arctan(Ax/squr(AyAy+AzAz))]180/π
θy=β1180/π=[arctan(Ay/squr(AxAx+AzAz))]180/π
θz=γ1180/π=[arctan(Az/squr(AxAx+AyAy))]*180/π
*/
float th[3];
th[0] = atan2(sqrt(accel[1]*accel[1]+accel[2]*accel[2]),accel[0]) * 180/PI;
th[1] = atan2(sqrt(accel[0]*accel[0]+accel[2]*accel[2]),accel[1]) * 180/PI;
th[2] = atan2(sqrt(accel[0]*accel[0]+accel[1]*accel[1]),accel[2]) * 180/PI;
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
/* 显示角度 */
snprintf(text,sizeof(text),"x:%f",th[0]);
glDrawText((GLubyte *)text, 0, 0, 0xFF0000);
snprintf(text,sizeof(text),"y:%f",th[1]);
glDrawText((GLubyte *)text, 0, 12, 0x00FF00);
snprintf(text,sizeof(text),"z:%f",th[2]);
glDrawText((GLubyte *)text, 0, 24, 0x0000FF);
显示立方体,立方体绕三轴旋转来动态展示,三轴的角度
/* 画立方体,并旋转角度 */
draw_cube(th[0], th[1], th[2], 2, winSizeX, winSizeY);
void draw_cube(float x, float y, float z, float size, float cx, float cy)
{
glRotatef(x, 1.0f, 0.0f, 0.0f);
glRotatef(y, 0.0f, 1.0f, 0.0f);
glRotatef(z, 0.0f, 0.0f, 1.0f);
glBegin(GL_QUADS);
// Front Face
glColor3f(1.0f, 0.0f, 0.0f); //红
glVertex3f(-size, -size, size);
glVertex3f(size, -size, size);
glVertex3f(size, size, size);
glVertex3f(-size, size, size);
// Back Face
glColor3f(1.0f, 1.0f, 0.0f); //黄
glVertex3f(-size, -size, -size);
glVertex3f(size, -size, -size);
glVertex3f(size, size, -size);
glVertex3f(-size, size, -size);
// Top Face
glColor3f(0.0f, 0.0f, 1.0f); //蓝
glVertex3f(-size, size, size);
glVertex3f(size, size, size);
glVertex3f(size, size, -size);
glVertex3f(-size, size, -size);
// Bottom Face
glColor3f(1.0f, 0.0f, 1.0f); //紫
glVertex3f(-size, -size, size);
glVertex3f(size, -size, size);
glVertex3f(size, -size, -size);
glVertex3f(-size, -size, -size);
// Left Face
glColor3f(0.0f, 1.0f, 0.0f); //绿
glVertex3f(-size, -size, -size);
glVertex3f(-size, -size, size);
glVertex3f(-size, size, size);
glVertex3f(-size, size, -size);
// Right face
glColor3f(0.0f, 1.0f, 1.0f); //青
glVertex3f(size, -size, size);
glVertex3f(size, -size, -size);
glVertex3f(size, size, -size);
glVertex3f(size, size, size);
glEnd();
}
完整的代码见附件。
编译
gcc tinygl/src/*.c cube.c lcd.c mpu6050.c mpu6050_itf.c -I tinygl/include/ -o cube -lm
运行
./cube
测试效果见视频