-1

我的代码在某个地方有问题,我已经在某处使用了几个小时,现在试图找出问题但无法确定原因。当我打印到屏幕上时,所有值都应该为零,但是当它应该为零时,angleY变量会继续打印出来。34244我想看看是否有人能告诉我这个值来自哪里以及为什么?我有printf("current rate: %d angle rate: %d angle rate: %d previous rate: %d \n",currentRateY, angleRateY, angleY, previousRateY);打印所有变量值的行,因此我可以查明问题并且所有变量都保留0angleY变量为止。我的代码如下:

#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdint.h>
#include <time.h>
#include <wiringPi.h>
#include <wiringPiI2C.h>

#define CTRL_REG1 0x20
#define CTRL_REG2 0x21
#define CTRL_REG3 0x22
#define CTRL_REG4 0x23


int fd;
short x = 0;
short y = 0;
short z = 0;
int main (){



    fd = wiringPiI2CSetup(0x69); // I2C address of gyro
    wiringPiI2CWriteReg8(fd, CTRL_REG1, 0x1F); //Turn on all axes, disable power down
    wiringPiI2CWriteReg8(fd, CTRL_REG3, 0x08); //Enable control ready signal
    wiringPiI2CWriteReg8(fd, CTRL_REG4, 0x80); // Set scale (500 deg/sec)
    delay(200);                    // Wait to synchronize

void getGyroValues (){
    int MSB, LSB;

    LSB = wiringPiI2CReadReg8(fd, 0x28);
    MSB = wiringPiI2CReadReg8(fd, 0x29);
    x = ((MSB << 8) | LSB);

    MSB = wiringPiI2CReadReg8(fd, 0x2B);
    LSB = wiringPiI2CReadReg8(fd, 0x2A);
    y = ((MSB << 8) | LSB);

    MSB = wiringPiI2CReadReg8(fd, 0x2D);
    LSB = wiringPiI2CReadReg8(fd, 0x2C);
    z = ((MSB << 8) | LSB);
}
    for (int i=0;i<1000;i++){

        getGyroValues();

    int previousRateZ = z /114;
    int previousRateY = y /114;
    int previousRateX = x /114;

        delay(100);

        getGyroValues();

    int currentRateZ = z /114;
    int currentRateY = y /114;
    int currentRateX = x /114;

    int angleRateZ = ((long)(previousRateZ + currentRateZ) * 105)/1000;
    int angleRateY = ((long)(previousRateY + currentRateY) * 105)/1000;
    int angleRateX = ((long)(previousRateX + currentRateX) * 105)/1000;

    int angleZ = angleZ + angleRateZ;
    int angleY = angleY + angleRateY;
    int angleX = angleX + angleRateX;
    printf("current rate: %d angle rate: %d angle rate: %d previous rate: %d \n",currentRateY, angleRateY, angleY, previousRateY);
        delay(100);

    if(i == 1){
        printf("Z equals: %d\n", angleZ);
        printf("Y equals: %d\n", angleY);
    printf("X equals: %d\n", angleX);
    i=0;
    }
}


};
4

1 回答 1

2

angleY您在此行中设置它之前正在使用:

int angleY = angleY + angleRateY;

C 不保证将值初始化为零。我想你真的想要这样的东西:

int angleY = 0;
angleY = angleY + angleRateY;

我还假设第二行将在未来版本中以某种循环结束。

于 2013-03-05T05:16:50.243 回答