/***************************************************************

This program is used to test that the debugging works.

It just counts and prints the value of the counter
on the LEDs and the UART.

***************************************************************

This program will work with the STR7x and the STR9x devices.
Just make sure that the correct derivative is selected
in the target options, the "#if"s will do the rest.

***************************************************************/

#if ( _STM32x_ )
#include "stm32f10x_lib.h"
#else
#include "STRx.h"
#endif


/*********************************************************************************/
/******************** features selection *****************************************/

#if ( _STR91x_ )
//this tells if we should make the code compliant with the trace
// trace uses some pins that must not be accessed or unconfigured by the application
#define TRACE_SUPPORT 1
// define to one if you use the trace, zero if you don't
// if you use the trace, you MUST unplug the D4, D5, D6 and D7 enable umpers of the REva.
#endif


//this tells if we should print on the UART
#define PRINT 0
// define to one if you use the UART, zero if you don't

#if PRINT
//this tells if we should print using the small version of print
// otherwise, we use the standard, big printf
#define VERYSMALLPRINT 1
#endif


/********************************************************************************/
/********************** UART management section *********************************/

#if PRINT
//with the following switches, you can test the different versions of printf
// and see the code size they need

#include "UART0_stdio.h"

//code of the very small print function
#if VERYSMALLPRINT

putint(unsigned int i)
    {
    unsigned char mod=i%10;
    unsigned int j=i/10;
    if(j)	putint(j);
    putchar(0x30+mod);
    }

//reduced version of printf accepting only one %d (unsigned short)
// usefull when using the UART for debugging because it's very small. (less than 1K)
print(char *str, unsigned short i)
    {
    while(*str)
        {
        if(*str=='%')
            {
            str++;
            if(*str=='d')
                {
                putint(i);
                str++;
                }
            }
        else
            putchar(*(str++));
        }
    }

#else // VERYSMALLPRINT

//when using this, try turning the "small printf" linker option ON and OFF
// to see what it does...
#define print printf
//you can also try to use iprintf because we only print integers.
//#define print iprintf

#endif // VERYSMALLPRINT


#else // PRINT

//not printing, and therefore not using small print
#define VERYSMALLPRINT 0

#endif // PRINT

/***********************************************************/
/***************** config **********************************/


void config()
    {

    /***************** config for STR71x **********************************/
#if ( _STR71x_ )
#if PRINT
    //tell io_putchar the board's crystal freq
    __io_SetMainOscFreq(4000000);
#endif
    //select GPIO1 for the rest of the demo
#define myGPIO GPIO1
    //configure REva LEDs as output
    myGPIO->PC0=0x0000;
    myGPIO->PC1=0x0000;
    myGPIO->PC2=(-1);
#endif

    /***************** config for STR73x **********************************/

#if ( _STR73x_ )
    unsigned char delay = 0 ;

#if PRINT
    //tell io_putchar the board's crystal freq   
    __io_SetMainOscFreq(8000000);
#endif

    //configure REva LEDs D2 to D7 as output
    /* GPIO2 Clock Enable */
    CFG->PCGR0 |= 0x0001 << 20;
    for (delay = 8 ; delay != 0 ; delay--); /* Peripheral Stabilization */
    //select GPIO2 for the rest of the demo
#define myGPIO GPIO2
    //configure REva LEDs as output
    myGPIO->PC0=0x0000;
    myGPIO->PC1=0x0000;
    myGPIO->PC2=(-1);
#endif


    /***************** config for STR75x **********************************/

#if ( _STR75x_ )
    //configure clock


#define MRCC_CKSYS_Div2    0x00000008
#define MRCC_HPRESC_Reset_Mask      0xFFFFFFE7
#define MRCC_Peripheral_GPIO     0x01000000
#define MRCC_Peripheral_UART1    0x00200000
#define MRCC_IOVoltageRange_3V3    0x00010000
#define MRCC_CKSEL_Reset_Mask       0xFF7FFFFF
#define MRCC_PLL_Mul_15      0x08000000
#define MRCC_PLLEN_Set_Mask         0x01000000
#define MRCC_LOCK_Mask              0x80000000
#define MRCC_XTDIV2_Reset_Mask      0xFFFF7FFF
#define MRCC_MX_Reset_Mask          0xE7FFFFFF
#define MRCC_PLLEN_Reset_Mask       0xFEFFFFFF
#define MRCC_CKSEL_Set_Mask         0x00800000
#define MRCC_CKTIM_Div1    0xFFFFFFFB
#define MRCC_HCLK_Div1    0x00000000
#define MRCC_PPRESC_Reset_Mask      0xFFFFFFFC

    /* Wait for OSC4M start-up */
    //OSC4MStartUpStatus = MRCC_WaitForOSC4MStartUp();
    do
        {
        /* Clear No Clock Detected flag */
        if((MRCC->CLKCTL & 0x00040000)!= 0)
            {
            MRCC->CLKCTL &= ~(0x00040000);
            }
        }while( (MRCC->RFSR&0x01000000) == 0 );


        /* Set HCLK to 30 MHz */
        //MRCC_HCLKConfig(MRCC_CKSYS_Div2);
        MRCC->CLKCTL = (MRCC->CLKCTL & MRCC_HPRESC_Reset_Mask) | MRCC_CKSYS_Div2;

        /* Set CKTIM to 30 MHz */
        //MRCC_CKTIMConfig(MRCC_HCLK_Div1);
        MRCC->CLKCTL = (MRCC->CLKCTL & MRCC_PPRESC_Reset_Mask) | MRCC_HCLK_Div1;

        /* Set PCLK to 30 MHz */
        //MRCC_PCLKConfig(MRCC_CKTIM_Div1);
        MRCC->CLKCTL &= MRCC_CKTIM_Div1;

        /* Set CKSYS to 60 MHz */
        //MRCC_CKSYSConfig(MRCC_CKSYS_OSC4MPLL, MRCC_PLL_Mul_15);
        /* Select CK_OSC as CK_SYS clock source */
        MRCC->CLKCTL |= MRCC_CKSEL_Set_Mask;

        /* Disable PLL */
        MRCC->CLKCTL &= MRCC_PLLEN_Reset_Mask;

        /* Configure PLL factor */
        /* Clear MX[1:0] bits */
        MRCC->CLKCTL &= MRCC_MX_Reset_Mask;
        /* Set MX[1:0] bits according to PLL_Mul value */
        MRCC->CLKCTL |= MRCC_PLL_Mul_15;

        /* Disable Oscillator Divider by 2 */
        MRCC->CLKCTL &= MRCC_XTDIV2_Reset_Mask;

        /* Enable PLL */
        MRCC->CLKCTL |= MRCC_PLLEN_Set_Mask;

        /* Wait until the PLL is locked */
        while((MRCC->CLKCTL & MRCC_LOCK_Mask) == 0);

        /* Select CK_PLL1 as CK_SYS clock source */
        MRCC->CLKCTL &= MRCC_CKSEL_Reset_Mask;

        /* GPIO pins optimized for 3V3 operation */
        //MRCC_IOVoltageRangeConfig(MRCC_IOVoltageRange_3V3);
        MRCC->PWRCTRL |= MRCC_IOVoltageRange_3V3;

        /* Enable UART1 and GPIO Clocks */
        MRCC->PCLKEN |= MRCC_Peripheral_UART1 | MRCC_Peripheral_GPIO;

#if PRINT
        //tell io_putchar the board's crystal freq
        __io_SetMainOscFreq(30000000);
#endif
        //select GPIO2 for the rest of the demo
#define myGPIO GPIO2

        //enable GPIO2 clock
#define MRCC_Peripheral_GPIO     0x01000000
        MRCC->PCLKEN |= MRCC_Peripheral_GPIO;

        //configure REva LEDs as output
        myGPIO->PC0=0x0000;
        myGPIO->PC1=0x0000;
        myGPIO->PC2=(-1);
#endif

    /***************** config for STR9x **********************************/
#if ( _STR91x_ )

#if PRINT
        //tell io_putchar the board's crystal freq
        __io_SetMainOscFreq(25000000);
#endif

        //select GPIO6 for the rest of the demo
#define myGPIO GPIO6
#define myGPIOnb 6
        SCU->PRR1  |= (0x00004000 << myGPIOnb);  // release GPIO reset
        SCU->PCGR1 |= (0x00004000 << myGPIOnb); // clock gating GPIO
#if TRACE_SUPPORT
        SCU->GPIOOUT[myGPIOnb] = ((SCU->GPIOOUT[myGPIOnb])&0xFF00) + 0x0055; // enable GPIO OUTPUT for all pins
        myGPIO->DIR |= 0x0F;       // Dir output on GPIO for all pins
#else
        SCU->GPIOOUT[myGPIOnb] = 0x5555; // enable GPIO OUTPUT for all pins
        myGPIO->DIR |= 0xFF;       // Dir output on GPIO for all pins
#endif
#endif


    /***************** config for STM32x **********************************/
#if ( _STM32x_ )


#if PRINT
   __io_SetMainOscFreq(8000000);
#endif

   {	
     ErrorStatus HSEStartUpStatus;															
     /* RCC system reset(for debug purpose) */
     RCC_DeInit();

     /* Enable HSE */
     RCC_HSEConfig(RCC_HSE_ON);

     /* Wait till HSE is ready */
     HSEStartUpStatus = RCC_WaitForHSEStartUp();

     if(HSEStartUpStatus == SUCCESS)
     {
       /* HCLK = SYSCLK */
       RCC_HCLKConfig(RCC_SYSCLK_Div1); 
     
       /* PCLK2 = HCLK */
       RCC_PCLK2Config(RCC_HCLK_Div1); 

       /* PCLK1 = HCLK/2 */
       RCC_PCLK1Config(RCC_HCLK_Div2);

       /* Flash 2 wait state */
       FLASH_SetLatency(FLASH_Latency_2);
       /* Enable Prefetch Buffer */
       FLASH_PrefetchBufferCmd(FLASH_PrefetchBuffer_Enable);

       /* PLLCLK = 8MHz * 9 = 72 MHz */
       RCC_PLLConfig(RCC_PLLSource_HSE_Div1, RCC_PLLMul_9);

       /* Enable PLL */ 
       RCC_PLLCmd(ENABLE);

       /* Wait till PLL is ready */
       while(RCC_GetFlagStatus(RCC_FLAG_PLLRDY) == RESET)
       {
       }

       /* Select PLL as system clock source */
       RCC_SYSCLKConfig(RCC_SYSCLKSource_PLLCLK);

       /* Wait till PLL is used as system clock source */
       while(RCC_GetSYSCLKSource() != 0x08)
       {
       }
     }
     
#if PRINT
     /* Enable GPIOC and USART1 clocks */
     RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC | RCC_APB2Periph_AFIO | RCC_APB2Periph_USART1, ENABLE);
#else
     /* Enable GPIOC clock */
     RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC | RCC_APB2Periph_AFIO , ENABLE);
#endif
      
      /* Configure PC pins as output push-pull */
      {
         GPIO_InitTypeDef GPIO_InitStructure;
         GPIO_InitStructure.GPIO_Pin =  GPIO_Pin_6 | GPIO_Pin_7 | GPIO_Pin_8 | GPIO_Pin_9
               | GPIO_Pin_10 | GPIO_Pin_11 | GPIO_Pin_12 | GPIO_Pin_13 ;
         GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
         GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
         GPIO_Init(GPIOC, &GPIO_InitStructure);
      }
   }
   
   {
   #ifdef  VECT_TAB_RAM
     /* Set the Vector Table base location at 0x20000000 */ 
     NVIC_SetVectorTable(NVIC_VectTab_RAM, 0x0); 
   #else  /* VECT_TAB_FLASH  */
     /* Set the Vector Table base location at 0x08000000 */ 
     NVIC_SetVectorTable(NVIC_VectTab_FLASH, 0x0);   
   #endif
   }


#endif
   }

/******************************************************************************/
/********************** utility functions *************************************/


//this displays a value on the LEDs
void DispLEDs(unsigned char val)
    {
    //print value of the counter on the LEDs
#if ( _STR91x_ )
#if TRACE_SUPPORT
    GPIO_WRITEDATA_MASKED(myGPIO, val, 0x0F);
#else
    GPIO_WRITEDATA(myGPIO, val);
#endif
#endif

#if ( _STR71x_ )
    myGPIO->PD=val<<4;
#endif

#if ( _STR73x_ )
    myGPIO->PD=val;
#endif

#if ( _STR75x_ )
    myGPIO->PD = val<<10;
#endif
    
#if ( _STM32x_ )
    GPIO_Write(GPIOC, val<<6);
#endif
    }

#if PRINT
#else
//counter...
volatile int delaycnt;

//this adds a delay for allowing to see the LEDs blinking
void delay()
    {
#if ( _STR71x_ )
    for(delaycnt=0;delaycnt<1000;delaycnt++);
#endif
#if ( _STR73x_ )
    for(delaycnt=0;delaycnt<1000;delaycnt++);
#endif
#if ( _STR75x_ )
    for(delaycnt=0;delaycnt<100000;delaycnt++);
#endif
#if ( _STR91x_ )
    for(delaycnt=0;delaycnt<10000;delaycnt++);
#endif
#if ( _STM32x_ )
    for(delaycnt=0;delaycnt<100000;delaycnt++);
#endif
    }
#endif


/*************************************************************************/
/********************** main program *************************************/

//this is the counter
volatile unsigned char i=0x55;

volatile unsigned long j=0x0020000;

//uncomment this line if you want the main function to be located
// in the FLASH BLOCK 1, if there is one (by default, all code goes in BLOCK 0)
//int main() __attribute__ ((section (".b1text")));

int main()
    {
    //delay for debug
    while(j--);

    config();

#if PRINT
    //print hello message on the UART
    print("Hello world!\n",0);
#endif

    while(1)
        {
#if PRINT
        //incremented echo
        putchar(getchar()+1);
#endif
        //increment the counter
        i++;
        //print value of the counter on the LEDs
        DispLEDs(i);

#if PRINT
        //print value of the counter on the UART
        print("  i=%d\n",i);
#else
        //delay to let time to see the LEDs
        delay();
#endif
        }

    //this will never be executed. (and is probably optimized out)	
    // but it avoids a warning when compiling
    return 0;
    }



