#include "stm32f4xx_rcc.c" #include "stm32f4xx_gpio.c" #include "stm32f4xx_tim.c" #include "stm32f4xx_spi.c" #include "LCD2x16.c" #include "dd.h" void GPIOBinit_SPI2(void) { GPIO_InitTypeDef GPIO_InitStructure; RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOB, ENABLE); GPIOB->BSRRL = BIT_14 | BIT_13 | BIT_12 | BIT_11; GPIO_InitStructure.GPIO_Pin = GPIO_Pin_13 | GPIO_Pin_14 | GPIO_Pin_15; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF; GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL; GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_25MHz; GPIO_Init(GPIOB, &GPIO_InitStructure); GPIO_InitStructure.GPIO_Pin = GPIO_Pin_11 | GPIO_Pin_12; // PB12, PB12: SPI_SEL GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT; GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP; GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_25MHz; GPIO_Init(GPIOB, &GPIO_InitStructure); GPIO_PinAFConfig(GPIOB, GPIO_PinSource13, GPIO_AF_SPI2); // PB13:SPI2_SCK GPIO_PinAFConfig(GPIOB, GPIO_PinSource14, GPIO_AF_SPI2); // PB14:SPI2_MISO GPIO_PinAFConfig(GPIOB, GPIO_PinSource15, GPIO_AF_SPI2); // PB15:SPI2_MOSI } void SPI2init(void) { // SPI_InitTypeDef SPI_InitStructure; RCC_APB1PeriphClockCmd(RCC_APB1Periph_SPI2, ENABLE); GPIOBinit_SPI2(); // GPIO clock enable, digital pin definitions SPI_InitStructure.SPI_Direction = SPI_Direction_2Lines_FullDuplex ; SPI_InitStructure.SPI_Mode = SPI_Mode_Master; SPI_InitStructure.SPI_DataSize = SPI_DataSize_16b; SPI_InitStructure.SPI_CPOL = SPI_CPOL_High; SPI_InitStructure.SPI_CPHA = SPI_CPHA_2Edge; SPI_InitStructure.SPI_NSS = SPI_NSS_Soft; SPI_InitStructure.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_64; SPI_InitStructure.SPI_FirstBit = SPI_FirstBit_MSB; SPI_InitStructure.SPI_CRCPolynomial = 7; SPI_Init(SPI2, &SPI_InitStructure); SPI_Cmd(SPI2, ENABLE); } void LIS_write (char address, char data) { GPIOB->BSRRH = BIT_12; for (int i = 0; i < 150; i++) {}; // waste time SPI2->DR = ((unsigned short)(address & 0x3f) << 8) + (unsigned short)(data); for (int i = 0; i < 1200; i++) {}; // waste time GPIOB->BSRRL = BIT_12; } short LIS_read (char address) { GPIOB->BSRRH = BIT_12; for (int i = 0; i < 150; i++) {}; // waste time SPI2->DR = ((address & 0x3f) << 8) + 0x8000; for (int i = 0; i < 1200; i++) {}; // waste time GPIOB->BSRRL = BIT_12; return (SPI2->DR & 0xff); } int main () { //short unsigned ii = 0; SPI2init(); // SPI2 init LCD_init(); // Init LCD LCD_string("SPI demo Z", 0); // write title LCD_string("X Y", 0x40); // write title LIS_write (0x20,0xc7); // waste time - indefinite while (1) { short xLSB = LIS_read(0x28); short xMSB = LIS_read(0x29) << 8; short yLSB = LIS_read(0x2a); short yMSB = LIS_read(0x2b) << 8; short zLSB = LIS_read(0x2c); short zMSB = LIS_read(0x2d) << 8; LCD_sInt16((xLSB + xMSB), 0x41, 0x01); // show acc x LCD_sInt16((yLSB + yMSB), 0x4a, 0x01); // show acc y LCD_sInt16((zLSB + zMSB), 0x0a, 0x01); // show acc z for (int i = 0; i < 10000000; i++) {}; // waste time }; }