示例#1
0
/*********************************************************************
 *
 *  main()
 *
 *********************************************************************/
void main()
{
    char rxdata;
  /******************************************************************
   *
   *  Place your code here.
   ******************************************************************/
  int cnt;
  cnt = 0;
  InitUSART();
  printf("this is example for printf from library\r\n");
  do {
#ifndef USE_UART_INTR
		if (UART_GetChar(USART2, &rxdata) == 0)
		{
		}
		else
		{
            outbyte(rxdata);
            if(rxdata==0x0d)
                outbyte(0x0a);
		}
#endif
    cnt++;
  } while (1);
}
示例#2
0
/**
 * Reads an integer
 *
 * \param pdwValue  Pointer to a integer variable to contain the input value.
 *
 * \return success(1) or failure(0)
 */
extern uint32_t UART_GetInteger( int32_t* pdwValue )
{
    uint8_t ucKey ;
    uint8_t ucNum = 0 ;
    int32_t dwValue = 0 ;
    int32_t sign = 1 ;

    while ( 1 )
    {
        ucKey=UART_GetChar() ;
        UART_PutChar( ucKey ) ;

        if ( ((ucKey == '-') || (ucKey == '+')) && (ucNum == 0) )
        {
            if (ucKey == '-')
            {
                sign = -1;
            }
            else
            {
                sign = 1;
            }
            ucNum++;
        }
        else
        {
            if ( ucKey >= '0' &&  ucKey <= '9' )
            {
                dwValue = (dwValue * 10) + (ucKey - '0');
                ucNum++;
            }
            else
            {
                if ( ucKey == 0x0D || ucKey == ' ' )
                {
                    if ( ucNum == 0 )
                    {
                        printf( "\n\rWrite a number and press ENTER or SPACE!\n\r" ) ;
                        return 0 ;
                    }
                    else
                    {
                        printf( "\n\r" ) ;
                        *pdwValue = dwValue * sign;

                        return 1 ;
                    }
                }
                else
                {
                    printf( "\n\r'%c' not a number or sign(+/-)!\n\r", ucKey ) ;

                    return 0 ;
                }
            }
        }
    }
}
示例#3
0
void UART_ReceiveBuffer(Uart *uart, uint8_t *pBuffer, uint32_t BuffLen)
{
	uint32_t Len =0;

	for(Len =0; Len<BuffLen; Len++ ) {
		*pBuffer = UART_GetChar(uart);
		pBuffer++;
	}
}
示例#4
0
文件: main.c 项目: cxjlante/at91sam3s
/**
 * \brief Get 2 digit numkey.
 *
 * \return numkey value
 */
static uint32_t _GetNumkey2Digit( void )
{
    uint32_t numkey;
    uint8_t key1, key2;

    printf("\n\rEnter 2 digits : ");
#if defined (  __GNUC__  )
        fflush(stdout);
#endif
    key1 = UART_GetChar();
    printf("%c", key1);
    key2 = UART_GetChar();
    printf("%c", key2);
    printf("\n\r");

    numkey = (key1 - '0')*10 + (key2 - '0');

    return numkey;
}
示例#5
0
/**
 *  \brief Interrupt handler for UART0.
 *
 */
void UART0_IrqHandler(void)
{
    uint32_t status;

    /* Read USART status*/
    status = UART0->UART_SR;

    /* Receive byte is stored in buffer. */
    if ((status & UART_SR_RXRDY) == UART_SR_RXRDY) {
		if(us1.count < US_BUFFER_SIZE){
	    	us1.buff[us1.head++] = UART_GetChar();
			us1.count++;
			if(us1.head >= US_BUFFER_SIZE)
				us1.head = 0;
	  	}
		else{
			us1.buff[us1.head] = UART_GetChar();
		}
    }
}
示例#6
0
int fgetc(FILE *f) {
	uint8_t tempch = UART_GetChar();

	UART_PutChar(tempch);
	if(tempch == '\r')
	{
		UART_PutChar('\n');
		return '\n';
	}
	else
		return tempch;
}
示例#7
0
// Function __readc() / __sys_readc
//
// Called by bottom level of scanf routine within RedLib C library to read
// a character. With the default semihosting stub, this would read the character
// from the debugger console window (which acts as stdin). But this version reads
// the character from the LPC11C14 UART.
int READFUNC (void)
{
	char c = UART_GetChar();
	UART_PutChar(c);
	if(c == '\r')
	{
		UART_PutChar('\n');
		return (int)'\n';
	}
	else
		return (int)c;
}
示例#8
0
int main(){
	UART_Init((F_CPU / (16UL * 9600)) - 1);
	
	while(1){
		if(UART_DataReady()){
			uint8_t byte = UART_GetChar(); 
			toggle_led(byte); 
			UART_PutChar(PORTC & LED_MASK); 
		}
	} 
	return 0; 
}
示例#9
0
文件: main.c 项目: cxjlante/at91sam3s
/**
 * \brief Application entry point for spi_slave example.
 *
 * \return Unused (ANSI-C compatibility).
 */
extern int main( void )
{
    uint8_t ucKey ;

    /* Disable watchdog */
    WDT_Disable( WDT ) ;

    /* Output example information */
    printf( "-- spi slave example %s --\n\r", SOFTPACK_VERSION ) ;
    printf( "-- %s\n\r", BOARD_NAME ) ;
    printf( "-- Compiled: %s %s --\n\r", __DATE__, __TIME__ ) ;

    /* Configure PIO Pins for SPI */
    PIO_Configure( pSpiPins, PIO_LISTSIZE( pSpiPins ) ) ;

    /* Configure SPI interrupts for Slave only*/
    NVIC_DisableIRQ( SPI_IRQn ) ;
    NVIC_ClearPendingIRQ( SPI_IRQn ) ;
    NVIC_SetPriority( SPI_IRQn, 0 ) ;
    NVIC_EnableIRQ( SPI_IRQn ) ;

    SpiSlaveInitialize() ;

    /* Display menu */
    DisplayMenu() ;

    while ( 1 )
    {
        ucKey = UART_GetChar() ;

        switch ( ucKey )
        {
            case 'h' :
                DisplayMenu() ;
            break ;

            case 't' :
                SpiMasterGo() ;
            break ;

            default :
                /* Set configuration #n */
                if ( (ucKey >= '0') && (ucKey <= ('0' + NUM_SPCK_CONFIGURATIONS - 1)) )
                {
                    SetClockConfiguration( ucKey - '0' ) ;
                }
            break ;
        }
    }
}
示例#10
0
size_t __read(int handle,unsigned char *buf,size_t bufSize)
{
  size_t i;
  for (i=0x0; i<bufSize;i++)
  {
    buf[i] = UART_GetChar();
    UART_PutChar(buf[i]);
    if(buf[i] == '\r')
    {
      UART_PutChar('\n');
      buf[i] = '\n';
    }
  }
  return i;
}
示例#11
0
static void uartCheck(void)
{
	bool rx = false;
	bool tx = false;
	UART0_Task(&rx, &tx);
	
	if (rx)
	{
		txrxBuffer[rxIndex] = UART_GetChar(UART0, NULL);
				
		if (strlen(txrxBuffer) == LLAP_MESSAGE_LENGTH)
		{
			LLAP_HandleIncomingMessage(&llapDevice, txrxBuffer);
			rxIndex = 0;
		}
	}
}
示例#12
0
int _read(int file, char *ptr, int len) {

#if 0
	//user code example
	int i;
	(void)file;

	for(i = 0; i < len; i++)
	{
		// UART_GetChar is user's basic input function
		*ptr++ = UART_GetChar();
	}

#endif

	return len;
}
int Timer_InterTimerTriggerMode(void)
{
    int volatile i;

    /* Init System, IP clock and multi-function I/O
       In the end of SYS_Init() will issue SYS_LockReg()
       to lock protected register. If user want to write
       protected register, please issue SYS_UnlockReg()
       to unlock protected register if necessary */
    SysInit();

    /* Init UART to 115200-8n1 for print message */
    UART_Open(UART0, 115200);

    /* This sample code demonstrate inter timer trigger mode using Timer0 and Timer1
     * In this mode, Timer0 is working as counter, and triggers Timer1. Using Timer1
     * to calculate the amount of time used by Timer0 to count specified amount of events.
     * By dividing the time period recorded in Timer1 by the event counts, we get
     * the event frequency.
     */
    printf("Inter timer trigger mode demo code\n");
    printf("Please connect input source with Timer 0 counter pin PB.8, press any key to continue\n");
    UART_GetChar();

    // Give a dummy target frequency here. Will over write prescale and compare value with macro
    TIMER_Open(TIMER0, TIMER_ONESHOT_MODE, 100);

    // Update prescale and compare value. Calculate average frequency every 1000 events
    TIMER_SET_PRESCALE_VALUE(TIMER0, 0);
    TIMER_SET_CMP_VALUE(TIMER0, 1000);

    // Update Timer 1 prescale value. So Timer 1 clock is 1MHz
    TIMER_SET_PRESCALE_VALUE(TIMER1, 11);

    // We need capture interrupt
    NVIC_EnableIRQ(TMR1_IRQn);

    while(1) {
        complete = 0;
        // Count event by timer 0, disable drop count (set to 0), disable timeout (set to 0). Enable interrupt after complete
        TIMER_EnableFreqCounter(TIMER0, 0, 0, TRUE);
        while(complete == 0);
    }

}
示例#14
0
void Console_Input_Char(){
	char c = UART_GetChar();
	if(c==10 || c==13){
		UART_Print("\n\r");
		Command_Parse(linebuffer, lbufsize);
		lbufsize = 0;
	}else if(c==127){ // backspace
		if(lbufsize>0){
			linebuffer[--lbufsize] = 0;
			UART_Print(c);
		}
	}else if(c >= 32){ // not a control-char
		if(lbufsize<sizeof(linebuffer)){
			linebuffer[lbufsize++] = c;
			UART_Print(c);
		}
	}
}
示例#15
0
/**
 *  Reads an integer
 *
 *  \param pdwValue  Pointer to the uint32_t variable to contain the input value.
 */
extern uint32_t UART_GetInteger( uint32_t* pdwValue )
{
    uint8_t ucKey ;
    uint8_t ucNbNb=0 ;
    uint32_t dwValue=0 ;

    while ( 1 )
    {
        ucKey=UART_GetChar() ;
        UART_PutChar( ucKey ) ;

        if ( ucKey >= '0' &&  ucKey <= '9' )
        {
            dwValue = (dwValue * 10) + (ucKey - '0');
            ucNbNb++ ;
        }
        else
        {
            if ( ucKey == 0x0D || ucKey == ' ' )
            {
                if ( ucNbNb == 0 )
                {
                    printf( "\n\rWrite a number and press ENTER or SPACE!\n\r" ) ;
                    return 0 ;
                }
                else
                {
                    printf( "\n\r" ) ;
                    *pdwValue=dwValue ;

                    return 1 ;
                }
            }
            else
            {
                printf( "\n\r'%c' not a number!\n\r", ucKey ) ;

                return 0 ;
            }
        }
    }

    return 0;
}
示例#16
0
/**
 *  Reads an hexadecimal number
 *
 *  \param pdwValue  Pointer to the uint32_t variable to contain the input value.
 */
extern uint32_t UART_GetHexa32( uint32_t* pdwValue )
{
    uint8_t ucKey ;
    uint32_t dw = 0 ;
    uint32_t dwValue = 0 ;

    for ( dw=0 ; dw < 8 ; dw++ )
    {
        ucKey = UART_GetChar() ;

        UART_PutChar( ucKey ) ;

        if ( ucKey >= '0' &&  ucKey <= '9' )
        {
            dwValue = (dwValue * 16) + (ucKey - '0') ;
        }
        else
        {
            if ( ucKey >= 'A' &&  ucKey <= 'F' )
            {
                dwValue = (dwValue * 16) + (ucKey - 'A' + 10) ;
            }
            else
            {
                if ( ucKey >= 'a' &&  ucKey <= 'f' )
                {
                    dwValue = (dwValue * 16) + (ucKey - 'a' + 10) ;
                }
                else
                {
                    printf( "\n\rIt is not a hexa character!\n\r" ) ;

                    return 0 ;
                }
            }
        }
    }

    printf("\n\r" ) ;
    *pdwValue = dwValue ;

    return 1 ;
}
示例#17
0
void USART2_IRQHandler(void)
{
	char rxData;
	int rxEmpty = 0;
	int count = 0;

	while (!rxEmpty)
	{
		if (UART_GetChar(USART2, &rxData) == 0)
		{
			if(count == 0x1000)
				rxEmpty = 1;
			count++;
		}
		else
		{
            outbyte(rxData);
            if(rxdata==0x0d)
                outbyte(0x0a);
		}
	}
}
示例#18
0
//-----------------------------------------------------------------------------
// FUNCTION:    main
// SCOPE:       Bootloader application system function
// DESCRIPTION: bootloader main function             
// RETURNS:     0
//----------------------------------------------------------------------------- 
int main(void)
{	
    volatile unsigned long loop_counter = 0;    // counter of loop without received frame

    Byte enableBootMode = 0; 			//  0: enter APP, 1: enter BOOT mode, 2: enter verify mode
    //Byte s19buffer[WR_BLOCK_BYTE] = {1};        //extract app file burning code from received frame, store them to s19buffer[]

    DisableInterrupts;


    INIT_CLOCKS_TO_MODULES;			// init clock module
    Boot_Button_Init();  			// init SW3 button (PTC3 port) on FRDM_K22 board
    INIT_BOOT_LED;
    //  condition for entering boot:
    if(((*(unsigned long*)(RELOCATED_VECTORS + 8)) == 0xffffffff)                          //1. no valid code in APP vector section,
    || Boot_StrCompare(( Byte*)APPOK_START_ADDRESS, str_app_ok, APPOK_LENGTH) == CHECK_FAIL	   //2."APP_OK" is wrong in address APPOK_START_ADDRESS.
    || ((GPIO_PDIR_REG(BOOT_PIN_ENABLE_GPIO_BASE) & (1 << BOOT_PIN_ENABLE_NUM)) == 0)      //3. SW1 is pressed
    || (AppIDC == 0x0000000B))                                                             //4. App request boot
    {
        enableBootMode = 1; // enable boot
        BOOT_LED_ON;
        AppIDC = 0;
    }
    else if (AppIDC == 0x0000000A)   // App request verify
    {
        enableBootMode = 2; // enable verify mode
        BOOT_LED_ON;
        AppIDC = 0;
    }
    if(enableBootMode)
    {
    // if use external clock
#ifdef USE_EXTERNAL_CLOCK
        Boot_Init_Clock();
#endif
        PIN_INIT_AS_UART;   			// set PTEA1/UART1_RX and PTE0/UART1_TX pins as UART
        UART_Initialization();  		// init UART module
    }   
    ////////////////////////////////////////////////////////////////////////
    //BOOT Model
    ////////////////////////////////////////////////////////////////////////
    while(enableBootMode)  // enter boot or verify mode, execute all command from GUI
    {        
        volatile Byte frame_start_flag  = 0;    // if frame header is received. 1: receive $, start to receive frame;  0: no $ received
        volatile Byte frame_length 	= 0xFF;    // SCI received frame length, initialized as 0xFF
        volatile Byte data_length = 0;
        volatile Byte buff_index = 1;   	   // receive buffer index for sci_buffer[]
        volatile Byte data_checked  = 0; 	   // check frame end 0xAA 0x55. 1: correct frame ; 0: wrong frame
        WDG_Refresh();
        FLASH_Initialization();

        sci_buffer[0] = UART_GetChar();
        if( sci_buffer[0] == '$') 			//check frame header: whether it is '$'
        {
            loop_counter = 0;
            frame_start_flag  = 1;
        }

        if(frame_start_flag == 1)
        {
            sci_buffer[1] = UART_GetChar();     // sci_buffer[1] is the station number
            UART_GetChar();   					// sci_buffer[2] is reserved
            sci_buffer[3] = UART_GetChar();     // sci_buffer[3] is the Data length
            data_length = sci_buffer[3];
            frame_length = 4 + sci_buffer[3] + 2;  // frame_length = frame head + data + frame end
            buff_index = 4;
            while(data_length --)
                      sci_buffer[buff_index ++] = UART_GetChar();
            sci_buffer[buff_index ++] = UART_GetChar();  // frame end. It should be 0xAA
            sci_buffer[buff_index ++] = UART_GetChar();  // frame end. It should be 0x55
            frame_start_flag = 0;
        }

        if((sci_buffer[frame_length-2] == 0xAA) && (sci_buffer[frame_length-1] == 0x55)) //Check if Frame end is correct
        {
            data_checked = 1; //  Correct frame received.
        }

       // all the data in frame was correctly received (data_checked = 1) above, now perform frame analysis below.
       // sci_buffer[] now is switched to tx buffer
        if(data_checked == 1)
        {
            Byte i = 0;
            Byte j = 0;
            Byte burn_data_length = 0;
            Byte s19buffer[WR_BLOCK_BYTE]; //extract app file burning code from received frame, store them to s19buffer[]

            //WDG_Refresh();
            switch(sci_buffer[4])
            {
                case 'I':	// receive 'I' command, send  version information to UART
                            i = 4;
                            while((sci_buffer[i] = MCU_Identification.targ_name[i-4]) !='\0')	//assign chip part number info to sci_buffer[]
                            {
                                    i++;
                            }
                            sci_buffer[i++] = '#';
                            j = i;
                            while((sci_buffer[i] = MCU_Identification.Boot_version[i-j]) !='\0')	//assign bootloader version info to sci_buffer[]
                            {
                                    i++;
                            }
                            sci_buffer[i++] = '#';
                            sci_buffer[i++] = (MCU_Identification.wrblk & 0xFF00)>>8;		//assign write block size
                            sci_buffer[i++] = MCU_Identification.wrblk & 0x00FF;

                            sci_buffer[i++] = (MCU_Identification.erblk & 0xFF00)>>8;		//assign erase block size
                            sci_buffer[i++] = MCU_Identification.erblk & 0x00FF;

                            sci_buffer[i++] = MCU_Identification.addr_limit.Bytes.hl;		 //assign MCU Flash end address
                            sci_buffer[i++] = MCU_Identification.addr_limit.Bytes.lh;
                            sci_buffer[i++] = MCU_Identification.addr_limit.Bytes.ll;

                            sci_buffer[i++] = MCU_Identification.dontcare_addrl.Bytes.hl;		//assign bootloader dont care memory start adddress
                            sci_buffer[i++] = MCU_Identification.dontcare_addrl.Bytes.lh;
                            sci_buffer[i++] = MCU_Identification.dontcare_addrl.Bytes.ll;

                            sci_buffer[i++] = MCU_Identification.dontcare_addrh.Bytes.hl;		//assign bootloader dont care memory end adddress
                            sci_buffer[i++] = MCU_Identification.dontcare_addrh.Bytes.lh;
                            sci_buffer[i++] = MCU_Identification.dontcare_addrh.Bytes.ll;

                            sci_buffer[i++] = MCU_Identification.relocated_vectors.Bytes.hl;		//assign bootloader start adddress
                            sci_buffer[i++] = MCU_Identification.relocated_vectors.Bytes.lh;
                            sci_buffer[i++] = MCU_Identification.relocated_vectors.Bytes.ll;

                            sci_buffer[i++] = MCU_Identification.targ_core; 	// target is M4 core
                            
                            sci_buffer[3] = i - 4;   // tx data length in one frame 
                            Boot_Send(sci_buffer);
                            if(enableBootMode == 1)  // if in boot mode
                                FLASH_EraseSector((LWord)APPOK_START_ADDRESS);	//erase APP_OK
                            WDG_Refresh();
                            break;

                case 'E':	// receive 'E' command, erase sector, then send confirm frame to UART
                            Boot_ReadAddress();
                            if(!( FLASH_EraseSector(address.complete)))
                            {
                                sci_buffer[3] = 00;
                                Boot_Send(sci_buffer);
                            }
                            WDG_Refresh();
                            break;

                case'W':	// receive 'W' command, extract app  burning code,  program flash. then send confirm frame to UART
                            Boot_ReadAddress();
                            burn_data_length = sci_buffer[8];
                            for(j=0,i=9;j<burn_data_length;j++,i++) // extract the prepared writing data from sci_buff[] to S19buffer[]
                            {
                                s19buffer[j] = sci_buffer[i];
                            }
                            if(!(FLASH_ProgramSectionByLongs (address.complete, (LWord*)s19buffer, burn_data_length/4)))
                            {
                                sci_buffer[3] = 00;
                                Boot_Send(sci_buffer);
                                
                            }
                            WDG_Refresh();
                            break;
                case'R':	// receive 'R' command, read out the memory data, then send the data in frame to UART
                            Boot_ReadAddress();
                            burn_data_length = sci_buffer[8];
                            for(i=0;i<burn_data_length;i++)
                            {
                                sci_buffer[i + 4] = ((Byte*)(address.complete))[i];
                            }
                            sci_buffer[3] = burn_data_length;
                            Boot_Send(sci_buffer);
                            WDG_Refresh();
                            break;

                case'G':	// receive 'G' command, go to app.
                            if(enableBootMode == 1)
                            FLASH_ProgramSectionByLongs ((LWord)APPOK_START_ADDRESS, (LWord*)str_app_ok, APPOK_LENGTH/4);
                            //BOOT_LED_OFF;
                            NVIC_SystemReset();
                            break;

                default :
                            break;
            }// end switch(sci_buffer[4])
            frame_start_flag  = 0;
            for (buff_index = 0; buff_index<FRAME_BUFF_LENGTH; buff_index++)	// clear sci_buffer[]
                sci_buffer[buff_index] = 0;

          }// end if(data_checked == 1)
          loop_counter ++;
          if(loop_counter >= 10 && enableBootMode == 2)                         // 100 * timeout of UART_GetChar();
          {
              NVIC_SystemReset();
          }
    }// end while(enableBootMode)
示例#19
0
文件: aprom.c 项目: clarenceliu/Mplib
int aprom()
{
    uint8_t     u8Item;
    uint32_t    u32Data;
    char *acBootMode[] = {"LDROM+IAP", "LDROM", "APROM+IAP", "APROM"};
    uint32_t u32CBS;

    /* Unlock protected registers */
    SYS_UnlockReg();

    /* Init system clock and multi-function I/O */
    SYS_Init();

    /* Init UART */
    UART_Init();

    printf("\n\n");
    printf("+----------------------------------------+\n");
    printf("|      NUC029 FMC IAP Sample Code          |\n");
    printf("|           [APROM code]                 |\n");
    printf("+----------------------------------------+\n");


    /* Enable FMC ISP function */
    FMC_Open();

    if(SetIAPBoot() < 0)
    {
        printf("Failed to set IAP boot mode!\n");
        goto lexit;
    }

    /* Get boot mode */
    printf("  Boot Mode ............................. ");
    u32CBS = (FMC->ISPSTA & FMC_ISPSTA_CBS_Msk) >> FMC_ISPSTA_CBS_Pos;
    printf("[%s]\n", acBootMode[u32CBS]);

    u32Data = FMC_ReadCID();
    printf("  Company ID ............................ [0x%08x]\n", u32Data);

    u32Data = FMC_ReadDID();
    printf("  Device ID ............................. [0x%08x]\n", u32Data);

    u32Data = FMC_ReadPID();
    printf("  Product ID ............................ [0x%08x]\n", u32Data);

    /* Read User Configuration */
    printf("  User Config 0 ......................... [0x%08x]\n", FMC_Read(FMC_CONFIG_BASE));
    printf("  User Config 1 ......................... [0x%08x]\n", FMC_Read(FMC_CONFIG_BASE + 4));

    do
    {
        printf("\n\n\n");
        printf("+----------------------------------------+\n");
        printf("|               Select                   |\n");
        printf("+----------------------------------------+\n");
        printf("| [0] Load IAP code to LDROM             |\n");
        printf("| [1] Run IAP program (in LDROM)         |\n");
        printf("+----------------------------------------+\n");
        printf("Please select...");
        u8Item = UART_GetChar();
        printf("%c\n", u8Item);

        switch(u8Item)
        {
        case '0':
            FMC_EnableLDUpdate();
            if(LoadImage((uint32_t)&loaderImage1Base, (uint32_t)&loaderImage1Limit,
                         FMC_LDROM_BASE, FMC_LDROM_SIZE) != 0)
            {
                printf("Load image to LDROM failed!\n");
                goto lexit;
            }
            FMC_DisableLDUpdate();
            break;

        case '1':
            printf("\n\nChange VECMAP and branch to LDROM...\n");
            UART_WAIT_TX_EMPTY(UART0); /* To make sure all message has been print out */

            /* Mask all interrupt before changing VECMAP to avoid wrong interrupt handler fetched */
            __set_PRIMASK(1);

            /* Set VECMAP to LDROM for booting from LDROM */
            FMC_SetVectorPageAddr(FMC_LDROM_BASE);

            /* Software reset to boot to LDROM */
            NVIC_SystemReset();

            break;

        default :
            break;
        }
    }
    while(1);


lexit:

    /* Disable FMC ISP function */
    FMC_Close();

    /* Lock protected registers */
    SYS_LockReg();

    printf("\nFMC Sample Code Completed.\n");

    while(1);
}
示例#20
0
int16 iot_atcmd_detect(uint8* pType)
{
    uint8 ch = 0;
    int32 read = -1;
    int16 ret_len = 0;

    static uint8  CmdType = PKT_UNKNOWN;
    static uint8  ATMatchNum = 0;
    static uint8  IWMatchNum = 0;
    char ATCmdPrefixAT[]=AT_CMD_PREFIX;
    char ATCmdPrefixIW[]=AT_CMD_PREFIX2;

    if (UART_LSROverErr() != 0)
        return -1;

    /*Notice: Must not use printf_high in the while block,  the Rx FIFO,RxINT and ringbuf will mess*/
    while (1) {
        read = UART_GetChar((uint8*)&ch);

        if (read == -1)
            return -1;

#if (UARTRX_TO_AIR_LEVEL == 1)
        uart_rb_push(ch);

#elif (UARTRX_TO_AIR_LEVEL == 2)
        if (iot_uart_rx_mode == UARTRX_PUREDATA_MODE) {
            if (cmd_len >= AT_CMD_MAX_LEN) {
                cmd_len = 0;
            }
            command[cmd_len] = ch;
            cmd_len++;
            continue;
        }
#endif

        if (CmdType == PKT_UNKNOWN) {
            /*case 1:AT#*/
            if (ATCmdPrefixAT[ATMatchNum] == ch)
                ATMatchNum++;
            else
                ATMatchNum = 0;

            /*case 2:iwpriv ra0*/
            if (ATCmdPrefixIW[IWMatchNum] == ch)
                IWMatchNum++;
            else
                IWMatchNum = 0;

            if (( ATMatchNum == sizeof(ATCmdPrefixAT)-1 ) ||   //match case 1: AT#
                ( IWMatchNum == sizeof(ATCmdPrefixIW)-1 ) ) {  //match case 2:iwpriv ra0
                if ( ATMatchNum == sizeof(ATCmdPrefixAT)-1 )
                    CmdType = PKT_ATCMD;             //match case 1: AT#
                else if ( IWMatchNum == sizeof(ATCmdPrefixIW)-1 )
                    CmdType = PKT_IWCMD;             //match case 2:iwpriv ra0

                ATMatchNum = 0;
                IWMatchNum = 0;
                continue;
            }
        } else if ((PKT_ATCMD == CmdType) || (PKT_IWCMD == CmdType)) {
            if (ch == '\n' || ch == '\r') {
                *pType = CmdType;
                CmdType = PKT_UNKNOWN;
                ret_len = cmd_len;   /*not include '\n'*/
                cmd_len = 0;
                return ret_len;
            } else {
                command[cmd_len] = ch;
                cmd_len++;
                if (cmd_len >= AT_CMD_MAX_LEN) {
                    CmdType = PKT_UNKNOWN;
                    cmd_len = 0;
                    return -2;
                }
            }
        }
    }
    return 0;

}
示例#21
0
void handle_mav_link_mess(void)
{

	int i,j;


	mavlink_message_t msg;
	mavlink_status_t status;
	mavlink_param_set_t set;
	char* key;

	while(UART_CharAvailable())
	{
		uint8_t c = UART_GetChar();
		if(mavlink_parse_char(0, c, &msg, &status))
		{
			switch(msg.msgid)
			{
				case MAVLINK_MSG_ID_PARAM_REQUEST_READ:
				break;
				case MAVLINK_MSG_ID_PARAM_REQUEST_LIST:
					param = 0;
				break;
				case MAVLINK_MSG_ID_PARAM_SET:
				{
					mavlink_msg_param_set_decode(&msg, &set);
					key = (char*) set.param_id;
					for (i = 0; i < ONBOARD_PARAM_COUNT; i++)
						{
							uint8_t match = 1;
							for (j = 0; j < ONBOARD_PARAM_NAME_LENGTH; j++)
							{
								// Compare
								if (((char) (global_data.param_name[i][j]))	!= (char) (key[j]))
								{
									match = 0;
								}

								// End matching if null termination is reached
								if (((char) global_data.param_name[i][j]) == '\0')
								{
									break;
								}
							}

							// Check if matched
							if (match)
							{
								// Only write and emit changes if there is actually a difference
								// AND only write if new value is NOT "not-a-number"
								// AND is NOT infy
								if (global_data.param[i] != set.param_value)
								{
									global_data.param[i] = set.param_value;
									// Report back new value
									mavlink_msg_param_value_send(MAVLINK_COMM_0,
											(int8_t*) global_data.param_name[i],
											global_data.param[i], ONBOARD_PARAM_COUNT, param);
								}
							}
						}
				}
				break;

			}
		}
	}

	if (param < ONBOARD_PARAM_COUNT)
		{
			mavlink_msg_param_value_send(0,
					(int8_t*) global_data.param_name[param],
					global_data.param[param], ONBOARD_PARAM_COUNT, param);
			param++;
		}
}
示例#22
0
文件: main.c 项目: cxjlante/at91sam3s
/**
 * \brief Application entry point.
 *
 * Configures USART1 in spi master/slave mode and SPI in slave/master mode,start
 * a transmission between two peripherals.
 * \return Unused.
 */
extern int main( void )
{
    char c ;
    char data = 0x0 ;

    /* Disable watchdog */
    WDT_Disable( WDT ) ;

    /*  Configure pins */
    PIO_Configure( pins, PIO_LISTSIZE( pins ) ) ;

    /* Example information log */
    printf( "-- USART SPI Mode Example %s --\n\r", SOFTPACK_VERSION ) ;
    printf( "-- %s\n\r", BOARD_NAME ) ;
    printf( "-- Compiled: %s %s --\n\r", __DATE__, __TIME__ ) ;

    /* display main menu*/
    _DisplayMainmenu() ;

    /* configure USART1 in  Master and SPI in slave mode*/
    _ConfigureUsart( STATE_UM_SS ) ;
    _ConfigureSpi( STATE_UM_SS ) ;

    printf( "--  USART1 as MASTER,SPI as SLAVE.--\n\r" ) ;

    while ( 1 )
    {
        c = UART_GetChar() ;
        switch ( c )
        {
            case 'w':
            case 'W':
            if ( glob_state == STATE_UM_SS )
            {
                data = SPI->SPI_RDR;
                printf( "0x%x\n\r", data ) ;

                /* slave in */
                SPI_ReadBuffer( SPI, pRecvBufferSPI, BUFFER_SIZE ) ;
                SPI_EnableIt( SPI, SPI_IER_RXBUFF ) ;
                /* master out*/
                USART_WriteBuffer( BOARD_USART_BASE, Buffer, BUFFER_SIZE ) ;
                while ( !recvDone ) ;

                if ( recvDone )
                {
                    printf( "----USART1 MASTER WRITE----\n\r" ) ;

                    if ( strncmp( pRecvBufferSPI, Buffer, BUFFER_SIZE ) )
                    {
                        printf( " -F-: Failed!\n\r" ) ;
                    }
                    else
                    {
                       /* successfully received*/
                       _DumpInfo( pRecvBufferSPI, BUFFER_SIZE ) ;
                    }
                    printf( "----END of USART1 MASTER WRITE----\n\r" ) ;
                    memset( pRecvBufferSPI, 0, sizeof( pRecvBufferSPI ) ) ;
                    recvDone = false ;
                }
            }
            else
            {
                data = USART1->US_RHR ;
                printf( "US_RHR:0x%x\n\r", data ) ;

                /* slave in */
                USART_ReadBuffer( USART1, pRecvBufferUSART1, BUFFER_SIZE ) ;
                USART_EnableIt( USART1, US_IER_RXBUFF ) ;
                printf( "----SPI MASTER WRITE----\n\r" ) ;

                /* master out*/
                SPI_WriteBuffer( SPI, Buffer, BUFFER_SIZE ) ;
                while ( !recvDone ) ;
                if ( recvDone )
                {
                    if ( strncmp( pRecvBufferUSART1, Buffer, BUFFER_SIZE ) )
                    {
                       printf( " -F-: Failed!\n\r" ) ;
                    }
                    else
                    {
                       /* successfully received*/
                       _DumpInfo( pRecvBufferUSART1, BUFFER_SIZE ) ;
                    }

                    printf( "----END of SPI MASTER WRITE----\n\r" ) ;
                    memset( pRecvBufferUSART1, 0, sizeof( pRecvBufferUSART1 ) ) ;
                    recvDone = false ;
                }
            }
            break ;

            case 'r':
            case 'R':
            if ( glob_state == STATE_UM_SS )
            {
                data = USART1->US_RHR ;
                printf( "US_RHR:0x%x\n\r", data ) ;

                /* slave out */
                SPI_WriteBuffer( SPI, Buffer, BUFFER_SIZE ) ;

                /* master read */
                USART_ReadBuffer( USART1, pRecvBufferUSART1, BUFFER_SIZE ) ;
                USART_EnableIt( USART1, US_IER_RXBUFF ) ;

                /* start transmission */
                USART_WriteBuffer( BOARD_USART_BASE, Buffer1, BUFFER_SIZE ) ;
                printf( "----USART1 MASTER READ----\n\r" ) ;
                while ( !recvDone ) ;

                if ( recvDone )
                {
                    if ( strncmp( pRecvBufferUSART1, Buffer, BUFFER_SIZE ) )
                    {
                       printf( " -F-: Failed!\n\r" ) ;
                    }
                    else
                    {
                       /* successfully received*/
                       _DumpInfo( pRecvBufferUSART1, BUFFER_SIZE ) ;
                    }
                    printf( "----END of USART1 MASTER READ----\n\r" ) ;
                    memset( pRecvBufferUSART1, 0, sizeof( pRecvBufferUSART1 ) ) ;
                    recvDone = false ;
                }
            }
            else
            {
                data = SPI->SPI_RDR ;
                printf( "SPI_RDR:0x%x\n\r", data ) ;

                /* slave out */
                USART_WriteBuffer( USART1, Buffer, BUFFER_SIZE ) ;
                printf( "----SPI MASTER READ----\n\r" ) ;

                /* master read */
                SPI_ReadBuffer( SPI, pRecvBufferSPI, BUFFER_SIZE ) ;
                SPI_EnableIt( SPI, SPI_IER_RXBUFF ) ;

                /* start transmission */
                SPI_WriteBuffer( SPI, Buffer1, BUFFER_SIZE ) ;
                while ( !recvDone ) ;

                if ( recvDone )
                {
                    if ( strncmp( pRecvBufferSPI, Buffer, BUFFER_SIZE ) )
                    {
                        printf( " -F-: Failed!\n\r" ) ;
                    }
                    else
                    {
                       /* successfully received */
                       _DumpInfo( pRecvBufferSPI, BUFFER_SIZE ) ;
                    }
                    printf("----END of SPI MASTER READ----\n\r");
                    memset(pRecvBufferSPI,0,sizeof(pRecvBufferSPI));
                    recvDone = false;
                }

            }
            break ;

            case 's':
            case 'S':
                if ( glob_state == STATE_UM_SS )
                {
                    glob_state = STATE_US_SM ;
                    _ConfigureUsart( glob_state ) ;
                    _ConfigureSpi( glob_state ) ;

                    printf( "-- USART1 as SLAVE,SPI as MASTER\n\r" ) ;

                }
                else
                {
                    glob_state = STATE_UM_SS ;
                    _ConfigureUsart( glob_state ) ;
                    _ConfigureSpi( glob_state ) ;

                    printf( "-- USART1 as MASTER,SPI as SLAVE\n\r" ) ;
                }
            break ;

            case 'm':
            case 'M':
                _DisplayMainmenu() ;
            break ;

        }

    }
}
示例#23
0
文件: main.c 项目: cxjlante/at91sam3s
/**
 * \brief Application entry point for PWM with PDC example.
 *
 * Outputs a PWM on LED1 & LED2 & LED3 to makes it fade in repeatedly.
 * Channel #0, #1, #2 are linked together as synchronous channels, so they have
 * the same source clock, the same period, the same alignment and
 * are started together. The update of the duty cycle values is made
 * automatically by the Peripheral DMA Controller (PDC).
 *
 * \return Unused (ANSI-C compatibility).
 */
int main(void)
{
    uint32_t i;
    uint8_t key;
    int32_t numkey;

    /* Disable watchdog */
    WDT_Disable( WDT ) ;

    /* Output example information */
    printf("-- PWM with PDC Example %s --\n\r", SOFTPACK_VERSION);
    printf("-- %s\n\r", BOARD_NAME);
    printf("-- Compiled: %s %s --\n\r", __DATE__, __TIME__);

    /* PIO configuration */
    PIO_Configure(pins, PIO_LISTSIZE(pins));

    /* Enable PWMC peripheral clock */
    PMC_EnablePeripheral(ID_PWM);

    /* Set clock A to run at PWM_FREQUENCY * MAX_DUTY_CYCLE (clock B is not used) */
    PWMC_ConfigureClocks(PWM_FREQUENCY * MAX_DUTY_CYCLE, 0, BOARD_MCK);

    /* Configure PWMC channel for LED0 (left-aligned, enable dead time generator) */
    PWMC_ConfigureChannelExt( PWM,
                              CHANNEL_PWM_LED0,  /* channel */
                              PWM_CMR_CPRE_CKA,  /* prescaler */
                              0,                 /* alignment */
                              0,                 /* polarity */
                              0,                 /* countEventSelect */
                              PWM_CMR_DTE,       /* DTEnable */
                              0,                 /* DTHInverte */
                              0 );               /* DTLInverte */

    PWMC_SetPeriod(PWM, CHANNEL_PWM_LED0, MAX_DUTY_CYCLE);
    PWMC_SetDutyCycle(PWM, CHANNEL_PWM_LED0, MIN_DUTY_CYCLE);
    PWMC_SetDeadTime(PWM, CHANNEL_PWM_LED0, 5, 5);

    /* Configure PWMC channel for LED1 */
    PWMC_ConfigureChannelExt( PWM,
                              CHANNEL_PWM_LED1,  /* channel */
                              PWM_CMR_CPRE_CKA,  /* prescaler */
                              0,                 /* alignment */
                              0,                 /* polarity */
                              0,                 /* countEventSelect */
                              0,                 /* DTEnable */
                              0,                 /* DTHInverte */
                              0 );               /* DTLInverte */

    PWMC_SetPeriod(PWM, CHANNEL_PWM_LED1, MAX_DUTY_CYCLE);
    PWMC_SetDutyCycle(PWM, CHANNEL_PWM_LED1, MIN_DUTY_CYCLE);

    /* Configure PWMC channel for LED2 */
    PWMC_ConfigureChannelExt( PWM,
                              CHANNEL_PWM_LED2,  /* channel */
                              PWM_CMR_CPRE_CKA,  /* prescaler */
                              0,                 /* alignment */
                              0,                 /* polarity */
                              0,                 /* countEventSelect */
                              0,                 /* DTEnable */
                              0,                 /* DTHInverte */
                              0 );               /* DTLInverte */

    PWMC_SetPeriod(PWM, CHANNEL_PWM_LED2, MAX_DUTY_CYCLE);
    PWMC_SetDutyCycle(PWM, CHANNEL_PWM_LED2, MIN_DUTY_CYCLE);

    /* Set synchronous channels, update mode = 2 */
    PWMC_ConfigureSyncChannel(PWM,
                              (1 << CHANNEL_PWM_LED0) |
                              (1 << CHANNEL_PWM_LED1) |
                              (1 << CHANNEL_PWM_LED2),
                              PWM_SCM_UPDM_MODE2, //  (PWMC) Automatic write of data and automatic trigger of the update
                              0,
                              0);

    /* Set Synchronous channel update period value */
    PWMC_SetSyncChannelUpdatePeriod(PWM, PWM_SCUP_UPR(0xF));

    /* Configure interrupt for PDC transfer */
    NVIC_DisableIRQ(PWM_IRQn);
    NVIC_ClearPendingIRQ(PWM_IRQn);
    NVIC_SetPriority(PWM_IRQn, 0);
    NVIC_EnableIRQ(PWM_IRQn);
    PWMC_EnableIt(PWM, 0, PWM_IER2_ENDTX);

    /* Set override value to 1 on PWMH0, others is 0. */
    PWMC_SetOverrideValue(PWM, PWM_OOV_OOVH0);

    /* Fill duty cycle buffer for channel #0, #1 and #2 */
    /* For Channel #0, #1, #2 duty cycle are from MIN_DUTY_CYCLE to MAX_DUTY_CYCLE */
    for (i = 0; i < DUTY_BUFFER_LENGTH/3; i++) {
        dutyBuffer[i*3]   = (i + MIN_DUTY_CYCLE);
        dutyBuffer[i*3+1] = (i + MIN_DUTY_CYCLE);
        dutyBuffer[i*3+2] = (i + MIN_DUTY_CYCLE);
    }

    /* Define the PDC transfer */
    PWMC_WriteBuffer(PWM, dutyBuffer, DUTY_BUFFER_LENGTH);

    /* Enable syncronous channels by enable channel #0 */
    PWMC_EnableChannel(PWM, CHANNEL_PWM_LED0);

    while (1) {
        _DisplayMenu();
        key = UART_GetChar();

        switch (key) {
            case 'u':
                printf("Input update period between %d to %d.\n\r", 0, PWM_SCUP_UPR_Msk);
                numkey = _GetNumkey2Digit();
                if(numkey <= PWM_SCUP_UPR_Msk) {

                    /* Set synchronous channel update period value */
                    PWMC_SetSyncChannelUpdatePeriod(PWM, numkey);
                    printf("Done\n\r");
                } else {

                    printf("Invalid input\n\r");
                }
                break;
            case 'd':
                printf("Input dead time for channel #0 between %d to %d.\n\r",
                    MIN_DUTY_CYCLE, MAX_DUTY_CYCLE);
                numkey = _GetNumkey2Digit();
                if(numkey >= MIN_DUTY_CYCLE && numkey <= MAX_DUTY_CYCLE) {

                    /* Set synchronous channel update period value */
                    PWMC_SetDeadTime(PWM, CHANNEL_PWM_LED0, numkey, numkey);
                    /* Update synchronous channel */
                    PWMC_SetSyncChannelUpdateUnlock(PWM);
                    printf("Done\n\r");
                } else {

                    printf("Invalid input\n\r");
                }
                break;
            case 'o':
                printf("0: Disable override output on channel #0\n\r");
                printf("1: Enable override output on channel #0\n\r");
                key = UART_GetChar();

                if (key == '1') {

                    PWMC_EnableOverrideOutput(PWM, PWM_OSSUPD_OSSUPH0 | PWM_OSSUPD_OSSUPL0, 1);
                    printf("Done\n\r");
                } else if (key == '0') {

                    PWMC_DisableOverrideOutput(PWM, PWM_OSSUPD_OSSUPH0 | PWM_OSSUPD_OSSUPL0, 1);
                    printf("Done\n\r");
                }
                break;
            default:
                printf("Invalid input\n\r");
                break;
        }
    }
}
示例#24
0
/*---------------------------------------------------------------------------------------------------------*/
 I2C_Loopback (void)
{
    uint32_t i;

    /* Init System, IP clock and multi-function I/O */
    SysInit();

    /* Init UART to 115200-8n1 for print message */
    UART_Open(UART0, 115200);

    printf("+-------------------------------------------------------+\n");
    printf("|      Nano1x2 Series I2C Cross Test Sample Code        |\n");
    printf("+-------------------------------------------------------+\n");
    printf("  I/O Configuration:\n");
    printf("  SCK: GPC0 <--> GPC2\n");
    printf("  SDA: GPC1 <--> GPC3\n");
    printf("\n\n");
    printf("..... Press a key to continue ...\n");
    UART_GetChar();


    /* Configure I2C0 as master and I2C1 as slave */
    I2C0_Init();
    I2C1_Init();

    for (i = 0; i < 0x100; i++) {
        g_u8SlvData[i] = 0;
    }

    /* I2C function to Slave receive/transmit data */
    s_I2C1HandlerFn = (I2C_FUNC)I2C_SlaveTRx;

    g_u8DeviceAddr = SLAVE_ADDRESS;

    printf("Test Loop =>");
    for (i = 0; i < 0x100; i++) {
        printf("%d..", i);
        g_au8MasterTxData[0] = (uint8_t)((i & 0xFF00) >> 8);
        g_au8MasterTxData[1] = (uint8_t)(i & 0x00FF);
        g_au8MasterTxData[2] = (uint8_t)(g_au8MasterTxData[1] + 3);

        g_u8MasterDataLen = 0;
        g_u8EndFlag = 0;

        /* I2C function to write data to slave */
        s_I2C0HandlerFn = (I2C_FUNC)I2C_MasterTx;

        /* I2C as master sends START signal */
        I2C_SET_CONTROL_REG(I2C0, I2C_STA);

        /* Wait I2C Tx Finish */
        while (g_u8EndFlag == 0);
        g_u8EndFlag = 0;

        /* I2C function to read data from slave */
        s_I2C0HandlerFn = (I2C_FUNC)I2C_MasterRx;

        g_u8MasterDataLen = 0;
        g_u8DeviceAddr = SLAVE_ADDRESS;

        /* I2C as master sends START signal */
        I2C_SET_CONTROL_REG(I2C0, I2C_STA);

        /* Wait I2C Rx Finish */
        while (g_u8EndFlag == 0);

        /* Compare Tx and Rx data */
        if (g_u8MasterRxData != g_au8MasterTxData[2]) {
            printf("I2C Byte Write/Read Failed, Data 0x%x\n", g_u8MasterRxData);
            return -1;
        }
        printf("[OK]\n");
    }

    printf("\nTest Completely !!\n");
    while(1);
}
示例#25
0
文件: main.c 项目: cxjlante/at91sam3s
/*----------------------------------------------------------------------------*/
extern int main( void )
{
    uint8_t i;

    /* Disable watchdog */
    WDT_Disable( WDT ) ;

    /* Output example information */
    printf( "-- PIO Parallel Capture example %s --\n\r", SOFTPACK_VERSION ) ;
    printf( "-- %s\n\r", BOARD_NAME ) ;
    printf( "-- Compiled: %s %s --\n\r", __DATE__, __TIME__ ) ;

    printf( "Frequency: %d MHz\n\r", BOARD_MCK/1000000 ) ;

    printf( "  Press r to Receive data on PIO Parallel Capture\n\r" ) ;
    printf( "  Press s to Send data on PIO Parallel Capture\n\r" ) ;
    _ucKey = 0 ;
    while( (_ucKey != 'r') && (_ucKey != 's') )
    {
        _ucKey = UART_GetChar() ;
    }
    if( _ucKey == 'r')
    {
        printf("** RECEIVE mode **\n\r");
        PIO_InitializeInterrupts(0);
        /* Clear Recept buffer */
        for(i=0; i<SIZE_BUFF_RECEPT; i++)
        {
            _adwPIO_mes_rx[i]=0;
        }
        /* Init calback */
        /* PIO_PCRHR register is a WORD */
        _PioCapture.dsize = 2;
        _PioCapture.dPDCsize = 16;
        /* A word, 16x, so we wait 64 bytes */
        /* Buffer for received data */
        _PioCapture.pData = _adwPIO_mes_rx;

        printf("  Press y to samples the data when both data enables are active\n\r");
        printf("  Press n to samples the data whatever the data enables are\n\r");
        _ucKey = 0;
        while( (_ucKey != 'y') && (_ucKey != 'n') )
        {
            _ucKey = UART_GetChar();
        }
        if( _ucKey == 'y')
        {
            /* The parallel capture mode samples the data when both data enables are active. */
            _PioCapture.alwaysSampling = 0;
            printf("We receive data when both data enables are active\n\r");
        }
        else
        {
            /* The parallel capture mode samples the data whatever the data enables are.*/
            _PioCapture.alwaysSampling = 1;
            printf("We receive data whatever the data enables are\n\r");
        }
        printf("  Press y to samples all the data\n\r");
        printf("  Press n to samples the data only one time out of two\n\r");
        _ucKey = 0;
        while( (_ucKey != 'y') && (_ucKey != 'n') )
        {
            _ucKey = UART_GetChar();
        }
        if( _ucKey == 'y')
        {
            /* The parallel capture mode samples all the data */
            _PioCapture.halfSampling = 0;
        }
        else
        {
            /* The parallel capture mode samples the data only one time out of two */
            _PioCapture.halfSampling = 1;
            printf("Data with an even index are sampled\n\r");
        }
        /* Only if halfSampling is set, data with an even index are sampled. */
        _PioCapture.modeFirstSample = 0;
        /* No callback for Data Ready */
        _PioCapture.CbkDataReady = NULL;
        /* No callback for Overrun */
        _PioCapture.CbkOverrun = NULL;
        /* Callback for end of reception */
        _PioCapture.CbkEndReception = OnEndOfReceptionTransfer;
        /* Callback for Reception Buffer Full */
        _PioCapture.CbkBuffFull = OnReceptionBufferFull;
        /* Custom parameter not used in this application */
        _PioCapture.pParam = NULL;

        while(1)
        {
            printf("\n\r");
            if( _PioCapture.alwaysSampling == 0 )
            {
                printf("Data enables are active");
            }
            else
            {
                printf("Whatever the data enables are");
            }
            if( _PioCapture.halfSampling == 0 )
            {
                printf(", sample all the data\n\r");
            }
            else
            {
                printf(" only one time out of two, with an even index\n\r");
            }
            /* Init PIO Parallel Capture */
            ucCbkReceived = 0;
            PIO_CaptureInit( &_PioCapture );
            PIO_CaptureEnable();
            printf("wait\n\r");
            while(ucCbkReceived == 0);
        }
    }
    else if( _ucKey == 's')
    {
        printf("** SEND mode **\n\r");
        printf("This is for debug purpose only !\n\r");
        printf("Frequency of PIO controller clock must be strictly superior to");
        printf(" 2 times the frequency of the clock of the device which");
        printf(" generates the parallel data.\n\r");
        printf("\n\rPlease, connect the second board, and put it in reception mode\n\r");
        PMC_EnablePeripheral( ID_PIOA );

        /* Configure PIO Parrallel Capture pins */
        PIO_Configure(_pinsPIOCD, PIO_LISTSIZE(_pinsPIOCD));

        /* Define PIO used for PIO DC */
        PIOA->PIO_OWER = PIO_OWER_P24 | PIO_OWER_P25 | PIO_OWER_P26 | PIO_OWER_P27
                       | PIO_OWER_P28 | PIO_OWER_P29 | PIO_OWER_P30 | PIO_OWER_P31;

        PIOA->PIO_ODSR = 0x00000000;
        PIO_Clear( &_pinPIODCCLK );

        printf("  Press y to send data without data enables pins\n\r");
        printf("  Press n to send data with data enables pins\n\r");
        _ucKey = 0;
        while( (_ucKey != 'y') && (_ucKey != 'n') )
        {
            _ucKey = UART_GetChar();
        }
        if( _ucKey == 'y')
        {
            while(1)
            {
                printf("\n\rWe send data without data enables pins\n\r");
                /* 0x3020100 0x7060504 0xB0A0908 0xF0E0D0C 0x13121110
                 * 0x17161514 0x1B1A1918 0x1F1E1D1C 0x23222120 0x27262524
                 * 0x2B2A2928 0x2F2E2D2C 0x33323130 0x37363534 0x3B3A3938
                 * 0x3F3E3D3C */
                for( i=0; i<64; i++)
                {
                    /* Set Data */
                    PIOA->PIO_ODSR = (i<<24);
                    /* set Clock */
                    PIO_Set( &_pinPIODCCLK );
                    PIOA->PIO_ODSR = (i<<24);
                    /* Clear clock */
                    PIO_Clear( &_pinPIODCCLK );
                    /* Clear data */
                    PIOA->PIO_ODSR = 0x00000000;
                }
                printf("  Press a key\n\r");
                while( UART_GetChar() == 0 );
            }
        }
        else
        {
            while(1)
            {
                printf("\n\rWe send data with data enables pins\n\r");
                /* 0x3020100 0x7060504 0xB0A0908 0xF0E0D0C 0x13121110
                 * 0x17161514 0x1B1A1918 0x1F1E1D1C 0x23222120 0x27262524
                 * 0x2B2A2928 0x2F2E2D2C 0x33323130 0x37363534 0x3B3A3938
                 * 0x3F3E3D3C */
                for( i=0; i<64; i++)
                {
                    /* set Enable */
                    PIO_Set( &_pinPIODCEN1 );
                    PIO_Set( &_pinPIODCEN2 );
                    /* Set Data */
                    //PIOA->PIO_ODSR = 0xA5000000;
                    PIOA->PIO_ODSR = (i<<24);
                    /* set Clock */
                    PIO_Set( &_pinPIODCCLK );
                    PIOA->PIO_ODSR = (i<<24);
                    /* Clear clock */
                    PIO_Clear( &_pinPIODCCLK );
                    PIOA->PIO_ODSR = 0x00000000;
                    /* Clear Enable */
                    PIO_Clear( &_pinPIODCEN1 );
                    PIO_Clear( &_pinPIODCEN2 );
                }
                printf("  Press a key\n\r");
                while( UART_GetChar() == 0 );
            }
        }
    }

    return 0 ;
}
示例#26
0
void UART_COMMAND_CPP_ISR() {
    uint8 val = UART_GetChar();

    Command_Process_Char(val, UART_ClearTxBuffer, uartPutuint8, uartPutArray);
}
static void Play_Piano(dac_config_t *dac_config, float vol) {
	char note;
	float sampling_interval = 1.00/(dac_config->sampling_rate);
	static int rep=0;
	static int rep_done=0;
	static int sample_count=0;
	static int orig_sample_count = 0;
	static double sample_rate = 0;
	static float sample_period = 0;
	static int sample_idx = 0;


	if ( UART_GetChar(COM0, &note) == NO_ERROR  && ( sample_count == 0 || rep_done > 0) ) {
		switch (note) {
			case 'a':
				sample_rate = LOW_DO;
				break;
			case 's':
				sample_rate = RE;
				break;
			case 'd':
				sample_rate = MI;
				break;
			case 'f':
				sample_rate = FA;
				break;
			case 'g':
				sample_rate = SO;
				break;
			case 'h':
				sample_rate = LA;
				break;
			case 'j':
				sample_rate = TI;
				break;
			case 'k':
				sample_rate = HIGH_DO;
				break;
			default:
				sample_rate = 0;
				break;
		}
		if (sample_rate > 0) {
			sample_period = 1.00/sample_rate;
			sample_count = sample_period/sampling_interval;

			rep = MAX_REP/sample_period; //5 / sample_period;
			rep_done = 0;
			orig_sample_count = sample_count;
			sample_idx = 0;
		} else {
			rep = 0;
			sample_count = 0;
		}
	}

	uint16_t dac_value;
	error_code_t error;
	if (sample_rate != 0 && sample_count > 0) {
		//Calculate a new value.
		float multiplier;
		multiplier = sin(2*3.14*sample_rate*sample_idx*sampling_interval)*vol;
		dac_value = 1024*multiplier;
		if ( (error=DAC_Write_FIFO(&dac_value, 1)) == NO_ERROR ) {
			sample_idx++;
			sample_count--;
		}
		if (sample_count == 0 && (rep_done < rep)) {
			sample_count = orig_sample_count;
			sample_idx = 0;
			rep_done++;
		}
	}

	DAC_Write_Value(&dac_value);
}
//-----------------------------------------------------------------------------
// FUNCTION:    main
// SCOPE:       Bootloader application system function
// DESCRIPTION: bootloader main function             
// RETURNS:     0
//----------------------------------------------------------------------------- 
int main(void)
{	
    volatile unsigned long loop_counter = 0;  // counter of loop without received frame
    
	Byte enableBootMode = 0; 			//  0: enter APP, 1: enter BOOT mode, 2: enter verify mode

	DisableInterrupts;
	//WDG_Disable();				//watchdog can be enable or disabled in kinetis_sysinit.c
	
	INIT_CLOCKS_TO_MODULES;			// init clock module
	Boot_Button_Init();  			// init SW1 button (PTC3 port) on FRDM_KL26 board
	INIT_BOOT_LED;
	
    //condition for entering boot:  
    if(((*(unsigned long*)(RELOCATED_VECTORS + 8)) == 0xffffffff)                          //1. no valid code in APP vector section,
    || Boot_StrCompare(( Byte*)APPOK_START_ADDRESS, str_app_ok, APPOK_LENGTH) == CHECK_FAIL	   //2."APP_OK" is wrong in address APPOK_START_ADDRESS.
    || ((GPIO_PDIR_REG(BOOT_PIN_ENABLE_GPIO_BASE) & (1 << BOOT_PIN_ENABLE_NUM)) == 0)      //3. SW1 is pressed
    || (AppIDC == 0x0000000B))                                                             //4. App request boot
    {
    	 enableBootMode = 1; // enable boot
    	 BOOT_LED_ON;
    	 AppIDC = 0;
    }
    else if (AppIDC == 0x0000000A)   // App request verify
    {
    	 enableBootMode = 2; // enable verify mode
    	 BOOT_LED_ON;
    	 AppIDC = 0;
    }
    
    if(enableBootMode)
    {
    	// if use external clock
#ifdef USE_EXTERNAL_CLOCK
    	Boot_Init_Clock( );
#endif
    	PIN_INIT_AS_UART;   			// set PTA1/UART0_RX and PTA2/UART0_TX pins as UART
    	UART_Initialization();  		// init UART module
    }

	////////////////////////////////////////////////////////////////////////
	//BOOT Model 
	////////////////////////////////////////////////////////////////////////
	while(enableBootMode)  // enter boot or verify mode, execute all command from GUI
	{  
		volatile Byte frame_start_flag  = 0;    // if frame header is received. 1: receive $, start to receive frame;  0: no $ received
		volatile Byte frame_length 	= 0xFF;    // SCI received frame length, initialized as 0xFF
		volatile Byte data_length = 0;
		volatile Byte buff_index = 1;   	   // receive buffer index for sci_buffer[]
		volatile Byte data_checked  = 0; 	   // check frame end 0xAA 0x55. 1: correct frame ; 0: wrong frame
				
		FLASH_Initialization();

		sci_buffer[0] = UART_GetChar();
		if( sci_buffer[0] == '$') 			//check frame header: whether it is '$'
		{
			loop_counter = 0;
			frame_start_flag  = 1;			
		}   
		
		if(frame_start_flag == 1)
		{
			sci_buffer[1] = UART_GetChar();     // sci_buffer[1] is the station number
			UART_GetChar();   					// sci_buffer[2] is reserved
			sci_buffer[3] = UART_GetChar();     // sci_buffer[3] is the Data length
			data_length = sci_buffer[3];
			frame_length = 4 + sci_buffer[3] + 2;  // frame_length = frame head + data + frame end 
			buff_index = 4;
			while(data_length --)
				sci_buffer[buff_index ++] = UART_GetChar();
			sci_buffer[buff_index ++] = UART_GetChar();  // frame end. It should be 0xAA
			sci_buffer[buff_index ++] = UART_GetChar();  // frame end. It should be 0x55
			frame_start_flag = 0;
		}
		
		if((sci_buffer[frame_length-2] == 0xAA) && (sci_buffer[frame_length-1] == 0x55)) //Check if Frame end is correct
		{
			data_checked = 1; //  Correct frame received. 
		}

		// all the data in frame was correctly received (data_checked = 1) above, now perform frame analysis below.
		// sci_buffer[] now is switched to tx buffer
		if(data_checked == 1)
		{ 
			Byte i = 0;  
			Byte j = 0;  	
			Byte s19length = 0;
			Byte s19buffer[WR_BLOCK_BYTE]; //extract app file burning code from received frame, store them to s19buffer[]
			
			WDG_Refresh();
			switch(sci_buffer[4])
			{
				
				case 'I':	// receive 'I' command, send  version information to UART    
							i = 4;
						    while((sci_buffer[i] = Identifier[i-4]) !='\0')	//assign chip part number info to sci_buffer[]
						    {
						    	i++;
						    }
						    sci_buffer[3] = i - 4;   // tx data length in one frame 
						    Boot_Send(sci_buffer);
						    if(enableBootMode == 1)  // if in boot mode
						      FLASH_EraseSector((LWord)APPOK_START_ADDRESS);	//erase APP_OK
						    break;
						    
				case 'E':	// receive 'E' command, erase sector, then send confirm frame to UART
							Boot_ReadAddress();
							if(!( FLASH_EraseSector(address.complete)))
							{
								 sci_buffer[3] = 00;							  
								 Boot_Send(sci_buffer);
							}
							break; 

				case'W':	// receive 'W' command, extract app  burning code,  program flash. then send confirm frame to UART
							Boot_ReadAddress();
							s19length = sci_buffer[8];
				
							for(j=0,i=9;j<s19length;j++,i++) // extract the prepared writing data from sci_buff[] to S19buffer[]
							{
								s19buffer[j] = sci_buffer[i];   
							}
							if(!(FLASH_ProgramSectionByLongs (address.complete, (LWord*)s19buffer, s19length/4))) 
							{            
								 sci_buffer[3] = 00;
								 Boot_Send(sci_buffer);
								 break;
							}

				case'R':	// receive 'R' command, read out the memory data, then send the data in frame to UART
							Boot_ReadAddress();
							s19length = sci_buffer[8];
							for(i=0;i<s19length;i++)
							{ 
								sci_buffer[i + 4] = ((Byte*)(address.complete))[i];
							}
							sci_buffer[3] = s19length;
							Boot_Send(sci_buffer);
							break;

				case'G':	// receive 'G' command, go to app. 
					        if(enableBootMode == 1)
				    		  FLASH_ProgramSectionByLongs ((LWord)APPOK_START_ADDRESS, (LWord*)str_app_ok, APPOK_LENGTH/4);   
					        
							Boot_Cpu_SystemReset( );
							// if we want  to jump to user application, we need to deinitialize used modules and switch MCG back to FEI mode
							break;

				default :
				         	break;
			}// end switch(sci_buffer[4])		
			frame_start_flag  = 0;
			for (buff_index = 0; buff_index<FRAME_BUFF_LENGTH; buff_index++)	// clear sci_buffer[]
				sci_buffer[buff_index] = 0;
			
		}// end if(data_checked == 1)
		loop_counter ++;
		if(loop_counter >= 10 && enableBootMode == 2)                         // 100 * timeout of UART_GetChar();
		{
			Boot_Cpu_SystemReset( );
		}
	}// end while(enableBootMode)
	
	// deinitialization of used modules
	UART_Deinitialization();
	DEINIT_BOOT_LED;
	DEINIT_CLOCKS_TO_MODULES;
	
	// relocate vector table
	SCB_VTOR = RELOCATED_VECTORS;	
	AppIDC = 0;
	// Jump to user application
	JumpToUserApplication(*((unsigned long*)RELOCATED_VECTORS), *((unsigned long*)(RELOCATED_VECTORS+4)));  
	return 0;
} // end main 
示例#29
0
int main()
{
	/* Perform processor initialization */

	sysinit();	
	
	printf("\nRunning the SolderTermo_v2 project.\r\n");
	
	initTime();

	initNVRAM();
	
	readNVRAM();	
	
	printf("Version %hd\tCRC %hd\r\n", nvram.Version, nvram.nvramCrc);

	initDisplay();

	//initMAX31855();
	initThermocoupleADC();

	initPowerPWM();

	initHMI();

	initButtons();

	initStateMachine();

	int fastLog = 0;
	while(1)
	{
		if (fastLog)
			printf("%hd\t%hd\r\n", vram.ADCVal, vram.CurrTemp);
		else
			printf("%hd\t%hd\t%hd\t%hd\t%hd\t%hd\r\n", vram.CurrTemp / 10, nvram.Tsp, vram.PWM_Sp,
					nvram.Kp, nvram.Ki, nvram.Kd);


		if ( UART_CharPresent(UART2) )
		{
			uint8_t c;
			uint8_t charNo = 0;
			memset(uartBuff, 0, UART_MAX_BUFF);
			printf("Finish your input by ENTER\r\n");
			printf("\r\n");
			do
			{
				c = uartBuff[charNo++] = UART_GetChar(UART2); // wait for char to come
				UART_PutChar(UART2, c);
				WAIT_Waitms(50);
			}
			while ( c != '\r' && charNo < UART_MAX_BUFF );

			switch(uartBuff[0])
			{
				case 'f': fastLog = 1; break;  // fast logging
				case 's': fastLog = 0; break;  // slow logging
				case 'p': nvram.Kp = atoi(uartBuff + 1); break;  // fast logging
				case 'i': nvram.Ki = atoi(uartBuff + 1); break;  // slow logging
				case 'd': nvram.Kd = atoi(uartBuff + 1); break;  // slow logging
			}
		}

		WAIT_Waitms(fastLog ? 20 : 200);
	}

	return 0; // should never come here
}
示例#30
0
int main(void)
{
	BoardInit();
	SystemCoreClockUpdate();

	LedConnectedOn();
	if (UserAppDescriptor.UserInit != NULL)
	{
		pUserAppDescriptor = &UserAppDescriptor;
		pUserAppDescriptor->UserInit((CoreDescriptor_t *)&CoreDescriptor);
	}
	LedConnectedOff();

	Delay_ms(100);
	/*
	led_count = 0;
	// Check for USB connected
	while ((GPIOA->IDR & GPIO_Pin_11) != 0)
	{
		if (led_count++ == 0)
			LedConnectedOn();
		else if (led_count == 5)
			LedConnectedOff();
		else if (led_count == 25)
			led_count = 0;
		Delay_ms(10);
	}
	LedConnectedOff();
	*/
	// USB Device Initialization and connect
	usbd_init();
	usbd_connect(__TRUE);

	led_count = 0;
	while (!usbd_configured())	// Wait for USB Device to configure
	{
		if (led_count++ == 0)
			LedConnectedOn();
		else if (led_count == 5)
			LedConnectedOff();
		else if (led_count == 50)
			led_count = 0;
		Delay_ms(10);
	}
	LedConnectedOff();
	Delay_ms(100);				// Wait for 100ms

	led_count = 0;
	led_timeout = TIMEOUT_DELAY;
	usb_rx_ch = -1;
	usb_tx_ch = -1;

	while (1)
	{
		if (pUserAppDescriptor == NULL)
		{	// No user application
			if (led_count++ == 1000000)
			{
				led_count = 0;
				LedConnectedToggle();
			}
			usbd_hid_process();
		}
		else if (!usbd_hid_process())
		{
			// No packet processing
			if (led_timeout == 1000)
			{
				LedConnectedOn();
			}
			else if (led_timeout == 0)
			{
				LedConnectedOff();
				led_timeout = TIMEOUT_DELAY;
			}
			led_timeout--;
			
		}
		else
		{
			led_timeout = TIMEOUT_DELAY;
		}

#if (USBD_CDC_ACM_ENABLE == 1)

		NotifyOnStatusChange();

		// USB -> UART
		if (usb_rx_ch == -1)
			usb_rx_ch = USBD_CDC_ACM_GetChar();

		if (usb_rx_ch != -1)
		{
			if (UART_PutChar (usb_rx_ch) == usb_rx_ch)
				usb_rx_ch = -1;
		}

		// UART -> USB
		if (usb_tx_ch == -1)
			usb_tx_ch = UART_GetChar();

		if (usb_tx_ch != -1)
		{
			if (USBD_CDC_ACM_PutChar(usb_tx_ch) == usb_tx_ch)
				usb_tx_ch = -1;
		}
#endif
	}
}