RM3000

Dependencies:   mbed

Fork of magnetomete_new by GOPA KUMAR K C

main.cpp

Committer:
sureshsusurla
Date:
2015-04-05
Revision:
1:953885edf7a7
Parent:
0:ac874e417fac

File content as of revision 1:953885edf7a7:

//magnetometer V1.2

#include "mbed.h"
#include "SPI.h"
#include "math.h"
#include "stdlib.h"
Serial pc(USBTX,USBRX);
SPI spi(PTE18,PTE19,PTE17);  //MOSI,MISO,SCLK
DigitalOut SSN_MAG(PTB11);  //SLAVE SELECT
DigitalIn DRDY(PTA17);
Timeout tr_mag;
uint8_t trflag_mag;
void trsub_mag();
//void end();

/*void end()
{
    pc.printf("varun");
    exit(1);
    
    }*/
void trsub_mag()
{
  trflag_mag=0;
}  
  

void FUNC_ACS_MAGNETOMETER_INIT();
void FUNC_ACS_MAGNETOMETER_EXECUTE();

void main()
{

FUNC_ACS_MAGNETOMETER_INIT();
while(1)
{pc.printf("start\n");
FUNC_ACS_MAGNETOMETER_EXECUTE();

} }
 
 void FUNC_ACS_MAGNETOMETER_INIT()
 {
   
  SSN_MAG=1;                                    //pin is disabled
  spi.format(8,0);                         //   8bits,Mode 0
  spi.frequency(100000);                   //clock frequency
  
  SSN_MAG=0;                                   // Selecting pin
  wait_ms(100);                            //accounts for delay.can be minimised.
  
  spi.write(0x83);                      //
  
  wait_ms(100);              
  
  unsigned char i;
  for(i=0;i<3;i++)//initialising values.
      {
         spi.write(0x00);              //MSB of X,y,Z
         spi.write(0xc8);             //LSB of X,Y,z;pointer increases automatically.
        }
   SSN_MAG=1;
 
}

void FUNC_ACS_MAGNETOMETER_EXECUTE()
{
   SSN_MAG=0;                                //enabling slave to measure the values
  wait_ms(100);
  spi.write(0x82);                     //initiates measurement
  wait_ms(100);
  spi.write(0x01);                   //selecting x,y and z axes, measurement starts now
  SSN_MAG=1;


 trflag_mag=1;
 tr_mag.attach(&trsub_mag,1);
 
 while(trflag_mag)
 {
 if(DRDY==1)
 {wait_ms(100);
  SSN_MAG=0;
 spi.write(0xc9);
  pc.printf(" ye");                  //command  byte for retrieving data
 
 unsigned char axis;
 float Bnewvalue[3]={0.0,0.0,0.0};
 int32_t Bvalue[3]={0,0,0}; 
 int32_t a= pow(2.0,24.0);
 int32_t b= pow(2.0,23.0);
 
 for(axis=0;axis<3;axis++)
  {
  Bvalue[axis]=spi.write(0x00)<<16;    //MSB 1 is send first 
  wait_ms(100);
  Bvalue[axis]|=spi.write(0x00)<<8;    //MSB 2 is send next
  wait_ms(100);
  Bvalue[axis]|=spi.write(0x00);       //LSB is send.....total length is 24 bits(3*8bits)...which are appended to get actual bit configuration
  
   
  if((Bvalue[axis]&b)==b)              
   {
     Bvalue[axis]=Bvalue[axis]-a;   //converting 2s complement to  signed decimal

  }
   Bnewvalue[axis]=(float)Bvalue[axis]*22.0*pow(10.0,-3.0);  //1 LSB=(22nT)...final value of field obtained in micro tesla
  
  wait_ms(100);
 pc.printf("\t%f\n \r",Bnewvalue[axis]);

 }
 SSN_MAG=1;break;
 }
 }
 pc.printf("exit");
 
 }