#include <libopencm3/stm32/rcc.h>
#include <libopencm3/stm32/gpio.h>
#include <hal/pin.h>
#include <libopencm3/stm32/spi.h>
#include "funkce_spolecne.h"
#include "funkce_Analyzator.h"

void JTAG_inicializace (void)
{
    uint32_t JTAG_piny [] = {JTAG_TMS, JTAG_TDI, JTAG_TCK};

    for (uint16_t i = 0; i < sizeof(JTAG_piny) / sizeof(JTAG_piny[0]); i++)
    {
        pin_pull_disable(JTAG_piny[i]);
        pin_output_pushpull(JTAG_piny[i]);
    }
    pin_pull_disable(JTAG_TDO);
    pin_input(JTAG_TDO);

}

void JTAG_odpojeni(void)
{
    uint32_t JTAG_piny [] = {JTAG_TMS, JTAG_TDI, JTAG_TCK};

    for (uint16_t i = 0; i < sizeof(JTAG_piny) / sizeof(JTAG_piny[0]); i++)
    {
        pin_input(JTAG_piny[i]);
    }

}

void SPI3_inicializace(void)
{
    uint32_t SPI3_piny [] = {SPI3_SCK, SPI3_MISO, SPI3_MOSI};

    rcc_periph_clock_enable(RCC_SPI3);
    for (uint16_t i = 0; i < sizeof(SPI3_piny) / sizeof(SPI3_piny[0]); i++)
    {
        pin_af_pushpull(SPI3_piny[i]);
        pin_speed_fast(SPI3_piny[i]);
        pin_af_map(SPI3_piny[i], GPIO_AF6); //AF6 = SPI3
    }

   spi_set_dff_16bit(SPI3);
   spi_set_clock_phase_1(SPI3);
   spi_set_clock_polarity_0(SPI3);
   spi_send_msb_first(SPI3);
   spi_enable_software_slave_management(SPI3);
   spi_set_nss_low(SPI3);

   SPI_CR2(SPI3) &=  ~(SPI_CR2_FRF); //motorola mode

   spi_set_unidirectional_mode(SPI3);
   spi_set_receive_only_mode(SPI3);

   spi_set_slave_mode(SPI3);
   //spi_enable(SPI3); // SPI je povoleno az tesne pred zahajenim prenosu
}

void PHY_INTRP_RST_inicializace(void)   //nastaveni signalu RST a INTRP pro PHY
{
    pin_pull_disable(PHY_INTRP);
    pin_input(PHY_INTRP);
    pin_pull_disable(PHY_RST);
    pin_set(PHY_RST,true);
    pin_output_pushpull(PHY_RST);
}

void rizeni_FPGA_inicializace (void)
{
    pin_pull_disable(pamet_pulka);
    pin_input(pamet_pulka);
    pin_pull_disable(FPGA_prevod);
    pin_input(FPGA_prevod);
    pin_pull_disable(pamet_prazdna);
    pin_input(pamet_prazdna);

	pin_pull_disable(procesor_RDY );
	pin_set(procesor_RDY,false);
	pin_output_pushpull(procesor_RDY );
}
