#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<10; 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) << 8) + Data); // prepare 16 bits } char SPIread(int Adr) { char Ret = SPItransaction(((Adr & 0x3f) << 8) + 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(0x28) + (SPIread(0x29) << 8); // read x axix, both bytes LCD_sInt16(retX, 0x02, 1); // display result short retY = SPIread(0x2a) + (SPIread(0x2b) << 8); // read y axix, both bytes LCD_sInt16(retY, 0x42, 1); // display result for (int i=0; i<1000000; i++) {}; // waste time, ~30ms }; }