Advertisement
tehcmn

Reading the STM32F407-DISCO MEMS Accelerometer over SPI

Jun 29th, 2014
260
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.42 KB | None | 0 0
  1. static void spi_test(BaseSequentialStream *chp, int argc, char **argv)
  2. {
  3.     //select LED15 to signify entry
  4.     palSetPadMode(GPIOD, 15, PAL_MODE_OUTPUT_PUSHPULL);
  5.     palSetPad(GPIOD, 15);
  6.  
  7.     //start the SPI driver
  8.     const SPIConfig cfg =
  9.     {
  10.         NULL,
  11.         GPIOE,      // port
  12.         GPIOE_CS_SPI,   // /SS
  13.         SPI_CR1_BR_0 | SPI_CR1_BR_1 |
  14.         SPI_CR1_CPOL | SPI_CR1_CPHA    
  15.     };
  16.     uint8_t tx[2], rx[2];
  17.     int32_t x, y, z;
  18.     spiStart(&SPID1, &cfg);
  19.     spiSelect(&SPID1);
  20.     //X, Y, Z are in 0x29, 0x2B and 0x2D
  21.     //Control bytes for init are 0x20, 0x21, 0x22
  22.     tx[0] = 0x20;
  23.     tx[1] = 0x73;
  24.     spiSend(&SPID1, 2, tx);
  25.     spiUnselect(&SPID1);
  26.     spiSelect(&SPID1);
  27.     tx[0] = 0x21;
  28.     tx[1] = 0x00;
  29.     spiSend(&SPID1, 2, tx);
  30.     spiUnselect(&SPID1);
  31.     spiSelect(&SPID1);
  32.     tx[0] = 0x22;
  33.     tx[1] = 0x00;
  34.     spiSend(&SPID1, 2, tx);
  35.     spiUnselect(&SPID1);
  36.  
  37.     //init done, now read out values
  38.     tx[0] = 0x80 | 0x29;
  39.     tx[1] = 0xff;
  40.     spiSelect(&SPID1);
  41.     spiExchange(&SPID1, 2, tx, rx);
  42.     spiUnselect(&SPID1);
  43.     x = (int8_t) rx[1];
  44.  
  45.     tx[0] = 0x80 | 0x2B;
  46.     tx[1] = 0xff;
  47.     spiSelect(&SPID1);
  48.     spiExchange(&SPID1, 2, tx, rx);
  49.     spiUnselect(&SPID1);
  50.     y = (int8_t) rx[1];
  51.  
  52.     tx[0] = 0x80 | 0x2D;
  53.     tx[1] = 0xff;
  54.     spiSelect(&SPID1);
  55.     spiExchange(&SPID1, 2, tx, rx);
  56.     spiUnselect(&SPID1);
  57.     //__asm__("bkpt");
  58.     z = (int8_t) rx[1];
  59.  
  60.     chThdSleepMilliseconds(50);
  61.     chprintf(chp, "Accelerometer: (%d,%d,%d)\r\n", x, y, z);
  62.  
  63.     spiUnselect(&SPID2);
  64.     palClearPad(GPIOD, 15);
  65.  
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement