无法读取加速度计数据

时间:2017-06-06 16:43:11

标签: accelerometer i2c msp430

我正在尝试使用msp430G2553从MMA8652读取加速度计数据,但总是得到0.看起来它永远不会读取xval。编译器有警告:

#112-D statement is unreachable
#161-D declaration is incompatible with previous "i2c_rx"

(在第42行宣布)

    //I2C
#include <msp430g2553.h>
#include <msp430.h>

#define SCL     TRISB4 // I2C bus
#define SDA     TRISB1 //
#define SCL_IN  RB4    //
#define SDA_IN  RB1    //

SDA = 1;
SCL = 1;
SCL_IN = 0;
SDA_IN = 0;

void main() {


volatile int xval = 0;
    WDTCTL = WDTPW + WDTHOLD; //Disable the Watchdog timer for our convenience.

   while(1);
   { 
   // sensor initialisation
    i2c_start();
    i2c_tx(0x1D);
    i2c_tx(0x2A);
    i2c_tx(0x01); //Active mode

    i2c_tx(0x1D);
    i2c_tx(0x09);
    i2c_tx(0x00); 

    i2c_tx(0x1D);
    i2c_tx(0x0F);
    i2c_tx(0x03);
    i2c_stop();

    // read x value
    i2c_start();
    i2c_tx(0x1D);
    i2c_tx(0x01);
    xval=i2c_rx(1); 
    i2c_stop();

    }
}


void i2c_dly(void)
{
}

void i2c_start(void)
{
  SDA = 1;             // i2c start bit sequence
  i2c_dly();
  SCL = 1;
  i2c_dly();
  SDA = 0;
  i2c_dly();
  SCL = 0;
  i2c_dly();
}

void i2c_stop(void)
{
  SDA = 0;             // i2c stop bit sequence
  i2c_dly();
  SCL = 1;
  i2c_dly();
  SDA = 1;
  i2c_dly();
}

unsigned char i2c_rx(char ack)
{
char x, d=0;
  SDA = 1; 
  for(x=0; x<8; x++) {
    d <<= 1;
    do {
      SCL = 1;
    }
    while(SCL_IN==0);    // wait for any SCL clock stretching
    i2c_dly();
    if(SDA_IN) d |= 1;
    SCL = 0;
  } 
  if(ack) SDA = 0;
  else SDA = 1;
  SCL = 1;
  i2c_dly();             // send (N)ACK bit
  SCL = 0;
  SDA = 1;
  return d;
}

char i2c_tx(unsigned char d)
{
char x;
static char b;
  for(x=8; x; x--) {
    if(d&0x80) SDA = 1;
    else SDA = 0;
    SCL = 1;
    d <<= 1;
    SCL = 0;
  }
  SDA = 1;
  SCL = 1;
  i2c_dly();
  b = SDA_IN;          // possible ACK bit
  SCL = 0;
  return b;
}

0 个答案:

没有答案