LinkNode_LIS3DH_test

Dependencies:   mbed

Fork of LinkNode_LIS3DH by Delong Qi

main.cpp

Committer:
helloqi
Date:
2016-04-13
Revision:
11:c16a53584668
Parent:
4:81cea7a352b0

File content as of revision 11:c16a53584668:

#include<mbed.h>

uint16_t x_a,y_a,z_a;
bool flag = 0;

SPI spi_master(P0_6,P0_5,P0_7); //mosi miso sclk 
DigitalOut cs(P0_4);

//Serial pc(P0_23,P0_25);

Serial pc(P0_9,P0_11);

uint8_t LIS3DH_SPI_RD(uint8_t addr)
{
    uint8_t  temp;
    cs = 0;
    wait_us(10);
    spi_master.write(addr);      
    temp=spi_master.write(0xff);
    wait_us(10);
    cs = 1;
    return temp;
}

void LIS3DH_SPI_WR(uint8_t addr,uint8_t wrdata)
{  
    cs = 0;
    wait_us(10);
    spi_master.write(addr);
    spi_master.write(wrdata);
    wait_us(10);
    cs = 1;
}

void SPI_LIS3DH_Init()
{
   spi_master.format(8,3);
   spi_master.frequency(100000);
   wait_ms(5);
   LIS3DH_SPI_WR(0x24,0x80);
   wait_ms(5);
   LIS3DH_SPI_WR(0x20,0x17);
   LIS3DH_SPI_WR(0x23,0x80);
}

void get_val(void)
{
    uint8_t Dx_L=1,Dy_L=1,Dz_L=1;
    uint8_t Dx_H=1,Dy_H=1,Dz_H=1;
    if(LIS3DH_SPI_RD(0x0f|0x80)==0x33)
    {
         printf("check device ok!\r\n");
         flag=1;
         Dx_H=LIS3DH_SPI_RD(0x29|0x80);   
         Dx_L=LIS3DH_SPI_RD(0x28|0x80);
         Dy_H=LIS3DH_SPI_RD(0x2b|0x80);
         Dy_L=LIS3DH_SPI_RD(0x2A|0x80);
         Dz_H=LIS3DH_SPI_RD(0x2d|0x80);
         Dz_L=LIS3DH_SPI_RD(0x2C|0x80);  
    }
    else
    { 
        printf("check device err!\r\n");
        wait(1);
    }
    x_a=Dx_H<<8|Dx_L/16;
    y_a=Dy_H<<8|Dy_L/16;
    z_a=Dz_H<<8|Dz_L/16;
}

int main(void)
{
  SPI_LIS3DH_Init();
  while(1)
  {  
     get_val();
     if(flag)
     {
         printf("Dx=:%d\r\n",x_a);
         printf("Dy=:%d\r\n",y_a);
         printf("Dz=:%d\r\n",z_a);
         flag=0;
         wait(1);
     }
  }
}