Esempio n. 1
0
/*-------------------------------------------------------------------------------------------------------------------------------*/
void LIN_SendHeaderUsingLinCtlReg(uint32_t u32id, uint32_t u32HeaderSel)
{
    g_i32pointer = 0 ;

    /* Switch back to LIN Function */
    UART1->FUN_SEL = UART_FUNC_SEL_LIN;

    /* Set LIN 1. PID as 0x30 [UART_LIN_CTL_LIN_LIN_PID(0x30)]
               2. Header select as includes "break field", "sync field" and "frame ID field".[UART_LIN_CTL_LIN_HEAD_SEL_BREAK_SYNC_ID]
               3. Break/Sync Delimiter Length as 1 bit time [UART_LIN_CTL_LIN_BS_LEN(1)]
               4. Break Field Length as 12 bit time [UART_LIN_CTL_LIN_BKFL(12)]
               5. ID Parity Enable. Hardware will calculate and fill P0/P1 automatically  [UART_LIN_CTL_LIN_IDPEN_Msk]
    */
    if(u32HeaderSel == UART_LIN_CTL_LIN_HEAD_SEL_BREAK_SYNC_ID) {
        UART1->LIN_CTL = UART_LIN_CTL_LIN_LIN_PID(u32id) | UART_LIN_CTL_LIN_HEAD_SEL_BREAK_SYNC_ID |
                         UART_LIN_CTL_LIN_BS_LEN(1) | UART_LIN_CTL_LIN_BKFL(12) | UART_LIN_CTL_LIN_IDPEN_Msk;
        /* LIN TX Send Header Enable */
        UART1->LIN_CTL |= UART_LIN_CTL_LIN_SHD_Msk;
        /* Wait until break field, sync field and ID field transfer completed */
        while((UART1->LIN_CTL & UART_LIN_CTL_LIN_SHD_Msk) == UART_LIN_CTL_LIN_SHD_Msk);
    }
    /* Set LIN 1. Header select as includes "break field" and "sync field".[UART_LIN_CTL_LIN_HEAD_SEL_BREAK_SYNC]
               2. Break/Sync Delimiter Length as 1 bit time [UART_LIN_CTL_LIN_BS_LEN(1)]
               3. Break Field Length as 12 bit time [UART_LIN_CTL_LIN_BKFL(12)]
    */
    else if(u32HeaderSel == UART_LIN_CTL_LIN_HEAD_SEL_BREAK_SYNC) {
        UART1->LIN_CTL = UART_LIN_CTL_LIN_HEAD_SEL_BREAK_SYNC | UART_LIN_CTL_LIN_BS_LEN(1) | UART_LIN_CTL_LIN_BKFL(12);
        /* LIN TX Send Header Enable */
        UART1->LIN_CTL |= UART_LIN_CTL_LIN_SHD_Msk;
        /* Wait until break field and sync field transfer completed */
        while((UART1->LIN_CTL & UART_LIN_CTL_LIN_SHD_Msk) == UART_LIN_CTL_LIN_SHD_Msk);

        /* Send ID field, g_u8SendData[0] is ID+parity field*/
        g_u8SendData[g_i32pointer++] = GetParityValue(u32id);   // ID+Parity Field
        UART_Write(UART1, g_u8SendData, 1);
    }
    /* Set LIN 1. Header select as includes "break field".[UART_LIN_CTL_LIN_HEAD_SEL_BREAK]
               2. Break/Sync Delimiter Length as 1 bit time [UART_LIN_CTL_LIN_BS_LEN(1)]
               3. Break Field Length as 12 bit time [UART_LIN_CTL_LIN_BKFL(12)]
    */
    else if(u32HeaderSel == UART_LIN_CTL_LIN_HEAD_SEL_BREAK) {
        UART1->LIN_CTL = UART_LIN_CTL_LIN_HEAD_SEL_BREAK | UART_LIN_CTL_LIN_BS_LEN(1) | UART_LIN_CTL_LIN_BKFL(12);
        /* LIN TX Send Header Enable */
        UART1->LIN_CTL |= UART_LIN_CTL_LIN_SHD_Msk;
        /* Wait until break field transfer completed */
        while((UART1->LIN_CTL & UART_LIN_CTL_LIN_SHD_Msk) == UART_LIN_CTL_LIN_SHD_Msk);

        /* Send sync field and ID field*/
        g_u8SendData[g_i32pointer++] = 0x55 ;                  // SYNC Field
        g_u8SendData[g_i32pointer++] = GetParityValue(u32id);   // ID+Parity Field
        UART_Write(UART1, g_u8SendData, 2);
    }
}
Esempio n. 2
0
/**
 * @brief	Write a string to the USART
 * @param	String: The string to write
 * @retval	None
 */
void UART_WriteString(const char *String)
{
	while (*String != 0x00)
	{
		UART_Write(*String++);
	}
}
Esempio n. 3
0
/**
 * @brief	Write a string to the USART from FLASH memory
 * @param	String: The string to write located in FLASH
 * @retval	None
 */
void UART_WriteString_P(const char *String)
{
	while (pgm_read_byte(String) != 0x00)
	{
		UART_Write(pgm_read_byte(String++));
	}
}
Esempio n. 4
0
void UART_Send_Char(void)
{
	lsx_percent = (int)(lsx*(3.40/4095)*100/3.40);
	lsy_percent = (int)(lsy*3.4/4095*100/3.4);
	rsx_percent = (int)(rsx*3.4/4095*100/3.4);
	rsy_percent = (int)(rsy*3.4/4095*100/3.4);
	
	int lsx_loc = Generate_Section(lsx_percent, 'x');
	int lsy_loc = Generate_Section(lsy_percent, 'y');
	int rsx_loc = Generate_Section(rsx_percent, 'x');
	int rsy_loc = Generate_Section(rsy_percent, 'y');
	
	int l_index = alpha_index[lsy_loc][lsx_loc];
	int r_index = alpha_index[rsy_loc][rsx_loc];
	
	if ((l_index == -1) || (r_index == -1)) {
		//UART_Write('_');
	  	current_char = '\0';
		return;
	}
	
	if (current_char != '\0') {
	  return;
	}
	
	current_char = alphabet[r_index][l_index];
	
	if (lsx > 50 && rsx > 50)
	{
		UART_Write(current_char);
	}
}
void UART_Write_Text(const char *text)
{
  int i;
  for(i=0;text[i]!='\0';i++)
    UART_Write(text[i]);

}
Esempio n. 6
0
void RS485_SendDataByte(uint8_t *pu8TxBuf, uint32_t u32WriteBytes)
{
    /* Set UART parity as SPACE and skip baud rate setting */
    UART_SetLine_Config(UART1, 0, UART_WORD_LEN_8, UART_PARITY_SPACE, UART_STOP_BIT_1);

    /* Send data */
    UART_Write(UART1, pu8TxBuf, u32WriteBytes);
}
Esempio n. 7
0
/*---------------------------------------------------------------------------------------------------------*/
void LIN_SendResponse(int32_t checkSumOption,uint32_t *pu32TxBuf)
{
	int32_t i32;

	for(i32=0;i32<8;i32++)
		g_u8SendData[g_i32pointer++] = pu32TxBuf[i32] ;

	g_u8SendData[g_i32pointer++] = GetCheckSumValue(g_u8SendData,checkSumOption) ;  //CheckSum Field

	UART_Write(UART1,g_u8SendData+2,9);	
}
Esempio n. 8
0
/*---------------------------------------------------------------------------------------------------------*/
void LIN_SendHeader(uint32_t u32id)
{
    g_i32pointer = 0 ;

    /* Set LIN operation mode, Tx mode and break field length is 12 bits */
    UART_SelectLINMode(UART1, UART_ALT_CSR_LIN_TX_EN_Msk, 10);

    g_u8SendData[g_i32pointer++] = 0x55 ;                   // SYNC Field
    g_u8SendData[g_i32pointer++] = GetParityValue(u32id);   // ID+Parity Field
    UART_Write(UART1, g_u8SendData, 2);
}
Esempio n. 9
0
/*******************************************************************************
函 数 名:	UART_Send
功能说明:	串口数据发送
参	  数:	*data: 要发送的数内容
			len :	数据长度
返 回 值:	发送结果 TRUE/FALSE
*******************************************************************************/ 
u8 UART_Send(u8 *data, u8 len, u8 level)
{
	while (len--)
	{
		if (!UART_Write(*data++))
		{
			UART_Init(72, 9600);
		}
	}

	return TRUE;
}
Esempio n. 10
0
void LIN_SendHeader(uint32_t u32id)
{
	g_i32pointer =0 ;

    /* Switch back to LIN Function */
    _UART_SEL_FUNC(UART1,UART_FUNC_SEL_LIN);

    _UART_SET_LIN_TXMODE(UART1,11);
	g_u8SendData[g_i32pointer++] = 0x55 ;                  // SYNC Field
	g_u8SendData[g_i32pointer++] = GetParityValue(u32id);   // ID+Parity Field
    UART_Write(UART1,g_u8SendData,2);	
}
Esempio n. 11
0
/*---------------------------------------------------------------------------------------------------------*/
void LIN_MasterTestUsingLinCtlReg(uint32_t u32id, uint32_t u32ModeSel)
{
    uint8_t au8TestPattern[9] = {0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x0}; // 8 data byte + 1 byte checksum
    uint32_t i;

    if(u32ModeSel == MODE_CLASSIC) {
        /* Send break+sync+ID */
        LIN_SendHeaderUsingLinCtlReg(u32id, UART_LIN_CTL_LIN_HEAD_SEL_BREAK_SYNC_ID);
        /* Compute checksum without ID and fill checksum value to  au8TestPattern[8] */
        au8TestPattern[8] = ComputeChksumValue(&au8TestPattern[0], 8);
        UART_Write(UART1, &au8TestPattern[0], 9);
    } else if(u32ModeSel == MODE_ENHANCED) {
        /* Send break+sync+ID and fill ID value to g_u8SendData[0]*/
        LIN_SendHeaderUsingLinCtlReg(u32id, UART_LIN_CTL_LIN_HEAD_SEL_BREAK_SYNC);
        /* Fill test pattern to g_u8SendData[1]~ g_u8SendData[8] */
        for(i = 0; i < 8; i++)
            g_u8SendData[g_i32pointer++] = au8TestPattern[i];
        /* Compute checksum value with ID and fill checksum value to g_u8SendData[9] */
        g_u8SendData[g_i32pointer++] = ComputeChksumValue(&g_u8SendData[0], 9) ;
        UART_Write(UART1, &g_u8SendData[1], 9);
    }
}
Esempio n. 12
0
void main(void)
{
     char rom_data[7];
     
     //setup UART
     UART1_Init(9600);      //setup UART for 9600bps comm
     UART1_Write_Text("mikroC EEPROM TEST\n");
     
     //write to EEPROM
     EEPROM_Write(0, '1');    //write data
     Delay_ms(20);            //needed to ensure correct write/read
     
     EEPROM_Write(1, '2');    //write data
     Delay_ms(20);            //needed to ensure correct write/read
     
     EEPROM_Write(2, '3');    //write data
     Delay_ms(20);            //needed to ensure correct write/read
     
     //Read from EEPROM
     IntToStr((int)EEPROM_Read(0), rom_data);      //read data
     UART1_Write_Text("EEPROM Data : ");
     UART1_Write_Text(rom_data);
     UART_Write('\n');
     Delay_ms(20);            //needed to ensure correct write/read
     
     IntToStr((int)EEPROM_Read(1), rom_data);      //read data
     UART1_Write_Text("EEPROM Data : ");
     UART1_Write_Text(rom_data);
     UART_Write('\n');
     Delay_ms(20);            //needed to ensure correct write/read
     
     IntToStr((int)EEPROM_Read(2), rom_data);      //read data
     UART1_Write_Text("EEPROM Data : ");
     UART1_Write_Text(rom_data);
     UART_Write('\n');
     Delay_ms(20);            //needed to ensure correct write/read
     
     while(1);
}
Esempio n. 13
0
int uart0write_(const char *buf, size_t len)
{
#if defined(TARGET_LPC23xx)
	// DMA currently doesn't work on the LPC23xx
	UART_WriteUnbuffered(uart0, buf, len);
#else
	const char *tmp = buf;
	do
	{
		tmp += UART_Write(uart0, tmp, (buf + len) - tmp);
	}
	while (tmp < (buf + len));
#endif
	return len;
}
Esempio n. 14
0
/*---------------------------------------------------------------------------------------------------------*/
void LIN_SendResponseWithByteCnt(int32_t checkSumOption, uint32_t *pu32TxBuf, uint32_t u32ByteCnt)
{
    int32_t i32;

    /* Prepare data */
    for(i32 = 0; i32 < u32ByteCnt; i32++)
        g_u8SendData[g_i32pointer++] = pu32TxBuf[i32] ;

    /* Prepare check sum */
    if(checkSumOption == MODE_CLASSIC)
        g_u8SendData[g_i32pointer++] = GetCheckSumValue(&g_u8SendData[2], u32ByteCnt) ;  //CheckSum Field
    else if(checkSumOption == MODE_ENHANCED)
        g_u8SendData[g_i32pointer++] = GetCheckSumValue(&g_u8SendData[1], (u32ByteCnt + 1)) ; //CheckSum Field

    /* Send data and check sum */
    UART_Write(UART1, g_u8SendData + 2, 9);
}
Esempio n. 15
0
/*******************************************************************
函 数 名:	UART_Send
功能说明:	串口数据发送
参	  数:	*data: 要发送的数内容
			len :	数据长度
			level:  串口选择
返 回 值:	发送结果 TRUE/FALSE
*******************************************************************/ 
u8 UART_Send(u8 *data, u8 len, u8 level)
{
//	u8 a[20] = {0};
//	u8 i = 0;
//	for(i=0;i<len;i++)
//	{
//		a[i] = data[i];
//	}
		
	while (len--)
	{
		if (!UART_Write(*data++))
		{
//			UART_Init(72, 115200);
		}
	}
	return TRUE;
}
Esempio n. 16
0
void Usart_Init(void)
{

   	  /* Enable IP clock */
    CLK_EnableModuleClock(UART3_MODULE);
    /* Select IP clock source */
    CLK_SetModuleClock(UART3_MODULE, CLK_CLKSEL1_UARTSEL_HIRC , CLK_CLKDIV0_UART(1));
   /* Set GPD multi-function pins for UART3 RXD and TXD */
    SYS->GPD_MFPL |= SYS_GPD_MFPL_PD4MFP_UART3_RXD | SYS_GPD_MFPL_PD5MFP_UART3_TXD  ;
	GPIO_SetMode(PD, 5, GPIO_MODE_OUTPUT);
	GPIO_SetMode(PD, 4, GPIO_MODE_INPUT);
    UART_Open(UART3, 9600);
   // UART_DisableFlowCtrl(UART3);
	//UART_SetLine_Config(UART3, 115200, UART_WORD_LEN_8,UART_PARITY_NONE,UART_STOP_BIT_1);
//	UART_EnableInt(UART3, UART_INTEN_RDAIEN_Msk );
//	NVIC_SetPriority(UART3_IRQn, 2 );
   	//NVIC_EnableIRQ(UART3_IRQn);	//UART_INTEN_THREIEN_Msk 
    NVIC_DisableIRQ(UART3_IRQn);	
  UART_Write(UART3,"Usart3 init done!\r\n", sizeof("Usart3 init done!\r\n"));
 
}
Esempio n. 17
0
void UART_WriteRead(uint8_t data[], int Write_length, int Read_length, uint8_t Data_array[])
{
	// Write Bytes
	int i;
	volatile uint8_t status;
	for(i = 0; i < (Write_length + 1) ; i++)
	{
		UART_Write(data[i]);
	}
	
	
	//*(uint32_t *)Flag_reg = FINAL_WRITE_STOP_FLAGS;
	
	// Read Bytes
	for(i = 0; i<Read_length+PACKET_OVERHEAD; i++)
	{
		*(uint32_t *)Addr_reg = STATUS_ADDR;		
		*(uint32_t *)Flag_reg = READ_TOGGLE_ON;
		*(uint32_t *)Flag_reg = READ_TOGGLE_OFF;
		
		unsigned long Time_out_counter = 0;
		do 	// check RX busy flag
		{
			Time_out_counter++;
			status = *(uint32_t *)Data_out_reg;
		}while(!(status & 0b10)  && Time_out_counter < 40000);
		
		if(status & 0x02){
			//printf("Data Received. Bytes: %d\n", i);
		}
				
		if(Time_out_counter >= 40000){
			//printf("Read Timed Out. Bytes: %d\n", i);
		}
		
		*(uint32_t *) Addr_reg =  DATA_ADDR;
		Data_array[i] = *(uint32_t *) Data_out_reg;
	}
}
Esempio n. 18
0
void lcdPosition(int row, int col) 
{
	UART_Write(0xFE);   //command flag
	UART_Write((col + row*64 + 128));    //position 
    delay_ms(10);
}
Esempio n. 19
0
/***************************************************************************//**
 * @brief Main function.
 *
 * @return None.
*******************************************************************************/
void main(void)
{
    /*! Variables holding information about the device */
    unsigned short temperature = 0;   /*!< Last temperature read from the device */
    unsigned long  startFreq = 0;     /*!< Start frequency sweep */
    unsigned long  incFreq = 0;       /*!< Increment frequency */
    unsigned short incNum = 0;        /*!< Number of increments */
    unsigned long  calibImped = 0;    /*!< Calibration impedance */
    double         gainFactor = 0;    /*!< Stores the value of the gain factor */
    double         impedance = 0;     /*!< Measured impedance */
    double         currentFreq = 0;   /*!< Signal frequency used during a measurement */
    /*! Temporary variables */
    unsigned char  tempString[12] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
    double         tempValue = 0;
    
    /*! Initialize the UART communication peripheral. */
    UART_Init(9600);
    /*! Initialize the AD5933 device. */
    if(AD5933_Init())
    {
        CONSOLE_WriteString("AD5933 OK");
        UART_Write(0x0D);
    }
    else
    {
        CONSOLE_WriteString("AD5933 Error");
        UART_Write(0x0D);
    }
    while(1)
    {
        CONSOLE_GetCommand(receivedCommand);
        invalidCommand = 0;
        for(command = 0; command < commandsNumber; command++)
        {
            commandType = CONSOLE_CheckCommands(receivedCommand,
                                                commandsList[command],
                                                (double*)&commandParam);
            if(commandType == 0)
            {
                invalidCommand++;
            }
            if((command == 0) && (commandType != 0))    /*!< "help?" command*/
            {
                CONSOLE_WriteString("Available commands:");
                UART_Write(0x0D);
                for(displayCommand = 0; displayCommand < commandsNumber;
                    displayCommand++)
                {
                    CONSOLE_WriteString(commandsList[displayCommand]);
                    CONSOLE_WriteString(commandsDescription[displayCommand]);
                    UART_Write(0x0D);
                }
            }
            if((command == 1) && (commandType != 0))  /*!< "temperature?" command*/
            {
                /*! Read the temperature from the device */
                temperature = AD5933_GetTemperature();
                /*! Send the requested value to user */
                CONSOLE_WriteString("temperature=");
                itoa(tempString, temperature, 10);
                CONSOLE_WriteString(tempString);
                CONSOLE_WriteString(" degrees Celsius");
                UART_Write(0xD);

            }
            if((command == 2) && (commandType != 0))  /*!< "startFreq=" command*/
            {
                /*! Check if the parameter is valid */
                if( (commandParam >= 0) && (commandParam < MAX_START_FREQ) )
                {
                    tempValue = (commandParam / MHZ_4) * POW_2_27;
                    startFreq = (unsigned long)tempValue;
                }
                else if(commandParam < 0)
                {
                    startFreq = 0;
                }
                else
                {
                    startFreq = 0x00FFFFFF;
                }
                /* Configure the sweep parameters */
                AD5933_ConfigSweep(startFreq,
                                   incFreq,
                                   incNum);
                /* Start the sweep operation */
                AD5933_StartSweep();
                /*! Send feedback to user */
                CONSOLE_WriteString(commandsList[command]);
                tempValue = ((double)startFreq * MHZ_4) / POW_2_27;
                FloatToString(tempString, tempValue);
                CONSOLE_WriteString(tempString);
                CONSOLE_WriteString(" Hz");
                UART_Write(0xD);
                /*! Update the currentFrequrncy */
                currentFreq = tempValue;
            }
            if((command == 3) && (commandType != 0))  /*!< "incFreq=" command*/
            {
                /*! Check if the parameter is valid */
                if( (commandParam >= 0) && (commandParam < MAX_START_FREQ) )
                {
                    tempValue = (commandParam / MHZ_4) * POW_2_27;
                    incFreq = (unsigned long)tempValue;
                }
                else if(commandParam < 0)
                {
                    incFreq = 0;
                }
                else
                {
                    incFreq = 0x00FFFFFF;
                }
                /* Configure the sweep parameters */
                AD5933_ConfigSweep(startFreq,
                                   incFreq,
                                   incNum);
                /* Start the sweep operation */
                AD5933_StartSweep();
                /*! Send feedback to user */
                CONSOLE_WriteString(commandsList[command]);
                tempValue = ((double)incFreq * MHZ_4) / POW_2_27;
                FloatToString(tempString, tempValue);
                CONSOLE_WriteString(tempString);
                CONSOLE_WriteString(" Hz");
                UART_Write(0xD);
            }
            if((command == 4) && (commandType != 0))  /*!< "incNum=" command*/
            {
                /*! Check if the parameter is valid */
                if( (commandParam >= 0) && (commandParam < MAX_INC_NUM) )
                {
                    incNum = (unsigned short)commandParam;
                }
                else if(commandParam < 0)
                {
                    incNum = 0;
                }
                else
                {
                    incNum = 0x01FF;
                }
                /* Configure the sweep parameters */
                AD5933_ConfigSweep(startFreq,
                                   incFreq,
                                   incNum);
                /* Start the sweep operation */
                AD5933_StartSweep();
                /*! Send feedback to user */
                CONSOLE_WriteString(commandsList[command]);
                itoa(tempString, incNum, 10);
                CONSOLE_WriteString(tempString);
                UART_Write(0xD);
            }
            if((command == 5) && (commandType != 0))  /*!< "sweepParam?" command*/
            {
                /*! Send the requested value to user */
                CONSOLE_WriteString(commandsList[2]);
                tempValue = ((double)startFreq * MHZ_4) / POW_2_27;
                FloatToString(tempString, tempValue);
                CONSOLE_WriteString(tempString);
                CONSOLE_WriteString(" Hz");
                UART_Write(0xD);
                CONSOLE_WriteString(commandsList[3]);
                tempValue = ((double)incFreq * MHZ_4) / POW_2_27;
                FloatToString(tempString, tempValue);
                CONSOLE_WriteString(tempString);
                CONSOLE_WriteString(" Hz");
                UART_Write(0xD);
                CONSOLE_WriteString(commandsList[4]);
                itoa(tempString, incNum, 10);
                CONSOLE_WriteString(tempString);
                UART_Write(0xD);
            }
            if((command == 6) && (commandType != 0))  /*!< "calibImpedance=" command*/
            {
                /*! Check if the parameter is valid */
                if( (commandParam >= 1) && (commandParam <= 1000000) )
                {
                    calibImped = (unsigned long)commandParam;
                }
                else if(commandParam < 1)
                {
                    calibImped = 1;
                }
                else
                {
                    calibImped = 1000000;
                }
                /* Calculate the gain factor for the selected impedance */
                 gainFactor = AD5933_CalculateGainFactor(calibImped,
                                                   AD5933_FUNCTION_REPEAT_FREQ);
                /*! Send feedback to user */
                CONSOLE_WriteString("Gain was calculated for Z=");
                itoa(tempString, calibImped, 10);
                CONSOLE_WriteString(tempString);
                CONSOLE_WriteString(" [Ohm]");
                UART_Write(0xD);
            }
            if((command == 7) && (commandType != 0))  /*!< "impendace?" command*/
            {
                /* Calculates the impedance between the VOUT and VIN pins. */
                impedance = AD5933_CalculateImpedance(gainFactor,
                                                   AD5933_FUNCTION_INC_FREQ);
                /*! Send the requested value to user */
                tempValue = (double)impedance / 1000;
                FloatToString(tempString, tempValue);
                CONSOLE_WriteString("impedance=");
                CONSOLE_WriteString(tempString);
                CONSOLE_WriteString("[KOhm]");
                UART_Write(0xD);
                /*! Update the currentFrequrncy */
                tempValue = ((double)incFreq * MHZ_4) / POW_2_27;
                currentFreq = currentFreq + tempValue;
            }
            if((command == 8) && (commandType != 0))  /*!< "currentFreq?" command*/
            {
                FloatToString(tempString, currentFreq);
                CONSOLE_WriteString(tempString);
                CONSOLE_WriteString(" [Hz]");
                UART_Write(0xD);
            }
        }
        if(invalidCommand == commandsNumber)
        {
            /*! Send feedback to user */
            CONSOLE_WriteString("Invalid command");
            UART_Write(0x0D);
        }
    }
}
Esempio n. 20
0
int main(void)
{
	system_init();
	clock_init();
	led_init();	led_set(0x01); //show life
	UART_Init(BAUD); UART_Write("\nInit"); //Show UART life
	motor_init();
	adc_init();
	
	
	//Enable Analog pins
	adc_enable(CHANNEL_SENSOR_LEFT); 
    adc_enable(CHANNEL_SENSOR_RIGHT);	
    adc_enable(CHANNEL_SENSOR_FRONT);

	
	//Sensor value variables
	uint16_t sensor_left_value = 0; uint16_t sensor_right_value  = 0; uint16_t sensor_front_value  = 0;

	//Analog inputSignal conditioning arrays
	circBuf_t left_buffer; circBuf_t right_buffer; 	circBuf_t front_buffer;

    //Initialise sensor averaging buffers
	initCircBuf(&left_buffer, ROLLING_AVERAGE_LENGTH);
	initCircBuf(&right_buffer, ROLLING_AVERAGE_LENGTH);
	initCircBuf(&front_buffer, ROLLING_AVERAGE_LENGTH);

		
	//UART output buffer
	char buffer[UART_BUFF_SIZE] = {0};

	//=====Application specific variables=====								//TODO: initialise circbuff
	circBuf_t sweep_times;
	initCircBuf(&sweep_times, SWEEP_TIME_MEMORY_LENGTH);
	short sweep_del_t_last = 0;
	short sweep_end_t_last = 0;
	
	//time when front sensor begins to see grey.
	uint32_t grey_time_start = 0;


	bool sweep_ended = FALSE;
	//set high if the front sensor crosses the line
	bool front_crossed_black = FALSE; 
	//set high if front finds finish line
	bool front_crossed_grey = FALSE;

	bool sensor_update_serviced = TRUE;
	
	action current_action = IDLE;
	
	int16_t forward_speed = DEFAULT_FORWARD_SPEED;
	int16_t turn_speed = DEFAULT_SPEED;
	
	//Scheduler variables
	uint32_t t = 0;	

	//Loop control time variables
	uint32_t maze_logic_t_last = 0;
	uint32_t sample_t_last = 0;
	uint32_t UART_t_last = 0;


	clock_set_ms(0);
	sei(); // Enable all interrupts
	UART_Write("ialized\n");

	//wait for start command
	DDRD &= ~BIT(7);
	PORTD |= BIT(7);
	
	
	//motor_set(128, 128);
	while((PIND & BIT(7)))
	{
		continue;
	}
	

	
	while(1)
	{
		                                                                                                                         
		t = clock_get_ms();
		
		//check if a sensor update has occured
		if ((sensor_update_serviced == FALSE) && 
			(t%MAZE_LOGIC_PERIOD == 0) && (t != maze_logic_t_last))
		{
			sensor_update_serviced = TRUE;


			// finishing condition is a grey read for a set period
			if(is_grey(sensor_front_value) && front_crossed_grey == FALSE)
			{
				front_crossed_grey = TRUE;
				grey_time_start = t;	                                   //TODO: adjust so that finishing condition is a 1/2 whole sweeps on grey line
			}
			else if (is_grey(sensor_front_value) && front_crossed_grey == TRUE)
			{
				//
				if ((grey_time_start + GREY_TIME) <= t )
				{
					// Finish line found. Stop robot.
					maze_completed(); // wait for button push
					front_crossed_grey = FALSE;
				}

			}
			else
			{
				front_crossed_grey = FALSE;
			}
			
			//see if the front sensor crosses the line in case we run into a gap
			if(is_black(sensor_front_value)&&front_crossed_black == FALSE)
			{
				front_crossed_black = TRUE;
				//check for false finish line
				if(front_crossed_grey)
					front_crossed_grey = FALSE; //false alarm
			}	
			
			// when both rear sensors go black, this indicates an intersection (turns included).
			// try turning left
			if(is_black(sensor_left_value) && is_black(sensor_right_value))
			{
				sweep_ended = TRUE;
				motor_set(0, 255);									
				PORTB |= BIT(3);
				PORTB |= BIT(4);
			}
			
			//when both sensors are completely white this indicates a dead end or a tape-gap
			else if (is_white(sensor_left_value) && is_white(sensor_right_value))
			{
				sweep_ended = TRUE;
				PORTB &= ~BIT(3);
				PORTB &= ~BIT(4);
				//current_action = ON_WHITE;
				//Check if the front sensor is on black, or has been during the last sweep.
				if(is_black(sensor_front_value) | front_crossed_black)
					motor_set(255, 255);
				else if (is_white(sensor_front_value))
					motor_set(-255, 255);
			}				
			
			//sweep to the side that reads the darkest value			
			else if (sensor_left_value + SENSOR_TOLLERANCE < sensor_right_value)
			{
				PORTB &= ~BIT(3);
				PORTB |= BIT(4);
				if (current_action == SWEEP_LEFT)
					sweep_ended = TRUE;
				current_action = SWEEP_RIGHT;
				motor_set(forward_speed + turn_speed, forward_speed);
			}
			else if(sensor_right_value + SENSOR_TOLLERANCE< sensor_left_value)
			{
				PORTB |= BIT(3);
				PORTB &= ~BIT(4);			
				if (current_action == SWEEP_RIGHT)
					sweep_ended = TRUE;
				current_action = SWEEP_LEFT;
				motor_set(forward_speed, forward_speed+ turn_speed);
			}

            //If a new sweep started this cycle, find how long it took
            if (sweep_ended)
            {
            	//reset front black crossing detection variable
				sweep_ended = FALSE;
				
				if (front_crossed_black)
					front_crossed_black = FALSE;

				//Calculate sweep time
				sweep_del_t_last = t - sweep_end_t_last;
				sweep_end_t_last = t;
				writeCircBuf(&sweep_times, sweep_del_t_last);
				
				//adjust turn_speed for battery level.
				if (sweep_del_t_last > IDEAL_SWEEP_TIME)
				{
					turn_speed += 5;
				}					
				if (sweep_del_t_last < IDEAL_SWEEP_TIME)
				{
					turn_speed -= 5;
				}					
					
				turn_speed = regulate_within(turn_speed, MIN_TURN_SPEED, MAX_TURN_SPEED);
				
			}
		}
		
		//Sensor value update
 		if((t%SAMPLE_PERIOD == 0) & (t!=sample_t_last))
		{
            sample_t_last = t;
            //read in analog values
            sensor_update(CHANNEL_SENSOR_LEFT, &left_buffer, &sensor_left_value );
            sensor_update(CHANNEL_SENSOR_RIGHT, &right_buffer, &sensor_right_value );
            sensor_update(CHANNEL_SENSOR_FRONT, &front_buffer, &sensor_front_value );
			sensor_update_serviced = FALSE;

		}
		
		//display debug information		
		if((t%UART_PERIOD == 0) & (t != UART_t_last) & UART_ENABLED)
		{
			UART_t_last = t;
			
			sprintf(buffer, "sweep_time: %u \n", sweep_del_t_last);
			UART_Write(buffer);

			sprintf(buffer, "L: %u F: %u R: %u", sensor_left_value, sensor_front_value, sensor_right_value);
			UART_Write(buffer);
			UART_Write("\n");
		}
	}
}
void main()
{
unsigned char i;

unsigned char array[80];

const char *main1="SLAVE 1(0XAA)";

const char *main2="SLAVE 2(0XBB)";

const char *main3="SLAVE 3(0XCC)";

const char *msg1="\r\nnWaiting for Master\r\n";

const char *t1="\r\n before start\r\n";

const char *t2="\r\n address detected\r\n";

const char *t3="\r\n data recieved??\r\n";

const unsigned char *arr1= "\r\nUART Initialised\r\n";

const unsigned char *arr2= "\r\nSlave I2C initialised:\r\n";

    OSCCONbits.IRCF = 0x07;  // Configure Internal OSC for 8MHz Clock

    while(!OSCCONbits.HTS);   // Wait Until Internal Osc is Stable

    UART_Init(baud_rate);

    UART_Write_Text(main3);//DISPLAYS SLAVE 1 AS THE SLAVE DEVICE

    UART_Write_Text(arr1);

    delay_ms(500);

    UART_Write_Text(msg1);

    i2c_slave_init();

     UART_Write_Text(arr2);

     while(1)
     {
         for(i=0;i<=80;i++)
         {
             array[i]=0;
         }
         i=0;

         UART_Write(datain);

         UART_Write_Text("\r\n next line\r\n");

         UART_Write_Text(array);

         UART_Write_Text("\r\n");

//start i2c routines

            i2c_start_detect();

            PIR1bits.SSPIF=0;

            i2c_address_detect();

              UART_Write_Text("Address check returns true\r\n");

            i=0;

            delay_us(50);
            do
            {
                i2c_data_detect();
            
                array[i]=datain;

                i++;
            }while(!(SSPSTATbits.P));

            UART_Write_Text("\r\nDATA READ\r\n");

            UART_Write_Text(array);
            
     }
}
Esempio n. 22
0
bool OfflineDownloadwithUART(void)
{
	u32 i,j;
	//u8 tmp[2];
	if(!mcu_scfg.flash_done) // no user FW for MCU
		return FALSE;

	//connect
	if(!UART_Connect())
		return FALSE;
		
	//check pid
	/*if(!UART_GetPID(tmp))
		return FALSE;
	if(memcmp(tmp,mcu_scfg.MCUPID,2)!=0)
		return FALSE;*/
	
	//check boot loader version
	
	//still not real boot loader version

	//remove password
  	if(!UART_RemovePWD())
		return FALSE;
	//write password or not
	if(mcu_scfg.pwdflag[0]==FISH_MAN)
	{
		if(!UART_WritePWD(mcu_scfg.max_auth_num,TRUE))
			return FALSE;
	}

	//download user FW
	for(i=0;i<MCU_FLASH_PAGES;i++)
	{
		if(mcu_scfg.flash_map[i])
		{
			for(j=0;j<PRO_PAGE_SIZE/MAX_DATA_SIZE;j++)
			{
				if(!UART_Write(MCU_FLASH_BASE+i*PRO_PAGE_SIZE+j*MAX_DATA_SIZE-mcu_scfg.flash_offset, 
						MAX_DATA_SIZE, 
						(u8*)(MCU_FLASH_BASE+i*PRO_PAGE_SIZE+j*MAX_DATA_SIZE), 
						TRUE))
					return FALSE;
				DelayMs(10);	
			}
		}
	}
	//verify
	for(i=0;i<MCU_FLASH_PAGES;i++)
	{
		if(mcu_scfg.flash_map[i])
		{
			for(j=0;j<PRO_PAGE_SIZE/MAX_DATA_SIZE;j++)
			{
				if(!UART_Read(MCU_FLASH_BASE+i*PRO_PAGE_SIZE+j*MAX_DATA_SIZE-mcu_scfg.flash_offset, 
						MAX_DATA_SIZE, 
						RD_Buffer, 
						TRUE))
					return FALSE;
				if(memcmp(RD_Buffer,(u8*)(MCU_FLASH_BASE+i*PRO_PAGE_SIZE+j*MAX_DATA_SIZE),MAX_DATA_SIZE)!=0)
					return FALSE;
				DelayMs(5);		
			}
		}
	}

	

	//GO usr app
	if(!UART_GoUserApp(0))
		return FALSE;

	return TRUE;
}
Esempio n. 23
0
void main(void){
  ADCON1 |= 0x0F;                         // Configure all ports with analog function as digital
  CMCON  |= 7;                            // Disable comparators
  INTCON = 0;
  TRISB = 0b01110111;
  TRISD = 0b00001111;

  PORTB=0;
  LATB=0;
  PORTD=0;   
  INTCON.INT0IF=0;
        INTCON.INT1IF=0;
           INTCON.INT2IF=0;
              INTCON.RBIF=0;
                 RCON.IPEN=1;
              INTCON2.RBIP=0;
              
  TRISA=0b00000000;
  PORTA=0;
  TRISE=0;
  PORTE=0;



  INTCON3.INT1IP=1 ;
        INTCON3.INT2IP=1;
        
  INTCON.INT0IE=1;
     INTCON.RBIE=0;
  INTCON3.INT1IE=1;
  INTCON3.INT2IE=1;
  INTCON2.RBPU = 1;
        INTCON2.INTEDG0  = 0 ;
             INTCON2.INTEDG1  = 0 ;
                  INTCON2.INTEDG2  = 0 ;
                                          INTCON.RBIF=0;

                        UART1_Init(2400);                         // initialize UART1 module
                        Delay_ms(100);




                         INTCON.GIE = 1;
                         INTCON.RBIE=1;
           for(cnt=0;cnt<6;cnt++)
        writebuff[cnt]=48;
        i=1;
  while(1){  

          writebuff[4]=0x2E;



            UART_Write(writebuff[0])   ;

          UART_Write(writebuff[1])  ;

           UART_Write(writebuff[2])  ;

          UART_Write(writebuff[3])    ;

          UART_Write(writebuff[4])    ;

           UART_Write(writebuff[5])     ;

           UART_Write(writebuff[6])      ;


              UART_Write(76);






  }
}
Esempio n. 24
0
void clearLCD()	//clear lcd
{
	UART_Write(0xFE);   //command flag
	UART_Write(0x01);   //clear command.
	delay_ms(10);
}
Esempio n. 25
0
void backlightOff()  //turns off the backlight
{
	UART_Write(0x7C);   //command flag for backlight stuff
	UART_Write(128);     //light level for off.
	delay_ms(10);
}
/* Required by user program and RAK415 library */
uint8_t rak_UART_send(uint8_t *tx_buf, uint16_t buflen)
{
    UART_Write(UART1, tx_buf, buflen);
    return 0;   
}
Esempio n. 27
0
void RS485_SendDataByte(uint8_t *pu8TxBuf, uint32_t u32WriteBytes)
{
    _UART_SET_DATA_FORMAT(UART1,UART_WORD_LEN_8 | UART_PARITY_SPACE | UART_STOP_BIT_1);
    UART_Write(UART1,pu8TxBuf,u32WriteBytes);
}
void main(void)
{
   const unsigned char *mas="\r\n---------------MASTER DEVICE-----------------\r\n";

   const unsigned char * arr1 = "\r\nTaking in the text \r\n";

   const unsigned char *arr2="\r\nEnter your choice \r\n 1.Slave 1(Address:0xAA\r\n2.Slave 2(Address:0xBB)\r\n3.Slave 3(Address:0xCC\r\n";

   const unsigned char *arr3= "You have entered:\r\n";

   const unsigned char *arr4= "\r\nUART Initialised\r\n";

   const unsigned char *arr5= "\r\nI2C initialised:\r\n";

   const unsigned char *msg1="\r\nSending to Slave 1 (Address 0xAA)\r\n";

   const unsigned char *msg2="\r\nSending to Slave 2 (Address 0xBB)\r\n";

   const unsigned char *msg3="\r\nSending to Slave 3 (Address 0xCC)\r\n";

   const unsigned char *msg4="\r\nAddress sent\r\n";

   const unsigned char *msg5="\r\nData sent\r\n";

    

   const unsigned char *err="\r\nNo message will be sent since no slave no entered\r\n";
     const unsigned char *fin="\r\nClosing Communication!\r\n";

   const unsigned char *msgm="\r\nYou have entered choice number:\r\n";

   unsigned char choice;

   OSCCONbits.IRCF = 0x07;  // Configure Internal OSC for 8MHz Clock

    while(!OSCCONbits.HTS);   // Wait Until Internal Osc is Stable

    INTCON=0;   // purpose of disabling the interrupts.

    UART_Init(baud_rate);

    UART_Write_Text(mas);

    UART_Write_Text(arr4);

    delay_ms(500);

    I2C_init();

    UART_Write_Text(arr5);
     //Initialisation done

    while(1)
    {
        UART_Write_Text(arr1);

        i2c_idle();

  //receive the characters until ENTER is pressed (ASCII for ENTER = 13)

         is=UART_Read_Text();

         UART_Write_Text(arr3);

         UART_Write_Text(is);

         UART_Write_Text(arr2);

         choice=UART_Read();

         UART_Write_Text(msgm);

         UART_Write(choice);

    switch(choice)
    {
        case 0x31:
        {
            UART_Write_Text(msg1);
            
            I2C_Start();

            if(I2C_address_send())//device address
           {   
           	delay_us(20);//clock settle and then send
                I2C_Write_Text(is);
           }
            
              else
                  break;
             I2C_Stop();
              break;
        }

        case 0x32:

          {
            UART_Write_Text(msg2);

            I2C_Start();

            if(I2C_address_send1())//device address
           {  
			 delay_us(20);//clock settle and then send
                 I2C_Write_Text(is);

             }

              else
                  break;
             I2C_Stop();
              break;
        }

       case 0x33:
           {
               UART_Write_Text(msg3);
               
               I2C_Start();
              
               if(I2C_address_send2())//device address
               {  
			 delay_us(20);//clock settle and then send
                 I2C_Write_Text(is);

               }
              else
                  break;
                I2C_Stop();

              break;
        }
        default:

            UART_Write_Text(err);
            break;
    }
    //Choice entered data sent respectively to slaves now stop
    //i2c_SendAcknowledge(I2C_LAST);
    PIR1bits.SSPIF = 0;

    
    UART_Write_Text(fin);

    }

}
Esempio n. 29
0
void backlightOn() 	 //turns on the backlight
{ 
	UART_Write(0x7C);   //command flag for backlight stuff
	UART_Write(157);    //light level.
	delay_ms(10);
}