I'm trying to pass a struct to a function (by reference) and set several values of the struct in that function.
Here's the struct:
struct Sensor
{
BYTE accel_data[6];
BYTE gyro_data[6];
int ax;
int ay;
int az;
int gx;
int gy;
int gz;
};
here's the declaration in main():
struct Sensor s;
here's the pass to the function:
readAccel(&s);
readAccel function:
void readAccel(struct Sensor* s)
{
int ax, ay, az;
// Read data from Accelerometer Chip
i2c_multiRead(ACCEL_READ_ADDR, ACCEL_DATA_ADDR, s->accel_data, 6);
ax = make16(s->accel_data[1],s->accel_data[0]);
ay = make16(s->accel_data[3],s->accel_data[2]);
az = make16(s->accel_data[5],s->accel_data[4]);
fprintf(COM_A,"x: %d\ty: %d\tz: %d\r\n", ax, ay, az);
s->ax = ax;
s->ay = ay;
s->az = az;
fprintf(COM_A,"x: %d\ty: %d\tz: %d\r\n", s->ax, s->ay, s->az);
}
for some reason, the three assignment lines at the bottom of readAccel() are not working. The first print statement gives the correct accelerometer values. The second print statement gives the right value for x, but y is a junk value and z is always 0.
This is slightly nonstandard c (ccs c compiler) running on a pic microchip. The compiler has a few quirks (ints are 16 bit, all variables must be declared at the beginning of a function, etc), but I don't think it should be the reason why this isn't working (though I supposed it's possible).
Thanks for taking your time to help!
EDIT:
here's the i2c_multiread function:
void i2c_multiRead(char deviceAddrR, char registerAddr, BYTE data[], int numBytes)
{
int x;
i2c_start();
i2c_write(deviceAddrR-0b00000001);
i2c_write(registerAddr);
i2c_start();
i2c_write(deviceAddrR);
for(x=0; x<numBytes-1; x++)
{
data[x]=i2c_read();
}
data[numBytes-1] = i2c_read(0); //NACK on last read
i2c_stop();
}
void main ()
{
struct Sensor s;
int raw_accel_data[6];
int i, data;
char data_ready;
fprintf(COM_A,"keyspan working \n\r");
initAccel(&s);
//initGyro(&s);
fprintf(COM_A,"ALL SYSTEMS GO (accel initialized successfully)\n\r");
while(true) {
//data_ready = i2c_singleRead(ACCEL_READ_ADDR,ACCEL_INT_MAP);
//data_ready = data_ready >> 7;
readAccel(&s);
//readGyro(&s);
//displayGyroData(&s);
//displayGyroRawData(&s);
delay_ms(100);
}
// Address of ITG (Gyro Chip)
// Read: 0xD1
// Write: 0xD0
}