垃圾值不确定它的来源

时间:2013-03-05 05:10:51

标签: c

我的代码出现了问题我现在已经在那里试了几个小时试图找出问题,但无法确定原因。当我打印到屏幕时,所有值应该等于零,而angleY变量保持打印出34244时应该为零。我想看看是否有人能告诉我这个价值来自哪里以及为什么?我有一行printf("current rate: %d angle rate: %d angle rate: %d previous rate: %d \n",currentRateY, angleRateY, angleY, previousRateY);打印所有变量的值,因此我可以查明问题,所有变量保持0直到angleY变量。我的代码如下:

#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;
    }
}


};

1 个答案:

答案 0 :(得分:2)

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

int angleY = angleY + angleRateY;

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

int angleY = 0;
angleY = angleY + angleRateY;

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