// E85 Lab 8: Digital Level // Cherie Ho and David Money Harris // Based on Bryce's SPI + GPIO STM32F0 CMSIS example #include "stm32f0xx.h" #include "EasyNucleoIO.h" ///////////////////////////////////////////////////////////////////// // SPI Functions ///////////////////////////////////////////////////////////////////// #define ALT 2 void spiInit() { //set ALT function for SPI pins pinMode(17, ALT); // PA4/SPI1_NSS (A3) pinMode(18, ALT); // PA5/SPI1_SCK (A4) pinMode(19, ALT); // PA6/SPI1_MISO (A5) pinMode(20, ALT); // PA7/SPI1_MOSI (A6) //configure SPI: //SPI enabled -> SPE; BAUD rate -> BR; Master -> MSTR; //BR = fclk/8, master mode SPI1->CR1 |= SPI_CR1_BR_1 | SPI_CR1_MSTR; // Enable NSS select signal, pulse NSS between transfers, 16-bit data, SPI1->CR2 |= SPI_CR2_SSOE | SPI_CR2_NSSP | (0xF) << 8; //enable SPI SPI1->CR1 |= SPI_CR1_SPE; } //send a 16-bits (short) on SPI1 unsigned short SPI1SendReceive16(unsigned short outDat) { SPI1->DR = outDat; while(!(SPI1->SR & SPI_SR_RXNE)); // wait for response return SPI1->DR; } void spiWrite(unsigned char address, unsigned char value) { SPI1SendReceive16(address << 8 | value); } unsigned char spiRead(unsigned char address) { return SPI1SendReceive16(address << 8 | (1 << 15)); } ///////////////////////////////////////////////////////////////////// // Digital Level logic ///////////////////////////////////////////////////////////////////// int main(void) { volatile unsigned char debug; volatile short x,y, disx,disy; //setup clocks and hardware EasyNucleoIOInit(); spiInit(); // Initialize SPI pins and clocks //Setup the LIS3DH for use spiWrite(0x20, 0x77); // highest conversion rate, all axis on spiWrite(0x23, 0x88); // block update, and high resolution // Check WHO_AM_I register. should return 0x33 debug = spiRead(0x0F); while(1) { // Collect the X and Y values from the LIS3DH x = spiRead(0x28) | (spiRead(0x29) << 8); y = spiRead(0x2A) | (spiRead(0x2B) << 8); // Small delay to reduce flicker delayLoop(100); } }