#include <stdio.h>
#include <stdint.h>
#include <stdbool.h>
#include "stm32f3xx.h"

volatile _Bool interruptWarDa;

void TIM2_IRQHandler(void)
{
	interruptWarDa = 1;
	TIM2->SR &= ~TIM_SR_UIF;
}
// Function to delay in microseconds
void Delay(uint32_t x){
	RCC->APB1ENR |= RCC_APB1ENR_TIM2EN;
	interruptWarDa = 0;
	TIM2->DIER = TIM_DIER_UIE;			// Update-Interrupt ein
	TIM2->CNT = 0;
	TIM2->PSC = 10;
	TIM2->ARR = x;
	TIM2->CR1 = TIM_CR1_CEN;			// Timer ein
	NVIC_EnableIRQ(TIM2_IRQn);
	while(!interruptWarDa)
		__WFI();
	TIM2->CR1 &= ~TIM_CR1_CEN;			// Timer aus
}

void DataHigh(){
	GPIOC->ODR |= (1<<8);	//PC8High
}

void DataLow(){
	GPIOC->ODR &= ~(1<<8);	//PC8 LOW
}

void CsHigh(){
	GPIOC->ODR |= (1<<6); 	//PC6 High
}

void CsLow(){
	GPIOC->ODR &= ~(1<<6);    //PC6 Low
}

void ClockHigh(){
	GPIOC->ODR |= (1<<5);	//PC5 High
}

void ClockLow(){
	GPIOC->ODR &= ~(1<<5);	//PC5 Low
}

int main() {

	RCC->AHBENR |= (1<<19); 			// GPIOC clock enable
	GPIOC->MODER |=	(1<<10)|(1<<12)|(1<<16); // PC8 = CS; PC6 = DIN; PC5 = CLK
	GPIOC->PUPDR |= (1<<11)|(1<<13)|(1<<17);

	while(1){
		int i, bit;
		uint16_t j = 0x0101; // LED erste Zeile, ganz rechts anschalten

		CsLow();

		for (i = sizeof(j) * 8 - 1; i >= 0; i--){

			bit = (j >> i) & 1 ;

			Delay(1);
			ClockLow();
			if(bit==0)
				DataLow();
			if(bit==1)
				DataHigh();
			Delay(1);
			ClockHigh();
		}

		CsHigh();
		Delay(10);

	};

    return 0;
}