cancel
Showing results for 
Search instead for 
Did you mean: 

STM32 Accelometer

achourwissem
Associate II
Posted on June 17, 2013 at 17:07

hello people

i'm using IAR  IDE and i'm trying to make a program which get accelo values (x and y) and put them on lcd

 this is my code and it didnt work i dont know why:

******************************

#include ''stm32f4xx.h''

#include ''LCD2x16.c''

char SPItransaction (int AandD) { // about 7us

#define MOSI 0x8000

#define MISO 0x4000

#define SCK 0x2000

#define SEL 0x1000

int Ret = 0;

GPIOB->ODR &= ~SEL; // SPI select

for (char k = 0; k<16; k++) { // for 16 bits

if (AandD & 0x8000) GPIOB->ODR |= MOSI; // send address & data

else GPIOB->ODR &= ~MOSI; //

AandD <<= 1; // next bit of address & data

GPIOB->ODR &= ~SCK; // SCL lo

for (int i = 0; i<100; i++) {}; // waste 150ns

Ret <<= 1; // shift bits read right

GPIOB->ODR |= SCK; // SCL hi

if (GPIOB->IDR & MISO) Ret++; // read bit and add to string

};

GPIOB->ODR |= SEL; // SPI done

return ((char)(Ret & 0xff)); // return result

}

void SPIwrite(int Adr, int Data) {

SPItransaction(((Adr & 0x3f) << 😎 + Data); // prepare 16 bits

}

char SPIread(int Adr) {

char Ret = SPItransaction(((Adr & 0x3f) << 😎 + 0x8000); // 16 bits

return (Ret); // return result

}

void main () {

// ports init: 15-MOSI, 14-MISO, 13-SCK, 12-SEL

RCC->AHB1ENR |= 0x00000002; // Enable clock for GPIOB

GPIOB->MODER &= ~0x80000000; // PB 15 => input pin, no AF!

GPIOB->MODER |= 0x45000000; // PB 15,13,12 => outputs

GPIOB->ODR |= 0xc000; // SEL & SCK -> hi

// Init accelerometer chip

SPIwrite(0x20, 0xc7); // CR1: power-up, all axes

SPIwrite(0x21, 0x40); // CR2: Block data update & 12 bit mode

SPIwrite(0x22, 0x00); // CR3: no filtering

// Init LCD & prepare display

LCD_init(); // Init LCD

LCD_string(''x= mg'', 0x00); // prepare 1st row

LCD_string(''y= mg'', 0x40); // prepare 2nd row

// endless loop

while (1) {

short retX = SPIread(0x29) + (SPIread(0x2a) << 8); // x axis, both bytes

LCD_sInt16(retX, 0x02, 1); // display result

short retY = SPIread(0x2b) + (SPIread(0x2c) << 8); // y axis, both bytes

LCD_sInt16(retY, 0x42, 1); // display result

//for (int i=0; i<100000; i++) {}; // waste time, ~30ms

};

}

the lcd works just the values always are 0! i think the problem is in the registeries , help plz

3 REPLIES 3
frankmeyer9
Associate II
Posted on June 18, 2013 at 08:47

You will have a hard time to find some one to support you with this

https://en.wikipedia.org/wiki/Magic_number_%28programming%29

and register-hack ridden code. I'm not going to dig into it.

Why bit banging ?

All STM32's have native SPI peripherals.

achourwissem
Associate II
Posted on June 18, 2013 at 10:15

okay forget about that code.

Can u help me and put a working code with IAR? and thnx 🙂
frankmeyer9
Associate II
Posted on June 18, 2013 at 11:46

okay forget about that code.

 

Good idea. Had you ever to maintain such a code ... ?

But more important : which accelerometer ?