/**
 ******************************************************************************
 * @file           : main.c
 * @author         : Auto-generated by STM32CubeIDE
 * @brief          : Main program body
 ******************************************************************************
 * @attention
 *
 * <h2><center>&copy; Copyright (c) 2019 STMicroelectronics.
 * All rights reserved.</center></h2>
 *
 * This software component is licensed by ST under BSD 3-Clause license,
 * the "License"; You may not use this file except in compliance with the
 * License. You may obtain a copy of the License at:
 *                        opensource.org/licenses/BSD-3-Clause
 *
 ******************************************************************************
 */

#if !defined(__SOFT_FP__) && defined(__ARM_FP)
  #warning "FPU is not initialized, but the project is compiling for an FPU. Please initialize the FPU before use."
#endif

#include "stm32l073xx.h"

void nastavSPI(void)
{
	// zapne hodinovy signal pro port B a C
	RCC->IOPENR |= (RCC_IOPENR_IOPBEN | RCC_IOPENR_IOPCEN);

	// vynuluje nastaveni rezimu PB10 (vstupni rezim)
	GPIOB->MODER &= ~GPIO_MODER_MODE10;

	// nastavi PB10 do alternativniho rezimu
	GPIOB->MODER |= GPIO_MODER_MODE10_1;

	// nastavi PB10 do alternativniho rezimu 5 pro SPI
	GPIOB->AFR[1] |= (5U << GPIO_AFRH_AFSEL10_Pos);

	// nastavi maximalni rychlost pinu PB10
	GPIOB->OSPEEDR |= GPIO_OSPEEDER_OSPEED10;

	//nastavi stredni rychlost pinu PB10
	//GPIOB->OSPEEDR |= GPIO_OSPEEDER_OSPEED10_0;

	// vynuluje nastaveni rezimu PC2 a PC3
	GPIOC->MODER &= ~(GPIO_MODER_MODE2 | GPIO_MODER_MODE3);

	// nastavi PC2 a PC3 do alternativniho rezimu
	GPIOC->MODER |= (GPIO_MODER_MODE2_1 | GPIO_MODER_MODE3_1);

	// nastavi PC2 a PC3 do alternativniho rezimu 2 pro SPI
	GPIOC->AFR[0] |= ((2U << GPIO_AFRL_AFSEL2_Pos) | (2U << GPIO_AFRL_AFSEL3_Pos));

	// nastavi maximalni rychlost pinu PC2 a PC3
	GPIOC->OSPEEDR |= (GPIO_OSPEEDER_OSPEED2 | GPIO_OSPEEDER_OSPEED3);

	// nastavi stredni rychlost pinu PC2 a PC3
	//GPIOC->OSPEEDR |= (GPIO_OSPEEDER_OSPEED2_0 | GPIO_OSPEEDER_OSPEED3_0);

	// zapne hodinovy signal pro SPI2
	RCC->APB1ENR |= RCC_APB1ENR_SPI2EN;

	// nastavi SPI2 do Master rezimu se SW rizenim NSS signalu a spusti jej
	SPI2->CR1 |= (SPI_CR1_MSTR | SPI_CR1_SPE | SPI_CR1_SSM | SPI_CR1_SSI);
}


int main(void)
{
	// reset nastaveni vicerychlostniho oscilatoru
	RCC->ICSCR &= ~(RCC_ICSCR_MSIRANGE_Msk);

	// nastavi kmitocet vicerychlostniho oscilatoru na 4 MHz
	RCC->ICSCR |= ((6 << RCC_ICSCR_MSIRANGE_Pos) & RCC_ICSCR_MSIRANGE_Msk);

	// zapne hodinovy signal pro port C
	RCC->IOPENR |= RCC_IOPENR_IOPCEN;

	// nastavi piny PC0 a PC4 jako vstupni
	GPIOC->MODER &= ~(GPIO_MODER_MODE0 | GPIO_MODER_MODE4);

	nastavSPI();

	// vypne hodinovy signal pro port B a C
	//RCC->IOPENR  &= ~(RCC_IOPENR_IOPBEN | RCC_IOPENR_IOPCEN);

	while(1)
	{
		// odesli data
		SPI2->DR = 0xAA;

		// cekej, dokud nejsou data odeslana
		while((SPI2->SR & SPI_SR_BSY) == SPI_SR_BSY);
	}
}
