Example #1
0
void UARTDebug_ControllerLoop(UART_HandleTypeDef *huart) {
	if (huart->hdmatx->State == HAL_DMA_STATE_READY) {
		if (mutex_HAL_UARTDebug_TxCpltCallback == 0) {	
			mutex_HAL_UARTDebug_TxCpltCallback = 1;
			if (CheckHasMsg()) {
				int32_t lengthOfMsg = PopAMsgFromTxBuff(txMsg);
				memcpy(txDMABuffer,txMsg,sizeof(txMsg));
				HAL_StatusTypeDef ret = HAL_UART_Transmit_DMA(huart, (uint8_t *) txDMABuffer, lengthOfMsg);
				if(ret == HAL_BUSY || ret == HAL_ERROR){
					PushAMsgToTxRbuff(txMsg,lengthOfMsg);
				}				
			}			
			mutex_HAL_UARTDebug_TxCpltCallback = 0;
		}		
	}
	if(rearmUartReceiveIT==1){
		HAL_StatusTypeDef ret = HAL_UART_Receive_IT(huart, (uint8_t*) (huart->pRxBuffPtr), 1);
		if(ret == HAL_OK){
			rearmUartReceiveIT = 0;
		}
	}
}
Example #2
0
HAL_StatusTypeDef WifiCom_Transmit_Service ( T_Requete Requete,	T_Ack_Nack Ack_Nack, T_Presence_Host Etat_Host )
{
	uint32_t etat_uart = HAL_UART_GetState ( &Wifi_Com_Uart ) ;
	
	if ( ( etat_uart != HAL_UART_STATE_BUSY_TX ) && ( etat_uart != HAL_UART_STATE_BUSY_TX_RX ) )
	{	/* Charge le buffer émission */
		Wifi_Buf_Emi.Transport.Header1											=  HEADER1 ;
		Wifi_Buf_Emi.Transport.Header2											=  HEADER2 ;					
		Wifi_Buf_Emi.Transport.Type 		 					   				=  TYPE_MSG_DE_SERVICE ; 
		Wifi_Buf_Emi.Transport.Total_Octet			 		 				=  0 ; 
		Wifi_Buf_Emi.Transport.Position_Premier_Octet				=  0 ; 	
		Wifi_Buf_Emi.Transport.Nombre_Doctets				 				=  TAILLE_MESSAGE_DE_SERVICE ;
		Wifi_Buf_Emi.De_Service.Type.Service.Requete 		 		= 	Requete ; 		
		Wifi_Buf_Emi.De_Service.Type.Service.Ack_Nack 		 	= 	Ack_Nack ;
		Wifi_Buf_Emi.De_Service.Type.Service.Presence_Host	= 	Etat_Host ;		
		Wifi_Buf_Emi.De_Service.Crc									 				= Calcule_Checksum ( Wifi_Buf_Emi.Word, TAILLE_MESSAGE_DE_SERVICE /4);
		Max_Repetition = 0 ;
		return ( HAL_UART_Transmit_DMA(&Wifi_Com_Uart, Wifi_Buf_Emi.Octet, TAILLE_MESSAGE) );
	}
	else
		return ( HAL_BUSY ); 		
}
Example #3
0
/* 串口发送 */
void uart_send(drv_uart_T *uart, uint8_T *fmt, ...)
{
    int32_T n = 0; /* printf 字符串长度 */
    uint32_T send_frame_len = 0; /* printf帧长度 */
	
    while(uart_tc_locked(uart)); /* 等待上一次传输完成 */
    uart_tc_lock(uart); /* 锁住资源 */
    
    va_list args;
    va_start(args, fmt); 
    n = vsnprintf((char *)(uart->send_buf + UART_FRAME_HEAD_SIZE), UART_LINE_BUF_SIZE, (char *)fmt, args);
    va_end(args); 

    /* 构造协议帧 */
    comm_frame_printf_make(&send_frame_len, uart->send_buf, n);
    if(HAL_UART_Transmit_DMA(&uart->handle, (uint8_t *)uart->send_buf, send_frame_len)!= HAL_OK)
    {
        /* 出错 */
        while(TRUE);
    }

    return;
}
Example #4
0
/**----------------------------------------------------------------------------
 * @brief  init finite state machine uart
 * @param  none
 * @retval none
 -----------------------------------------------------------------------------*/
void fsm_uart(void) {
	static HAL_StatusTypeDef uart_status;
	
	switch (state_fsm_uart) {
		case FSM_UART_READY:
		  if(GetMessage(MSG_UART_SBUS)) {
				state_fsm_uart=FSM_UART_TX;
			}
		  break;
		case FSM_UART_BUSY:
		  if(GetMessage(MSG_UART_TX_END)) {
				state_fsm_uart=FSM_UART_READY;
			}
		  break;
		case FSM_UART_TX:
			if(GetTimer(SBUS_TIMER)>=SBUS_DELAY_STD) {
				uart_status=HAL_UART_Transmit_DMA(UART_HANDLE, (uint8_t *)packet_sbus, PKT_LEN);
				switch(uart_status) {
					case HAL_OK:
						state_fsm_uart=FSM_UART_BUSY;
					  break;
					default:
						state_fsm_uart=FSM_UART_FAIL;
					  break;
				}
				ResetTimer(SBUS_TIMER);
			}
		  break;
		case FSM_UART_FAIL:
		  break;
		default:
		  state_fsm_uart=FSM_UART_FAIL;
		  break;
	}
	
}
Example #5
0
int32_t UDebugSendRaw(int8_t * data, int32_t lengthOfMsg) {
	UART_HandleTypeDef * huart = GetUartDebugPtr();
	int32_t ret = -1;

	if (huart->hdmatx->State == HAL_DMA_STATE_READY) {
		int32_t txRBuffState = CheckHasMsg();
		if (txRBuffState == false) {
			memcpy(txDMABuffer,data,sizeof(data));
			HAL_StatusTypeDef ret1 = HAL_UART_Transmit_DMA(huart, (uint8_t *) txDMABuffer, lengthOfMsg);	
			if(ret1 == HAL_BUSY || ret1 == HAL_ERROR){
				PushAMsgToTxRbuff(txMsg,lengthOfMsg);
			} else{
				ret = 0;
			}		
		} else if (txRBuffState == true) {
			PushAMsgToTxRbuff(data, lengthOfMsg);
			ret = 1;
		}
	} else {
		PushAMsgToTxRbuff(data, lengthOfMsg);
		ret = 2;
	}
	return ret;
}
Example #6
0
void Data_Send_Senser(void)
{
	uint8_t _cnt=0;
	data_to_send[_cnt++]=0xAA;
	data_to_send[_cnt++]=0xAA;
	data_to_send[_cnt++]=0x02;
	data_to_send[_cnt++]=0;
	__IO int16_t _temp;
	_temp = (int)(gy);  //gy代表绕Y轴x轴的输出,表示x轴角速度
	data_to_send[_cnt++]=BYTE1(_temp);
	data_to_send[_cnt++]=BYTE0(_temp);
	_temp = (int)(gx);  //gx代表绕X轴y轴的输出,表示y轴角速度
	data_to_send[_cnt++]=BYTE1(_temp);
	data_to_send[_cnt++]=BYTE0(_temp);
	
//	_temp = (int)(init_gx);
//	data_to_send[_cnt++]=BYTE1(_temp);
//	data_to_send[_cnt++]=BYTE0(_temp);
//	_temp = (int)(init_gy);
//	data_to_send[_cnt++]=BYTE1(_temp);
//	data_to_send[_cnt++]=BYTE0(_temp);
	
//	_temp = (int)(q2 * 100);
//	data_to_send[_cnt++]=BYTE1(_temp);
//	data_to_send[_cnt++]=BYTE0(_temp);
//	_temp = (int)(q3 * 100);
//	data_to_send[_cnt++]=BYTE1(_temp);
//	data_to_send[_cnt++]=BYTE0(_temp);
	
//	__IO int16_t _temp;
//	_temp = (int)(AA.angle * 100);
//	data_to_send[_cnt++]=BYTE1(_temp);
//	data_to_send[_cnt++]=BYTE0(_temp);
//	_temp = (int)(AA.ax * 100);
//	data_to_send[_cnt++]=BYTE1(_temp);
//	data_to_send[_cnt++]=BYTE0(_temp);
//	_temp = (int)(AA.ay * 100);
//	data_to_send[_cnt++]=BYTE1(_temp);
//	data_to_send[_cnt++]=BYTE0(_temp);
//	_temp = (int)(AA.az * 100);
//	data_to_send[_cnt++]=BYTE1(_temp);
//	data_to_send[_cnt++]=BYTE0(_temp);
  _temp = (int)(Motor_Angle_X);
	data_to_send[_cnt++]=BYTE1(_temp);
	data_to_send[_cnt++]=BYTE0(_temp);
	_temp = (int)(Motor_Angle_Y);
	data_to_send[_cnt++]=BYTE1(_temp);
	data_to_send[_cnt++]=BYTE0(_temp);
	
	data_to_send[_cnt++]=BYTE1(MOTOR4);          //X轴正向电机
	data_to_send[_cnt++]=BYTE0(MOTOR4);          
	data_to_send[_cnt++]=BYTE1(MOTOR3);          //X轴负向电机
	data_to_send[_cnt++]=BYTE0(MOTOR3);
	data_to_send[_cnt++]=BYTE1(MOTOR2);          //Y轴正向电机
	data_to_send[_cnt++]=BYTE0(MOTOR2);
	data_to_send[_cnt++]=BYTE1(MOTOR1);          //Y轴负向电机
	data_to_send[_cnt++]=BYTE0(MOTOR1);
//	data_to_send[_cnt++]=BYTE1(MPU6050_GYRO_LAST.Y);
//	data_to_send[_cnt++]=BYTE0(MPU6050_GYRO_LAST.Y);
//	data_to_send[_cnt++]=BYTE1(MPU6050_GYRO_LAST.Z);
//	data_to_send[_cnt++]=BYTE0(MPU6050_GYRO_LAST.Z);
//	data_to_send[_cnt++]=BYTE1(AK8975_Data[0]);
//	data_to_send[_cnt++]=BYTE0(AK8975_Data[0]);
//	data_to_send[_cnt++]=BYTE1(AK8975_Data[1]);
//	data_to_send[_cnt++]=BYTE0(AK8975_Data[1]);
//	data_to_send[_cnt++]=BYTE1(AK8975_Data[2]);
//	data_to_send[_cnt++]=BYTE0(AK8975_Data[2]);
  data_to_send[_cnt++]=0;
	data_to_send[_cnt++]=0;
	data_to_send[_cnt++]=0;
	data_to_send[_cnt++]=0;
	data_to_send[_cnt++]=0;
	data_to_send[_cnt++]=0;

	
	data_to_send[3] = _cnt-4;
	
	uint8_t sum = 0;
	for(uint8_t i=0;i<_cnt;i++)
		sum += data_to_send[i];
	data_to_send[_cnt++] = sum;
	
//#ifdef DATA_TRANSFER_USE_USART
//	Uart1_Put_Buf(data_to_send,_cnt);
HAL_UART_Transmit_DMA(&huart2, data_to_send, _cnt);
//#else
//	NRF_TxPacket(data_to_send,_cnt);
//#endif
}
Example #7
0
void uart2_transmit(char* string) {	
	HAL_UART_Transmit_DMA(huart2,(uint8_t*)string,strlen(string));
}
Example #8
0
File: main.c Project: ndhuan/GPSRTK
void SendStr(const char* str)
{
	HAL_UART_Transmit_DMA(&UartResultHandle,(unsigned char*)str,strlen(str));
}
Example #9
0
File: main.c Project: z80/stm32f429
/**
  * @brief  Main program
  * @param  None
  * @retval None
  */
int main(void)
{

  /* STM32F4xx HAL library initialization:
       - Configure the Flash prefetch, instruction and Data caches
       - Configure the Systick to generate an interrupt each 1 msec
       - Set NVIC Group Priority to 4
       - Global MSP (MCU Support Package) initialization
     */
  HAL_Init();
  
  /* Configure LED3, LED4, LED5 and LED6 */
  BSP_LED_Init(LED3);
  BSP_LED_Init(LED4);
  BSP_LED_Init(LED5);
  BSP_LED_Init(LED6);

  /* Configure the system clock to 100 MHz */
  SystemClock_Config();

#ifdef TRANSMITTER_BOARD
  /* Configure USER Button */
  BSP_PB_Init(BUTTON_KEY, BUTTON_MODE_GPIO);
	
  /* Wait for USER Button press before starting the Communication */
  while (BSP_PB_GetState(BUTTON_KEY) == RESET)
  {
    /* Toggle LED3 waiting for user to press button */
    BSP_LED_Toggle(LED3);
    HAL_Delay(40);		
  }
  /* Wait for USER Button to be release before starting the Communication */
  while (BSP_PB_GetState(BUTTON_KEY) == SET)
  {
  }
  
  /* Turn LED3 off */
  BSP_LED_Off(LED3);
#endif /* TRANSMITTER_BOARD */

  /*##-1- Configure the UART peripheral ######################################*/
  /* Put the USART peripheral in the Asynchronous mode (UART Mode) */
  /* UART1 configured as follow:
      - Word Length = 8 Bits
      - Stop Bit = One Stop bit
      - Parity = None
      - BaudRate = 9600 baud
      - Hardware flow control disabled (RTS and CTS signals) */
  UartHandle.Instance          = USARTx;
  
  UartHandle.Init.BaudRate     = 9600;
  UartHandle.Init.WordLength   = UART_WORDLENGTH_8B;
  UartHandle.Init.StopBits     = UART_STOPBITS_1;
  UartHandle.Init.Parity       = UART_PARITY_NONE;
  UartHandle.Init.HwFlowCtl    = UART_HWCONTROL_NONE;
  UartHandle.Init.Mode         = UART_MODE_TX_RX;
  UartHandle.Init.OverSampling = UART_OVERSAMPLING_16;
    
  if(HAL_UART_Init(&UartHandle) != HAL_OK)
  {
    Error_Handler();
  }
  
#ifdef TRANSMITTER_BOARD

  /* The board sends the message and expects to receive it back */
  /* DMA is programmed for reception before starting the transmission, in order to
     be sure DMA Rx is ready when board 2 will start transmitting */
  /*##-2- Program the Reception process #####################################*/
  if(HAL_UART_Receive_DMA(&UartHandle, (uint8_t *)aRxBuffer, RXBUFFERSIZE) != HAL_OK)
  {
    Error_Handler();
  }

  /*##-3- Start the transmission process #####################################*/  
  /* While the UART in reception process, user can transmit data through 
     "aTxBuffer" buffer */
  if(HAL_UART_Transmit_DMA(&UartHandle, (uint8_t*)aTxBuffer, TXBUFFERSIZE)!= HAL_OK)
  {
    Error_Handler();
  }
  
  /*##-4- Wait for the end of the transfer ###################################*/  
  while (UartReady != SET)
  {
  } 
  
  /* Reset transmission flag */
  UartReady = RESET;

#else
  
  /* The board receives the message and sends it back */

  /*##-2- Put UART peripheral in reception process ###########################*/  
  if(HAL_UART_Receive_DMA(&UartHandle, (uint8_t *)aRxBuffer, RXBUFFERSIZE) != HAL_OK)
  {
    Error_Handler();
  }
  
  /*##-3- Wait for the end of the transfer ###################################*/
  /* While waiting for message to come from the other board, LED2 is
     blinking according to the following pattern: a double flash every half-second */  
  while (UartReady != SET)
  {
      BSP_LED_On(LED3); 
      HAL_Delay(100);
      BSP_LED_Off(LED3); 
      HAL_Delay(100);
      BSP_LED_On(LED3); 
      HAL_Delay(100);
      BSP_LED_Off(LED3); 
      HAL_Delay(500); 
  }
  
  /* Reset transmission flag */
  UartReady = RESET;
  BSP_LED_Off(LED3);
  
  /* Reset transmission flag */
  UartReady = RESET;
  
  /*##-4- Start the transmission process #####################################*/  
  /* While the UART in reception process, user can transmit data through 
     "aTxBuffer" buffer */
  if(HAL_UART_Transmit_DMA(&UartHandle, (uint8_t*)aTxBuffer, TXBUFFERSIZE)!= HAL_OK)
  {
    Error_Handler();
  }
  
#endif /* TRANSMITTER_BOARD */
  
  /*##-5- Wait for the end of the transfer ###################################*/  
  while (UartReady != SET)
  {
  }
  
  /* Reset transmission flag */
  UartReady = RESET;

  /*##-6- Compare the sent and received buffers ##############################*/
  if(Buffercmp((uint8_t*)aTxBuffer,(uint8_t*)aRxBuffer,RXBUFFERSIZE))
  {
    Error_Handler();
  }
  
  /* Infinite loop */
  while (1)
  {    
  }
}
void consoleLog(char *message)
{
    HAL_UART_Transmit_DMA(&huart2, (uint8_t *)message, strlen(message));
}
/**
  * @brief  CDC_Itf_DataRx
  *         Data received over USB OUT endpoint is processed here.
  * @param  Buf: Buffer of data received
  * @param  Len: Number of data received (in bytes)
  * @retval Result of the opeartion: USBD_OK if all operations are OK else USBD_FAIL
  * @note   The buffer we are passed here is just UserRxBuffer, so we are
  *         free to modify it.
  */
static int8_t CDC_Itf_Receive(uint8_t* Buf, uint32_t *Len) {
#if 0
    // this sends the data over the UART using DMA
    HAL_UART_Transmit_DMA(&UartHandle, Buf, *Len);
#endif

    // TODO improve this function to implement a circular buffer

    // if we have processed all the characters, reset the buffer counters
    if (UserRxBufCur > 0 && UserRxBufCur >= UserRxBufLen) {
        memmove(UserRxBuffer, UserRxBuffer + UserRxBufLen, *Len);
        UserRxBufCur = 0;
        UserRxBufLen = 0;
    }

    uint32_t delta_len;

    if (user_interrupt_char == VCP_CHAR_NONE) {
        // no special interrupt character
        delta_len = *Len;

    } else {
        // filter out sepcial interrupt character from the buffer
        bool char_found = false;
        uint8_t *dest = Buf;
        uint8_t *src = Buf;
        uint8_t *buf_top = Buf + *Len;
        for (; src < buf_top; src++) {
            if (*src == user_interrupt_char) {
                char_found = true;
            } else {
                if (char_found) {
                    *dest = *src;
                }
                dest++;
            }
        }

        if (char_found) {
            // raise exception when interrupts are finished
            user_interrupt_char = VCP_CHAR_NONE;
            pendsv_nlr_jump(user_interrupt_data);
        }

        // length of remaining characters
        delta_len = dest - Buf;
    }

    if (UserRxBufLen + delta_len + CDC_DATA_FS_MAX_PACKET_SIZE > APP_RX_DATA_SIZE) {
        // if we keep this data then the buffer can overflow on the next USB rx
        // so we don't increment the length, and throw this data away
    } else {
        // data fits, leaving room for another CDC_DATA_FS_OUT_PACKET_SIZE
        UserRxBufLen += delta_len;
    }

    // initiate next USB packet transfer, to append to existing data in buffer
    USBD_CDC_SetRxBuffer(&hUSBDDevice, UserRxBuffer + UserRxBufLen);
    USBD_CDC_ReceivePacket(&hUSBDDevice);

    return USBD_OK;
}
Example #12
0
 /* STM32F3xx HAL library initialization:
       - Configure the Flash prefetch
       - Systick timer is configured by default as source of time base, but user 
         can eventually implement his proper time base source (a general purpose 
         timer for example or other time source), keeping in mind that Time base 
         duration should be kept 1ms since PPP_TIMEOUT_VALUEs are defined and 
         handled in milliseconds basis.
       - Set NVIC Group Priority to 4
       - Low Level Initialization
			 */
void com_DMA()
{

  HAL_Init();
	
	  /* Configure the system clock to 168 Mhz */
  SystemClock_Config();
	  /*##-1- Configure the UART peripheral ######################################*/
  /* Put the USART peripheral in the Asynchronous mode (UART Mode) */
  /* UART configured as follows:
      - Word Length = 8 Bits
      - Stop Bit = One Stop bit
      - Parity = None
      - BaudRate = 9600 baud
      - Hardware flow control disabled (RTS and CTS signals) */

  UartHandle.USART_BaudRate   = 38400;
  UartHandle.USART_WordLength = USART_WordLength_8b;
  UartHandle.USART_StopBits   = USART_StopBits_1;
  UartHandle.USART_Parity     = USART_Parity_No;
  UartHandle.USART_HardwareFlowControl  = USART_HardwareFlowControl_None;
  UartHandle.USART_Mode       = USART_Mode_Rx|USART_Mode_Tx;
  
  if(HAL_UART_DeInit(&UartHandle) != HAL_OK)
  {
    Error_Handler();
  } 
  if(HAL_UART_Init(&UartHandle) != HAL_OK)
  {
    Error_Handler();
  }
  
#ifdef TRANSMITTER_BOARD

  /* Configure User push-button */
  BSP_PB_Init(BUTTON_USER, BUTTON_MODE_GPIO);
  
  /* Wait for User push-button press before starting the Communication */
  while (BSP_PB_GetState(BUTTON_USER) == RESET)
  {
  }
  
  /* The board sends the message and expects to receive it back */
  
  /*##-2- Start the transmission process #####################################*/  
  /* While the UART in reception process, user can transmit data through 
     "aTxBuffer" buffer */
  if(HAL_UART_Transmit_DMA(&UartHandle, (uint8_t*)aTxBuffer, TXBUFFERSIZE)!= HAL_OK)
  {
    Error_Handler();
  }
  
  /*##-3- Wait for the end of the transfer ###################################*/  
  while (UartReady != SET)
  {
  }
  
  /* Reset transmission flag */
  UartReady = RESET;
  
  /*##-4- Put UART peripheral in reception process ###########################*/  
  if(HAL_UART_DeInit(&UartHandle) != HAL_OK)
  {
    Error_Handler();
  } 
  if(HAL_UART_Init(&UartHandle) != HAL_OK)
  {
    Error_Handler();
  }  
  if(HAL_UART_Receive_DMA(&UartHandle, (uint8_t *)aRxBuffer, RXBUFFERSIZE) != HAL_OK)
  {
    Error_Handler();
  }

#else
  
  /* The board receives the message and sends it back */

  /*##-2- Put UART peripheral in reception process ###########################*/  
  if(HAL_UART_Receive_DMA(&UartHandle, (uint8_t *)aRxBuffer, RXBUFFERSIZE) != HAL_OK)
  {
    Error_Handler();
  }
  
  /*##-3- Wait for the end of the transfer ###################################*/  
  while (UartReady != SET)
  {
  }

  /* Reset transmission flag */
  UartReady = RESET;
  
  /*##-4- Start the transmission process #####################################*/  
  /* While the UART in reception process, user can transmit data through 
     "aTxBuffer" buffer */
  if(HAL_UART_DeInit(&UartHandle) != HAL_OK)
  {
    Error_Handler();
  } 
  if(HAL_UART_Init(&UartHandle) != HAL_OK)
  {
    Error_Handler();
  }     
  if(HAL_UART_Transmit_DMA(&UartHandle, (uint8_t*)aTxBuffer, TXBUFFERSIZE)!= HAL_OK)
  {
    Error_Handler();
  }
  
#endif /* TRANSMITTER_BOARD */
  
  /*##-5- Wait for the end of the transfer ###################################*/  
  while (UartReady != SET)
  {
  }

  /* Reset transmission flag */
  UartReady = RESET;

  /*##-6- Compare the sent and received buffers ##############################*/
  if(Buffercmp((uint8_t*)aTxBuffer,(uint8_t*)aRxBuffer,RXBUFFERSIZE))
  {
    Error_Handler();
  }
   
  /* Infinite loop */
  while (1)
  {
  }
}
Example #13
0
static T_Ack_Nack WifiCom_Lire_Data ( T_Buf_Wifi *Buf )
{
  T_Ack_Nack qualite ;
	uint16_t 	taille = 0 ; 					// par défaut 
	uint32_t  crc_recu ;

	
	if ( 			( Buf->Transport.Header1 ==  HEADER1 )
				&&	( Buf->Transport.Header2 ==  HEADER2 )	)
	{	/* Header correct */	
		switch ( Buf->Transport.Type	)
		{	/* vérifie le type de message reçu */
			case TYPE_MSG_REGLAGE :
				taille = Buf->Transport.Nombre_Doctets;
				crc_recu = Buf->Reglage.Crc ;		
			break ;
			
			case TYPE_MSG_DE_SERVICE :
				taille = Buf->Transport.Nombre_Doctets ;
				crc_recu = Buf->De_Service.Crc ;
			break ;

/*			case TYPE_MSG_SCAN :
				taille = TAILLE_MESSAGE_TRANSPORT ;
				crc_recu = Buf->Buf_Transport.Crc ;
			break ;  */
			
			default :
			/* reçu un message de type inconnu */			
			break ; 
		}
	}
		
	if ( taille != 0 )
	{
		if ( 	crc_recu == Calcule_Checksum (Buf->Word, taille/4)  ) 			
		{	/* le checksum est bon alors récupére les données */
			switch ( Buf->Transport.Type	)
			{
				case TYPE_MSG_REGLAGE :		
					Etat_Moteur[MOTEUR_DROIT].CoefP  			= Buf->Reglage.Etat_Moteur_Droit.CoefP ;
					Etat_Moteur[MOTEUR_DROIT].CoefI  			= Buf->Reglage.Etat_Moteur_Droit.CoefI ;
					Etat_Moteur[MOTEUR_DROIT].CoefD  			= Buf->Reglage.Etat_Moteur_Droit.CoefD ;
					Etat_Moteur[MOTEUR_GAUCHE].CoefP 			= Buf->Reglage.Etat_Moteur_Gauche.CoefP ;
					Etat_Moteur[MOTEUR_GAUCHE].CoefI 			= Buf->Reglage.Etat_Moteur_Gauche.CoefI ;
					Etat_Moteur[MOTEUR_GAUCHE].CoefD 			= Buf->Reglage.Etat_Moteur_Gauche.CoefD ;
					ConsigneManuelle.Vitesse			   			= Buf->Reglage.ConsigneManuelle.Vitesse;
					ConsigneManuelle.ConsigneAngulaire		= Buf->Reglage.ConsigneManuelle.ConsigneAngulaire ;	
					Phare_Luminosite 											=	Buf->Reglage.Phare_Luminosite  ;								
					Mode_Commande	 												=	Buf->Reglage.Mode_Commande ;											
					ConsigneBoucle_Ouverte[MOTEUR_DROIT]	= Buf->Reglage.ConsigneBoucle_Ouverte_Moteur_Droit  ; 
					ConsigneBoucle_Ouverte[MOTEUR_GAUCHE]	= Buf->Reglage.ConsigneBoucle_Ouverte_Moteur_Gauche ;
					Offset_Orientation_Lidar							= Buf->Reglage.Offset_Orientation_Lidar ;
					ConsigneAngulaireNulle								= Buf->Reglage.ConsigneAngulaireNulle ;
					Compensation_Ligne_Droite							= Buf->Reglage.Compensation_Ligne_Droite;
					Suivi_De_Mur													= Buf->Reglage.Suivi_De_Mur	;
			
					qualite = SANS_ACK_NACK ; 
					
			#ifdef DEBUG_WIFI 
					++ Msg_Reglage_Rx ; 
			#endif
				break ;
					
/*				case TYPE_MSG_SCAN :   transfert du contenu au bon endroit et vérifie si scan complet 
					LazerScanRec.Transport.Type 		 							=  Buf->Transport.Type	; 
					LazerScanRec.Transport.Total_Octet 		 				=  Buf->Transport.Total_Octet	; 
					LazerScanRec.Transport.Position_Premier_Octet	=  Buf->Transport.Position_Premier_Octet ; 	
					if ( Buf->Transport.Position_Premier_Octet == 0 ) 
						LazerScanRec.Transport.Nombre_Doctets = 0 ; 
					memcpy ( &LazerScanRec.Data[Buf->Transport.Position_Premier_Octet], Buf->Buf_Transport.Data, Buf->Transport.Nombre_Doctets ) ;					
					LazerScanRec.Transport.Nombre_Doctets		+=  Buf->Transport.Nombre_Doctets ;
				  if ( LazerScanRec.Transport.Nombre_Doctets == LazerScanRec.Transport.Total_Octet )
					{	 le scan a été reçu entierement 
						Lazer_Scan_Received () ;					
					}			
					qualite = ACK_MSG ;
				break ; 
*/				
				case TYPE_MSG_DE_SERVICE :					
					switch ( Buf->De_Service.Type.Service.Requete ) 
					{
						case REQUETE_ACK_NACK :			// réception du nack du message envoyé précédemment 
																		// ou de ack / nack du message TYPE_MSG_SCAN envoyé précédemment	
							Presence_Host = Buf->De_Service.Type.Service.Presence_Host ;
						
							if ( Transport_Emis.Etat_Transport == EN_COUR )
							{	/* si envoi d'un message long en cour */
								if ( Buf->De_Service.Type.Service.Ack_Nack == ACK_MSG )
								{	/* envoi du paquet suivant s'il en reste */
									Transport_Emis.Max_Repetition = MAX_REPETITION_TRANSPORT ;
									if  ( WifiCom_Transmit_NextPacket() == -1 )
									{ /* Envoi du message terminé, recu ACK du dernier paquet envoyé*/	
										Transport_Emis.Etat_Transport = DONE ; 
									}
				#ifdef DEBUG_WIFI								
									++ Msg_Requete_RxAck ;
				#endif
								}
								else
								{	/* renvoi du message */						
									if ( Transport_Emis.Max_Repetition-- != 0 )
									{
									  HAL_UART_Transmit_DMA(&Wifi_Com_Uart, Transport_Emis.Wifi_Buf_Emi.Octet, TAILLE_MESSAGE) ;
									}
									else
									{ /* Envoi du message aborté*/
										Transport_Emis.Etat_Transport = ABORT ;																					
									}	
				#ifdef DEBUG_WIFI									
									++Msg_Requete_RxNack	 ;
				#endif
								}	
							}
							else
							{
								if ( Buf->De_Service.Type.Service.Ack_Nack == NACK_MSG )
								{	/* renvoi du message */
									if ( Max_Repetition-- != 0 )
									{
										HAL_UART_Transmit_DMA(&Wifi_Com_Uart, Wifi_Buf_Emi.Octet, TAILLE_MESSAGE);
									}
									else
									{ /* Envoi du message aborté*/	
										Max_Repetition = 0 ; 										
									}
				#ifdef DEBUG_WIFI								
									++Msg_Requete_RxNack	 ;	
				#endif					
								}		
				#ifdef DEBUG_WIFI						
								else
										++Msg_Requete_RxAck	 ;	
				#endif				
							}					
						break ; 
							
						case REQUETE_SERVICE :
							/* message envoyé par défaut par la carte wifi lorsque pas de message du Host */
							Presence_Host = Buf->De_Service.Type.Service.Presence_Host ;
				#ifdef DEBUG_WIFI							
							++ Msg_Requete_service	;	
				#endif
						break ; 
											
						case REQUETE_MSG_REGLAGE :
							Requete_Exterieure = REQUETE_MSG_REGLAGE ; 
						break ; 
						
						case REQUETE_ENREGISTRE_PARAM1 :
							Sauvegarde_Tout_Request () ; 
						break ; 
						
						case REQUETE_ENREGISTRE_PARAM2 :
						break ; 
						
						case REQUETE_MSG_SCAN :
							Lazer_Scan_Request (Buf->De_Service.Type.Demande.Arg1, Buf->De_Service.Type.Demande.Arg2) ;
						break ;												

#ifdef HMC5883L_VALIDATION 							
						case REQUETE_MSG_COMPAS_XY :
							HMC5883L_Request (Buf->De_Service.Type.Demande.Arg1 ) ;
						break ;
#endif
						default :
								/* reçu une requete inconnue */						
						break ; 
					}	
					qualite = SANS_ACK_NACK ;	 /* on n'acquitte pas les messages de requete */
				break ;
				
				default :
					/* reçu un message de type inconnu On ne peut normalement jamais arriver ici */		
					qualite = SANS_ACK_NACK ;					
				break ; 
			}				
		}
		else
		{ /* le message reçu présente une erreur de CRC */
	#ifdef DEBUG_WIFI				
			ERREUR_CHECKSUM ++ ; 		
	#endif
			if ( Transport_Emis.Etat_Transport == EN_COUR )
			{ /* Envoi du message terminé car on ne se comprend plus c'est une erreur sur reception du msg d'ack/nack */
				Transport_Emis.Etat_Transport = ABORT ;		
				qualite = SANS_ACK_NACK ;					
			}	
			else
			{				
				qualite = NACK_MSG ;
			}
		} 
	}
	else
	{ /* reçu un message de type inconnu ou header non conforme */	
		if ( Transport_Emis.Etat_Transport == EN_COUR )
		{ /* Envoi du message terminé car on ne se comprend plus c'est une erreur sur reception du msg d'ack/nack */
			Transport_Emis.Etat_Transport = ABORT ;		
		}			
		qualite = ERREUR_SYNCHRO ;	
	#ifdef DEBUG_WIFI				
		++ Mesg_defaut_Synchro  ;
	#endif		
	}
	return ( qualite ) ;
}
Example #14
0
int EELib_UART_Transmit(uint8_t *pData, uint16_t Size)
{
	HAL_UART_Transmit_DMA(&huart1, pData, Size);
	while(__HAL_UART_GET_FLAG(&huart1, UART_FLAG_TC) == RESET){}
}
Example #15
0
File: main.c Project: ndhuan/GPSRTK
int main()//OPTIMIZATION LEVEL = 0
{
	HAL_Init();
	SystemClockConfig();
	ConfigLED();
	ConfigTimer();

	rtksvrstart(&svr);

	ConfigUART(svr.format[0]);

	fobs[0]=fobs[1]=0;

	//svr.raw[1].time.time = 1429540822;//test SS2 data
	//svr.raw[1].time.time = 1429539852;//test SS2 data
	
	while (HAL_UART_Receive_DMA(&UartGPSHandle,svr.buff[0],MAX_RAW_LEN) != HAL_OK);	
	while (HAL_UART_Receive_DMA(&UartRFHandle,svr.buff[1],MAX_RAW_LEN) != HAL_OK);	

	HAL_Delay(3000);
	sendRequest(svr.format[0]);
	
//	test();

	while(1)
	{
#ifndef _TEST_RESULT		
		if (flagTimeout)
		{

			int index,temp;
			flagTimeout=0;
			//SendIntStr(UartGPSHandle.Instance->SR);
			//SendIntStr(UartRFHandle.Instance->SR);
			for (index=0;index<2;index++)
			{
				if (index==0)
					temp = UartGPSHandle.hdmarx->Instance->NDTR & 0xffff;
				else
					temp = UartRFHandle.hdmarx->Instance->NDTR & 0xffff;					
				
				if (temp + svr.buffPtr[index] <= MAX_RAW_LEN)
					svr.nb[index] = MAX_RAW_LEN - svr.buffPtr[index] - temp;
				else
					svr.nb[index] = 2*MAX_RAW_LEN - temp - svr.buffPtr[index];
				
				fobs[index] =	decode_raw(&svr,index);

				svr.buffPtr[index] = MAX_RAW_LEN - temp;	

			}
			
//			temp = UartGPSHandle.hdmarx->Instance->NDTR & 0xffff;
//			if (temp + svr.buffPtr[0] <= MAX_RAW_LEN)
//					svr.nb[0] = MAX_RAW_LEN - svr.buffPtr[0] - temp;
//			else
//					svr.nb[0] = 2*MAX_RAW_LEN - temp - svr.buffPtr[0];
//			if (svr.buffPtr[0] + svr.nb[0] <= MAX_RAW_LEN)
//			{
//				for (i = svr.buff[0] + svr.buffPtr[0] ; 
//							i < svr.buff[0] + svr.buffPtr[0] + svr.nb[0]; i++)
//				{
//					HAL_UART_Transmit(&UartResultHandle,i,1,1);

//				}
//			}
//			else
//			{
//				for (i = svr.buff[0] + svr.buffPtr[0] ; 
//							i < svr.buff[0] + MAX_RAW_LEN; i++)
//				{
//					HAL_UART_Transmit(&UartResultHandle,i,1,1);

//				}
//				for (i = svr.buff[0] ; 
//					i < svr.buff[0] + svr.nb[0] + svr.buffPtr[0] - MAX_RAW_LEN ; i++)
//				{
//					HAL_UART_Transmit(&UartResultHandle,i,1,1);
//				}		
//			}
//			svr.buffPtr[0] = MAX_RAW_LEN - temp;


		//rtk positioning**********************************************************************
//		if (0)	
			if (fobs[1])
			{
				fobs[1]=0;
				LED4_TOGGLE;
			}
			if (fobs[0])
			{						
				int i;
				fobs[0]=0;
				LED3_TOGGLE;
#ifdef TIME_MEASURE
				start=HAL_GetTick();
#endif			
				temp=svr.obs[0].n;
				for (i=0;i<temp;i++)
				{
					obsd[i]=svr.obs[0].data[i];				
				}
				for (i=0;(i<svr.obs[1].n)&&(i+temp<MAX_OBS);i++)
				{
					obsd[i+temp]=svr.obs[1].data[i];				
				}			
				if (!rtkpos(&svr.rtk,obsd,i+temp,&svr.nav))
	//			if (1)
				{

					LED5_TOGGLE;

#ifdef TIME_MEASURE
					t=HAL_GetTick()-start;
					svr.rtk.sol.processTime = t;	
#endif					
					if (svr.rtk.sol.stat==SOLQ_FIX)
						LED6_TOGGLE;
					
					outsol(&svr.rtk.sol,svr.rtk.rb);
					SendStr(svr.rtk.sol.result);
				}
				else
				{
					HAL_UART_Transmit_DMA(&UartResultHandle,(unsigned char*)svr.rtk.errbuf,svr.rtk.errLen);
				}
			}
		}
		

#else	
		if (flagTimeout)
		{
			static int i;
			char* res = svr.rtk.sol.result;
			flagTimeout = 0;
			
			res+=sprintf(res,
		"%04.0f/%02.0f/%02.0f %02.0f:%02.0f:%06.3f %14.4f %14.4f %14.4f %3d %3d %8.4f %8.4f %8.4f %8.4f %8.4f %8.4f %6.2f %6.1f",
			2015.0,10.0,12.0,3.0,45.0,18.0,//time yy/mm/dd hh:mm:ss.ssss
			1.0,2.0,1.0,
			1,1,
			1.0,1.0,1.0,
			1.0,1.0,1.0,
			1.0,1.0);
			res+=sprintf(res," %4d",i++);
			res[0]='\n';
			SendStr(svr.rtk.sol.result);
		}
#endif		
	}
	
}
Example #16
0
/*-----------------------------------------------------------*/
void DEBUGConsoleTask(void const * argument)//( void *pvParameters )
{
char 		cRxedChar;
uint8_t 	ucInputIndex = 0;
char 		*pcOutputString;					// указатель на выходной буфер
static char cInputString[ cmdMAX_INPUT_SIZE ], cLastInputString[ cmdMAX_INPUT_SIZE ];
BaseType_t 	xReturned;

//	( void ) pvParameters;

	// создадим семафоры и мьютексы используемые задачей
	xDEBUGbusMutex = xSemaphoreCreateMutex();			// блокировка доступа к USART
	vSemaphoreCreateBinary( xNewDataSemaphore );		// сигнал о принятии новых данных
	// проверим создались правильно или нет ?
	configASSERT( xDEBUGbusMutex );
	configASSERT( xNewDataSemaphore );

	// добавим семафоры и мьютексы в очередь для просмотра ЯДРОМ (стейтмашиной)
	//  API-функция vQueueAddToRegistry() не имеет другого предназначения, кроме как для целей отладки. Причем до-
	// бавлять в реестр следует только те очереди, поведение которых необходимо выяснить в ходе отладки.
	vQueueAddToRegistry( xDEBUGbusMutex, "DBGMu" );
	vQueueAddToRegistry( xNewDataSemaphore, "DBGDat" );


	// Получим адрес выходного буфера.
	pcOutputString = DEBUG_GetOutputBuffer();

	// Инит выходного драйвера
//	BOOT_UART_Init(115200);

	// отправим привет
//	HAL_UART_Transmit_DMA(&BOOT_UART, (uint8_t *)"DBG->", strlen( "DBG->" ));

	for( ;; )
	{
		// обнулим счетчик принятых данных
		cRxedChar = 0;

		// читаем по одному принятому символу за раз
		cRxedChar = cGetChar();
		if( xSemaphoreTake( xDEBUGbusMutex, cmdMAX_MUTEX_WAIT ) == pdPASS )							// подождем семафор освобождения порта cmdMAX_MUTEX_WAIT время
		{
			// возвращаем ЭХО.
//			HAL_UART_Transmit(&BOOT_UART, (uint8_t *)&cRxedChar, 1, 0xFFFF);
			HAL_UART_Transmit_DMA(&BOOT_UART, (uint8_t *)&cRxedChar, 1);

			// Был ли это конец строки?
			if( cRxedChar == '\n' || cRxedChar == '\r' )
			{
				// Переводим каретку на следующую строку
//				HAL_UART_Transmit(&BOOT_UART, (uint8_t *)pcNewLine, strlen( pcNewLine ), 0xFFFF);
				HAL_UART_Transmit_DMA(&BOOT_UART, (uint8_t *)pcNewLine, strlen( pcNewLine ));

				//если команда пуста, то последняя команда должна быть выполнена повторно.
				if( ucInputIndex == 0 )
				{
					// Скопируем последнюю команду обратно в строку ввода.
					strcpy( cInputString, cLastInputString );
				}

				// прогоняем полученную команду через интерпретатора команд. Вызываем его многократно, пока он не вернёт pdFALSE
				// т.к. он может генерировать более одной строки.
				do
				{
					// получаем строку для вывода из интерпретатора команд.
					xReturned = DEBUG_ProcessCommand( cInputString, pcOutputString, BOOT_BUF_MAX_OUTPUT_SIZE );
					vTaskDelay( 1 );
					// передадим ответ в порт
					HAL_UART_Transmit_DMA(&BOOT_UART, (uint8_t *)pcOutputString, strlen( pcOutputString ));
					vTaskDelay( 10 );

				} while( xReturned != pdFALSE );

				// Очистить строку ввода для приема следующей команды. Запомним
				// команду, которая была, на случай если она должна быть
				// обрабатывается снова.
				strcpy( cLastInputString, cInputString );
				ucInputIndex = 0;
				memset( cInputString, 0x00, cmdMAX_INPUT_SIZE );

				HAL_UART_Transmit_DMA(&BOOT_UART, (uint8_t *)pcEndOfOutputMessage, strlen( pcEndOfOutputMessage ));

			}
			else
			{
				if( cRxedChar == '\r' )
				{
					// игнорируем символ
				}
				else if( cRxedChar == '\b' )
				{
					// Backspace - удаление последнего символа в командной строке
					if( ucInputIndex > 0 )
					{
						ucInputIndex--;
						cInputString[ ucInputIndex ] = '\0';
					}
				}
				else
				{
					// добавляем символ в строку введённую до этого. Если введена \n то команду отправляем на выполнение.
					if( ( cRxedChar >= ' ' ) && ( cRxedChar <= '~' ) )
					{
						if( ucInputIndex < cmdMAX_INPUT_SIZE )
						{
							cInputString[ ucInputIndex ] = cRxedChar;
							ucInputIndex++;
						}
					}
				}
			}

			// Вернём мьютекс.
			xSemaphoreGive( xDEBUGbusMutex );
		}
	}
}
Example #17
0
void myNecErrorCallback() {
    char* msg = "Error!\n";
    HAL_UART_Transmit_DMA(&huart3, (uint8_t*) msg, strlen(msg));
    HAL_Delay(10);
    NEC_Read(&nec);
}
Example #18
0
int bluetoothSend(unsigned char *data, int length)
{
    return HAL_UART_Transmit_DMA(&huart3, data, length);
}
/**
  * @brief  CDC_Itf_DataRx
  *         Data received over USB OUT endpoint are sent over CDC interface 
  *         through this function.
  * @param  Buf: Buffer of data to be transmitted
  * @param  Len: Number of data received (in bytes)
  * @retval Result of the operation: USBD_OK if all operations are OK else USBD_FAIL
  */
static int8_t CDC_Itf_Receive(uint8_t* Buf, uint32_t *Len)
{
  HAL_UART_Transmit_DMA(&UartHandle, Buf, *Len);
  return (USBD_OK);
}
Example #20
0
/**
  * @brief  Main program
  * @param  None
  * @retval None
  */
int main(void)
{
#ifdef TRANSMITTER_BOARD
  GPIO_InitTypeDef  GPIO_InitStruct;
#endif
  /* STM32F0xx HAL library initialization:
       - Configure the Flash prefetch
       - Systick timer is configured by default as source of time base, but user 
             can eventually implement his proper time base source (a general purpose 
             timer for example or other time source), keeping in mind that Time base 
             duration should be kept 1ms since PPP_TIMEOUT_VALUEs are defined and 
             handled in milliseconds basis.
       - Low Level Initialization
     */
  HAL_Init();

  /* Configure the system clock to 48 MHz */
  SystemClock_Config();
  
  /* Configure LED3 */
  BSP_LED_Init(LED3);

#ifdef TRANSMITTER_BOARD
  /* Configure PA.12 (Arduino D2) as input with External interrupt */
  GPIO_InitStruct.Pin = GPIO_PIN_12;
  GPIO_InitStruct.Pull = GPIO_PULLUP;
  GPIO_InitStruct.Mode = GPIO_MODE_IT_RISING;

  /* Enable GPIOA clock */
  __HAL_RCC_GPIOA_CLK_ENABLE();

  HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);

  /* Enable and set PA.12 (Arduino D2) EXTI Interrupt to the lowest priority */
  NVIC_SetPriority((IRQn_Type)(EXTI4_15_IRQn), 0x03);
  HAL_NVIC_EnableIRQ((IRQn_Type)(EXTI4_15_IRQn));
  /* Wait for the user to set GPIOA to GND before starting the Communication.
     In the meantime, LED3 is blinking */
  while(VirtualUserButtonStatus == 0)
  {
      /* Toggle LED3*/
      BSP_LED_Toggle(LED3);
      HAL_Delay(100);
  }

  BSP_LED_Off(LED3);
#endif

  /*##-1- Configure the UART peripheral ######################################*/
  /* Put the USART peripheral in the Asynchronous mode (UART Mode) */
  /* UART configured as follows:
      - Word Length = 8 Bits
      - Stop Bit = One Stop bit
      - Parity = None
      - BaudRate = 9600 baud
      - Hardware flow control disabled (RTS and CTS signals) */
  UartHandle.Instance        = USARTx;

  UartHandle.Init.BaudRate   = 9600;
  UartHandle.Init.WordLength = UART_WORDLENGTH_8B;
  UartHandle.Init.StopBits   = UART_STOPBITS_1;
  UartHandle.Init.Parity     = UART_PARITY_NONE;
  UartHandle.Init.HwFlowCtl  = UART_HWCONTROL_NONE;
  UartHandle.Init.Mode       = UART_MODE_TX_RX;
  UartHandle.AdvancedInit.AdvFeatureInit = UART_ADVFEATURE_NO_INIT;
  if(HAL_UART_DeInit(&UartHandle) != HAL_OK)
  {
    Error_Handler();
  }  
  if(HAL_UART_Init(&UartHandle) != HAL_OK)
  {
    Error_Handler();
  }
  
#ifdef TRANSMITTER_BOARD
  
  /* The board sends the message and expects to receive it back */
  /* DMA is programmed for reception before starting the transmission, in order to
     be sure DMA Rx is ready when board 2 will start transmitting */

  /*##-2- Program the Reception process #####################################*/  
  if(HAL_UART_Receive_DMA(&UartHandle, (uint8_t *)aRxBuffer, RXBUFFERSIZE) != HAL_OK)
  {
    Error_Handler();
  }

  /*##-3- Start the transmission process #####################################*/  
  /* While the UART in reception process, user can transmit data through 
     "aTxBuffer" buffer */
  if(HAL_UART_Transmit_DMA(&UartHandle, (uint8_t*)aTxBuffer, TXBUFFERSIZE)!= HAL_OK)
  {
    Error_Handler();
  }
  
  /*##-4- Wait for the end of the transfer ###################################*/  
  while (UartReady != SET)
  {
  }

  /* Reset transmission flag */
  UartReady = RESET;
  
#else
  
  /* The board receives the message and sends it back */

  /*##-2- Put UART peripheral in reception process ###########################*/  
  if(HAL_UART_Receive_DMA(&UartHandle, (uint8_t *)aRxBuffer, RXBUFFERSIZE) != HAL_OK)
  {
    Error_Handler();
  }

  /*##-3- Wait for the end of the transfer ###################################*/
  /* While waiting for message to come from the other board, LED3 is
     blinking according to the following pattern: a double flash every half-second */  
  while (UartReady != SET)
  {
      BSP_LED_On(LED3); 
      HAL_Delay(100);
      BSP_LED_Off(LED3); 
      HAL_Delay(100);
      BSP_LED_On(LED3); 
      HAL_Delay(100);
      BSP_LED_Off(LED3); 
      HAL_Delay(500); 
  }

  /* Reset transmission flag */
  UartReady = RESET;
  BSP_LED_Off(LED3); 
  
  /*##-4- Start the transmission process #####################################*/  
  /* While the UART in reception process, user can transmit data through 
     "aTxBuffer" buffer */
  if(HAL_UART_Transmit_DMA(&UartHandle, (uint8_t*)aTxBuffer, TXBUFFERSIZE)!= HAL_OK)
  {
    Error_Handler();
  }
  
#endif /* TRANSMITTER_BOARD */
  
  /*##-5- Wait for the end of the transfer ###################################*/  
  while (UartReady != SET)
  {
  }

  /* Reset transmission flag */
  UartReady = RESET;

  /*##-6- Compare the sent and received buffers ##############################*/
  if(Buffercmp((uint8_t*)aTxBuffer,(uint8_t*)aRxBuffer,RXBUFFERSIZE))
  {
    Error_Handler();
  }
   
  /* Turn on LED3 if test passes then enter infinite loop */
  BSP_LED_On(LED3); 
  /* Infinite loop */
  while (1)
  {
  }
}
Example #21
0
/**
  * @brief  Main program
  * @param  None
  * @retval None
  */
int main(void)
{    
  /* STM32F4xx HAL library initialization:
       - Configure the Flash prefetch, instruction and Data caches
       - Configure the Systick to generate an interrupt each 1 msec
       - Set NVIC Group Priority to 4
       - Global MSP (MCU Support Package) initialization
     */
  HAL_Init();
  
  /* Configure the system clock to 168 MHz */
  SystemClock_Config();
  
  /* Configure LED1, LED2 and LED3 */
  BSP_LED_Init(LED1);
  BSP_LED_Init(LED2);
  BSP_LED_Init(LED3);
  
  /*##-1- Configure the UART peripheral ######################################*/
  /* Put the USART peripheral in the Asynchronous mode (UART Mode) */
  /* UART1 configured as follow:
      - Word Length = 8 Bits
      - Stop Bit    = One Stop bit
      - Parity      = ODD parity
      - BaudRate    = 9600 baud
      - Hardware flow control disabled (RTS and CTS signals) */
  UartHandle.Instance          = USARTx;
  
  UartHandle.Init.BaudRate     = 9600;
  UartHandle.Init.WordLength   = UART_WORDLENGTH_8B;
  UartHandle.Init.StopBits     = UART_STOPBITS_1;
  UartHandle.Init.Parity       = UART_PARITY_ODD;
  UartHandle.Init.HwFlowCtl    = UART_HWCONTROL_NONE;
  UartHandle.Init.Mode         = UART_MODE_TX_RX;
  UartHandle.Init.OverSampling = UART_OVERSAMPLING_16;
    
  if(HAL_UART_Init(&UartHandle) != HAL_OK)
  {
    /* Initialization Error */
    Error_Handler(); 
  }
  /*##-2- Start the transmission process #####################################*/  
  /* User start transmission data through "TxBuffer" buffer */
  if(HAL_UART_Transmit_DMA(&UartHandle, (uint8_t*)aTxStartMessage, TXSTARTMESSAGESIZE)!= HAL_OK)
  {
    /* Transfer error in transmission process */
    Error_Handler();  
  }
  
  /*##-3- Put UART peripheral in reception process ###########################*/  
  /* Any data received will be stored in "RxBuffer" buffer : the number max of 
     data received is 10 */
  if(HAL_UART_Receive_DMA(&UartHandle, (uint8_t *)aRxBuffer, RXBUFFERSIZE) != HAL_OK)
  {
    /* Transfer error in reception process */
    Error_Handler();     
  }

  /*##-4- Wait for the end of the transfer ###################################*/  
  while (HAL_UART_GetState(&UartHandle) != HAL_UART_STATE_READY)
  {
  } 
 
  /*##-5- Send the received Buffer ###########################################*/  
  if(HAL_UART_Transmit_DMA(&UartHandle, (uint8_t*)aRxBuffer, RXBUFFERSIZE)!= HAL_OK)
  {
    /* Transfer error in transmission process */
    Error_Handler();    
  }
  
  /*##-6- Wait for the end of the transfer ###################################*/  
  while (HAL_UART_GetState(&UartHandle) != HAL_UART_STATE_READY)
  {
  }
  
  /*##-7- Send the End Message ###############################################*/  
  if(HAL_UART_Transmit_DMA(&UartHandle, (uint8_t*)aTxEndMessage, TXENDMESSAGESIZE)!= HAL_OK)
  {
    /* Turn LED3 on: Transfer error in transmission process */
    BSP_LED_On(LED3);
    while(1)
    {
    }      
  }
  
  /*##-8- Wait for the end of the transfer ###################################*/  
  while (HAL_UART_GetState(&UartHandle) != HAL_UART_STATE_READY)
  {
  }
  
  /* Infinite loop */  
  while (1)
  {
  }
}
/**
  * @brief  Uart send data in non blocking mode
  * @param  huart: pointer to a UART_HandleTypeDef structure that contains
  * @param  p_data: Pointer to data buffer
  * @param  size: Amount of data to be sent
  */
void write_uart_noblocking(UART_HandleTypeDef *huart, uint8_t *p_data, uint16_t size)
{
  HAL_UART_Transmit_DMA(huart, p_data, size);
}
Example #23
0
/**
  * @brief  Main program
  * @param  None
  * @retval None
  */
int main(void)
{
    /* STM32F3xx HAL library initialization:
         - Configure the Flash prefetch
         - Systick timer is configured by default as source of time base, but user
           can eventually implement his proper time base source (a general purpose
           timer for example or other time source), keeping in mind that Time base
           duration should be kept 1ms since PPP_TIMEOUT_VALUEs are defined and
           handled in milliseconds basis.
         - Set NVIC Group Priority to 4
         - Low Level Initialization
       */
    HAL_Init();

    /* Configure the system clock to 72 MHz */
    SystemClock_Config();

    /* Configure LED5, LED6, LED4 and LED3 */
    BSP_LED_Init(LED5);
    BSP_LED_Init(LED6);
    BSP_LED_Init(LED4);
    BSP_LED_Init(LED3);

#ifdef TRANSMITTER_BOARD
    /* Configure User push-button in Interrupt mode */
    BSP_PB_Init(BUTTON_USER, BUTTON_MODE_EXTI);

    /* Wait for User push-button press before starting the Communication.
       In the meantime, LED6 is blinking */
    while(UserButtonStatus == 0)
    {
        /* Toggle LED6*/
        BSP_LED_Toggle(LED6);
        HAL_Delay(100);
    }

    BSP_LED_Off(LED6);
#endif

    /*##-1- Configure the UART peripheral ######################################*/
    /* Put the USART peripheral in the Asynchronous mode (UART Mode) */
    /* UART configured as follows:
        - Word Length = 8 Bits
        - Stop Bit = One Stop bit
        - Parity = None
        - BaudRate = 9600 baud
        - Hardware flow control disabled (RTS and CTS signals) */
    UartHandle.Instance        = USARTx;

    UartHandle.Init.BaudRate   = 9600;
    UartHandle.Init.WordLength = UART_WORDLENGTH_8B;
    UartHandle.Init.StopBits   = UART_STOPBITS_1;
    UartHandle.Init.Parity     = UART_PARITY_NONE;
    UartHandle.Init.HwFlowCtl  = UART_HWCONTROL_NONE;
    UartHandle.Init.Mode       = UART_MODE_TX_RX;
    UartHandle.AdvancedInit.AdvFeatureInit = UART_ADVFEATURE_NO_INIT;
    if(HAL_UART_DeInit(&UartHandle) != HAL_OK)
    {
        Error_Handler();
    }
    if(HAL_UART_Init(&UartHandle) != HAL_OK)
    {
        Error_Handler();
    }

#ifdef TRANSMITTER_BOARD

    /* The board sends the message and expects to receive it back */
    /* DMA is programmed for reception before starting the transmission, in order to
       be sure DMA Rx is ready when board 2 will start transmitting */

    /*##-2- Program the Reception process #####################################*/
    if(HAL_UART_Receive_DMA(&UartHandle, (uint8_t *)aRxBuffer, RXBUFFERSIZE) != HAL_OK)
    {
        Error_Handler();
    }

    /*##-3- Start the transmission process #####################################*/
    /* While the UART in reception process, user can transmit data through
       "aTxBuffer" buffer */
    if(HAL_UART_Transmit_DMA(&UartHandle, (uint8_t*)aTxBuffer, TXBUFFERSIZE)!= HAL_OK)
    {
        Error_Handler();
    }

    /*##-4- Wait for the end of the transfer ###################################*/
    while (UartReady != SET)
    {
    }

    /* Reset transmission flag */
    UartReady = RESET;

#else

    /* The board receives the message and sends it back */

    /*##-2- Put UART peripheral in reception process ###########################*/
    if(HAL_UART_Receive_DMA(&UartHandle, (uint8_t *)aRxBuffer, RXBUFFERSIZE) != HAL_OK)
    {
        Error_Handler();
    }

    /*##-3- Wait for the end of the transfer ###################################*/
    /* While waiting for message to come from the other board, LED6 is
       blinking according to the following pattern: a double flash every half-second */
    while (UartReady != SET)
    {
        BSP_LED_On(LED6);
        HAL_Delay(100);
        BSP_LED_Off(LED6);
        HAL_Delay(100);
        BSP_LED_On(LED6);
        HAL_Delay(100);
        BSP_LED_Off(LED6);
        HAL_Delay(500);
    }

    /* Reset transmission flag */
    UartReady = RESET;
    BSP_LED_Off(LED6);

    /*##-4- Start the transmission process #####################################*/
    /* While the UART in reception process, user can transmit data through
       "aTxBuffer" buffer */
    if(HAL_UART_Transmit_DMA(&UartHandle, (uint8_t*)aTxBuffer, TXBUFFERSIZE)!= HAL_OK)
    {
        Error_Handler();
    }

#endif /* TRANSMITTER_BOARD */

    /*##-5- Wait for the end of the transfer ###################################*/
    while (UartReady != SET)
    {
    }

    /* Reset transmission flag */
    UartReady = RESET;

    /*##-6- Compare the sent and received buffers ##############################*/
    if(Buffercmp((uint8_t*)aTxBuffer,(uint8_t*)aRxBuffer,RXBUFFERSIZE))
    {
        Error_Handler();
    }

    /* Infinite loop */
    while (1)
    {
    }
}
/**
  * @brief  It's LOW-LEVEL usart transmition function
  * 				it indicates where and how the data should be transmitted
  * @param  huart:Which usart port used to transmit the data
  * @retval null
  */
static void UART_TransmitContent(UART_HandleTypeDef *huart)
{
	HAL_UART_Transmit_DMA(&huart1, (uint8_t*)txbuf, strlen(txbuf) + 1);
	while(huart1.State == HAL_UART_STATE_BUSY_TX || huart1.State == HAL_UART_STATE_BUSY_TX_RX);
}
Example #25
0
/**
  * @brief  Main program
  * @param  None
  * @retval None
  */
int main(void)
{
  /* STM32F0xx HAL library initialization:
       - Configure the Flash prefetch
       - Systick timer is configured by default as source of time base, but user 
         can eventually implement his proper time base source (a general purpose 
         timer for example or other time source), keeping in mind that Time base 
         duration should be kept 1ms since PPP_TIMEOUT_VALUEs are defined and 
         handled in milliseconds basis.
       - Low Level Initialization
     */
  HAL_Init();
  
  /* Configure LED1, LED2 and LED3 */
  BSP_LED_Init(LED1);
  BSP_LED_Init(LED2);
  BSP_LED_Init(LED3);
  
  /* Configure the system clock to 48 MHz */
  SystemClock_Config();

  /*##-1- Configure the UART peripheral ######################################*/
  /* Put the USART peripheral in the Asynchronous mode (UART Mode) */
  /* UART configured as follows:
      - Word Length = 8 Bits
      - Stop Bit    = One Stop bit
      - Parity      = ODD parity
      - BaudRate    = 9600 baud
      - Hardware flow control disabled (RTS and CTS signals) */
  UartHandle.Instance        = USARTx;

  UartHandle.Init.BaudRate   = 9600;
  UartHandle.Init.WordLength = UART_WORDLENGTH_8B;
  UartHandle.Init.StopBits   = UART_STOPBITS_1;
  UartHandle.Init.Parity     = UART_PARITY_ODD;
  UartHandle.Init.HwFlowCtl  = UART_HWCONTROL_NONE;
  UartHandle.Init.Mode       = UART_MODE_TX_RX;

  if (HAL_UART_Init(&UartHandle) != HAL_OK)
  {
    /* Initialization Error */
    Error_Handler();
  }
  /*##-2- Start the transmission process #####################################*/
  /* User start transmission data through "TxBuffer" buffer */
  if (HAL_UART_Transmit_DMA(&UartHandle, (uint8_t *)aTxBuffer, TXBUFFERSIZE) != HAL_OK)
  {
    /* Transfer error in transmission process */
    Error_Handler();
  }

  /*##-3- Put UART peripheral in reception process ###########################*/
  /* Any data received will be stored in "RxBuffer" buffer : the number max of
     data received is 10 */
  if (HAL_UART_Receive_DMA(&UartHandle, (uint8_t *)aRxBuffer, RXBUFFERSIZE) != HAL_OK)
  {
    /* Transfer error in reception process */
    Error_Handler();
  }

  /*##-4- Wait for the end of the transfer ###################################*/
  /*  Before starting a new communication transfer, you need to check the current
      state of the peripheral; if it’s busy you need to wait for the end of current
      transfer before starting a new one.
      For simplicity reasons, this example is just waiting till the end of the
      transfer, but application may perform other tasks while transfer operation
      is ongoing. */
  while (HAL_UART_GetState(&UartHandle) != HAL_UART_STATE_READY)
  {
  }

  /*##-5- Send the received Buffer ###########################################*/
  if (HAL_UART_Transmit_DMA(&UartHandle, (uint8_t *)aRxBuffer, RXBUFFERSIZE) != HAL_OK)
  {
    /* Transfer error in transmission process */
    Error_Handler();
  }

  /*##-6- Wait for the end of the transfer ###################################*/
  /*  Before starting a new communication transfer, you need to check the current
      state of the peripheral; if it’s busy you need to wait for the end of current
      transfer before starting a new one.
      For simplicity reasons, this example is just waiting till the end of the
      transfer, but application may perform other tasks while transfer operation
      is ongoing. */
  while (HAL_UART_GetState(&UartHandle) != HAL_UART_STATE_READY)
  {
  }

  /* Infinite loop */
  while (1)
  {
  }
}
Example #26
0
int main(void)
{

  /* USER CODE BEGIN 1 */

	// create pointer to MX_SPI_Init() function in order to use it in utility functions
   MX_SPI1_Init_Pointer = &MX_SPI1_Init;

  /* USER CODE END 1 */

  /* MCU Configuration----------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* Configure the system clock */
  SystemClock_Config();

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_DMA_Init();
  //MX_SPI1_Init();
  MX_TIM16_Init();
  MX_TIM17_Init();
  MX_USART1_UART_Init();
  MX_USART2_UART_Init();
  MX_WWDG_Init();

  /* USER CODE BEGIN 2 */
	// delete MX_SPI1_Init(); up there after regenerating code with mx cube

	//=================================================================================
	/// some basic setups
	//=================================================================================

	// input is up
	// output is down
	uart_queue_initialize(&uart_input_queue);
	uart_queue_initialize(&uart_output_queue);
	uart_queue_initialize(&uart_command_queue);

	// load setup_data from flash to struct: config_data_flash_struct setup_data;
	get_from_Flash();

	LED_init();

	if(setup_data.initied_0xAA!=0xAA)
	{
		reset_joint();
	}

	part_init();

	/// FIND DIRECTION = WAIT FOR FIRST 'R'
	DIRECTION_SET = 0;

	PROGRAMM_SENSOR = 0;
	SET_FLASH = 0;

	UP_STATE = IDLE;
	DOWN_STATE = IDLE;

	// init some huart stuff
	huart_DOWN = &huart1;
	huart_UP = &huart2;

	uint16_t si = 0;
	data_mode = 0;

	HAL_StatusTypeDef status;

	// create empty messages
	Line empty_command_line;
	empty_command_line.text[0] = empty;
	for(si=1; si < DOWN_MESSAGE_LENGTH-1; si++)
	{
		empty_command_line.text[si] = si;
	}

	empty_command_line.text[DOWN_MESSAGE_LENGTH-1] = ComputeCRCN(empty_command_line.text, DOWN_MESSAGE_LENGTH-1);
	empty_command_line.length = DOWN_MESSAGE_LENGTH;

	Line empty_up_line;
	empty_up_line.text[0] = empty;
	for(si=1; si < UP_MESSAGE_LENGTH-1; si++)
	{
		empty_up_line.text[si] = si;
	}

	empty_up_line.text[UP_MESSAGE_LENGTH-1] = ComputeCRCN(empty_up_line.text, UP_MESSAGE_LENGTH-1);
	empty_up_line.length = UP_MESSAGE_LENGTH;

	// start timer
	HAL_TIM_Base_Start(&htim16);
	HAL_TIM_Base_Start(&htim17);

	// send some initial init messages
	uart_queue_push_line(&uart_input_queue, &init_message_line);

	if(is_splitter(setup_data.type))
	{
		for(si = 0; si < 8; si++)
		{
			if(setup_data.splitter_outputs[si]==1)
			{
				uart_queue_push_line(&uart_input_queue, &splitter_message_lines[si]);
				skc[si] = 1;
			}
		}
	}

	int redled_timeout_timer = __HAL_TIM_GetCounter(&htim16);

	int init_timout_timer = __HAL_TIM_GetCounter(&htim16);

	interrupt_up_timeout_time = __HAL_TIM_GetCounter(&htim16);
	interrupt_down_timeout_time = __HAL_TIM_GetCounter(&htim16);

	int new_sensor_timer = __HAL_TIM_GetCounter(&htim16);

	int up_timeout_timer = __HAL_TIM_GetCounter(&htim16);

	int kids_timer[] = {-1,-1,-1,-1,-1,-1,-1,-1};

	transmittedUP=0;
	receivedUP=0;
	transmittedDOWN=0;
	receivedDOWN=0;

	uint8_t TIMEDOUT = 0;

	update_sensor_messages();

	HAL_HalfDuplex_EnableTransmitterReceiver(huart_DOWN);
	HAL_HalfDuplex_EnableTransmitterReceiver(huart_UP);
	HAL_UART_Receive_DMA(huart_UP, up_buffer, DOWN_MESSAGE_LENGTH + 1);
	HAL_UART_Receive_DMA(huart_DOWN, down_buffer, DOWN_MESSAGE_LENGTH + 1);

	led_set(1, 1, 0);

	//while(1);

	//if(is_splitter(setup_data.type))
	HAL_WWDG_Start(&hwwdg);

  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */

	get_up_time = __HAL_TIM_GetCounter(&htim16);

	uint8_t WDGO = 0;

	uint8_t WDSET = 0;

  while (1)
  {
  /* USER CODE END WHILE */

  /* USER CODE BEGIN 3 */

//	if((WD_UP && WD_DOWN) || DIRECTION_SET==0)
//	{
//		WD_UP = 0;
//		WD_DOWN = 0;
//		// for up and dwn we have own flags
//
//		HAL_WWDG_Refresh(&hwwdg, 127);
//	}

	if(DIRECTION_SET && WDSET==0)
	{
		HAL_WWDG_Start(&hwwdg);
		WDSET = 1;
		up_timeout_timer = __HAL_TIM_GetCounter(&htim16);
	}

	if(WDGO==0 || is_splitter(setup_data.type)==0)
	{
		HAL_WWDG_Refresh(&hwwdg, 127);
	}


	// if there was no poll from above a certain time = reset!
	if(__HAL_TIM_GetCounter(&htim16) - interrupt_up_timeout_time > 250)
	{
		WDGO = 1;

		get_up(1);

		interrupt_up_timeout_time = __HAL_TIM_GetCounter(&htim16);

		UP_STATE = IDLE;
	}


	// if there was no interrupt call for data from below
	if(__HAL_TIM_GetCounter(&htim16) - interrupt_down_timeout_time > 250)
	{
		WDGO = 1;

		HAL_UART_DMAStop(huart_DOWN);
		HAL_UART_DMAResume(huart_DOWN);

		if(!DIRECTION_SET)
		{
			HAL_HalfDuplex_EnableTransmitterReceiver(huart_DOWN);
			HAL_UART_Receive_DMA(huart_DOWN, down_buffer, DOWN_MESSAGE_LENGTH + 1);
		}

		interrupt_down_timeout_time = __HAL_TIM_GetCounter(&htim16);

		DOWN_STATE = IDLE;
	}

	  // wait for directions to be set
	if(!DIRECTION_SET)
	{
		led_set(8, 1, 8);
		continue;
	}

	led_set(8, 0, 8);

	if(__HAL_TIM_GetCounter(&htim16) - get_up_time > 20 && receivedUP == 0)
	{
		get_up(0);
	}

	// red blinking led
	if(__HAL_TIM_GetCounter(&htim16) - redled_timeout_timer > 250)
	{
		HAL_GPIO_TogglePin(GPIOB, GPIO_PIN_0);
		redled_timeout_timer = __HAL_TIM_GetCounter(&htim16);
	}

	if(__HAL_TIM_GetCounter(&htim16) - up_timeout_timer > 500)
	{
		WDGO = 1;
	}

	// sent init messages
	if(__HAL_TIM_GetCounter(&htim16) - init_timout_timer > 1000)
	{
		uart_queue_replace_push_line(&uart_input_queue, &init_message_line, setup_data.id);

		if(is_splitter(setup_data.type))
		{
			for(si = 0; si < 8; si++)
			{
				if(setup_data.splitter_outputs[si]==1)
				{
					uart_queue_push_line(&uart_input_queue, &splitter_message_lines[si]);
				}
			}
		}

		init_timout_timer = __HAL_TIM_GetCounter(&htim16);
	}

	if(SET_FLASH && UP_STATE == IDLE && DOWN_STATE == IDLE)
	{
		HAL_HalfDuplex_EnableTransmitter(huart_UP);

		set_in_Flash(&setup_data);
		SET_FLASH = 0;

		get_up(1);
	}

	if(PROGRAMM_SENSOR && UP_STATE == IDLE && DOWN_STATE == IDLE)
	{
		HAL_HalfDuplex_EnableTransmitter(huart_UP);

		if(setup_data.hardware == 2)
			init_2D(hspi1, GPIOA, GPIO_PIN_3);
		else
			init_2D(hspi1, GPIOB, GPIO_PIN_1);

		PROGRAMM_SENSOR = 0;

		get_up(1);
	}

	/// UP_STATE_MACHINE
	switch(UP_STATE)
	{
		case IDLE:
			if(SET_FLASH || PROGRAMM_SENSOR)
			{
				UP_STATE = IDLE;
				break;
			}

			if(receivedUP)
			{
				receivedUP = 0;

				if(up_buffer[0] == poll_receive /*&& __HAL_TIM_GetCounter(&htim16) - receivedUPtime < 5*/)
				{
					if(UP_RESEND_MESSAGE==0)
					{
						//update_sensor_messages();

						uint8_t n_up_messages = 0;

						while(uart_queue_is_empty(&uart_input_queue)==0 && (n_up_messages < UP_MESSAGES_MAX))
						{
							uart_queue_pop_line(&uart_input_queue, &send_up_line);
							memcpy(&poll_up_buffer[n_up_messages*(UP_MESSAGE_LENGTH)], send_up_line.text, UP_MESSAGE_LENGTH);

							n_up_messages++;
						}

						while(n_up_messages < UP_MESSAGES_MAX)
						{
							memcpy(&poll_up_buffer[n_up_messages*(UP_MESSAGE_LENGTH)], empty_up_line.text, UP_MESSAGE_LENGTH);

							n_up_messages++;
						}

						poll_up_size = n_up_messages*UP_MESSAGE_LENGTH;
					}

					UP_RESEND_MESSAGE = 0;
					UP_STATE = SENDING;

					HAL_HalfDuplex_EnableTransmitter(huart_UP);
					HAL_UART_Transmit_DMA(huart_UP, poll_up_buffer, poll_up_size);
					int something_else = __HAL_TIM_GetCounter(&htim16);

					if(up_buffer[1]!=empty)
					{
						memcpy(command_in_line.text, &up_buffer[1], DOWN_MESSAGE_LENGTH);
						command_in_line.length = DOWN_MESSAGE_LENGTH;

						uint8_t checksum = ComputeCRCN(command_in_line.text, DOWN_MESSAGE_LENGTH-1);

						if(checksum == command_in_line.text[DOWN_MESSAGE_LENGTH-1])
						{
							if(command_in_line.text[0] == poll_direct || getIDfromMessage(command_in_line.text)==setup_data.id)
							{
								uart_queue_push_line(&uart_command_queue, &command_in_line);

								if((command_in_line.text[0] == poll_send) && (setup_data.type==NODE_JOINT_TUT_TU))
									uart_queue_push_line(&uart_output_queue, &command_in_line);
							}
							else if(getIDfromMessage(command_in_line.text)==BROADCAST_ID)
							{
								uart_queue_push_line(&uart_command_queue, &command_in_line);
								uart_queue_push_line(&uart_output_queue, &command_in_line);
							}
							else
							{
								uart_queue_push_line(&uart_output_queue, &command_in_line);
							}
						}
					}

					if(is_splitter(setup_data.type))
					{
						/*__disable_irq();
						delayUS(10000);
						__enable_irq();*/
					}
					else
					{
						update_sensor_messages();
					}

					up_timeout_time = __HAL_TIM_GetCounter(&htim16);
				}
				else
				{
					//HAL_UART_DMAStop(huart_UP);
					//HAL_UART_DMAResume(huart_UP);

					// HAL_UART_Receive(huart_UP, &up_buffer[1], DOWN_MESSAGE_LENGTH, 2);

					get_up(1);
				}
			}
			break;

		case SENDING:
			if(transmittedUP)
			{
				UP_STATE = END;
				transmittedUP = 0;
			}
			else if(__HAL_TIM_GetCounter(&htim16) - up_timeout_time > 10)
			{
				HAL_UART_DMAStop(huart_UP);
				HAL_UART_DMAResume(huart_UP);
				UP_STATE = END;
			}
			break;

		case END:
			WD_UP = 1;
			up_timeout_timer = __HAL_TIM_GetCounter(&htim16);

			// work on commands

			UP_STATE = IDLE;
			get_up(1);
			break;
	}

	uint8_t s=0;

	switch(DOWN_STATE)
	{
		case DELAY:
			if(is_splitter(setup_data.type) || (__HAL_TIM_GetCounter(&htim16) - down_timeout_time > 7) /* && TIMEDOUT==0 */)
				DOWN_STATE = IDLE;

			/*else if (__HAL_TIM_GetCounter(&htim16) - down_timeout_time > 5)
				DOWN_STATE = IDLE;*/
			break;

		case IDLE:
			// do nothing
			if(SET_FLASH || PROGRAMM_SENSOR)
			{
				DOWN_STATE = IDLE;
				break;
			}


			if(is_splitter(setup_data.type))
			{
				if(splitter_kids_counter[i_p_splitter] > 10)
				{
					splitter_kids_counter[i_p_splitter] = 9;
					kids_timer[i_p_splitter] = __HAL_TIM_GetCounter(&htim16) + 200;
				}

				if(kids_timer[i_p_splitter]!=-1 && kids_timer[i_p_splitter] > __HAL_TIM_GetCounter(&htim16))
				{
					interrupt_down_timeout_time = __HAL_TIM_GetCounter(&htim16);
					DOWN_STATE = END;
					break;
				}

				if(skc[i_p_splitter] == 0)
				{
					send_down_line = send_down_line_now;
				}
				else
				{
					send_down_line = empty_command_line;
				}
			}


			if(skc[0]+skc[1]+skc[2]+skc[3]+skc[4]+skc[5]+skc[6]+skc[7] >= n_splitter)
			{
				if(uart_queue_is_empty(&uart_output_queue)==0)
				{
					uart_queue_pop_line(&uart_output_queue, &send_down_line_now);
					send_down_line = send_down_line_now;
					for(s=0; s<n_splitter; s++)
						skc[s] = 0;
				}
				else
				{
					send_down_line = empty_command_line;
					for(s=0; s<n_splitter; s++)
						skc[s] = 1;
				}
			}

			//send_down_line = empty_command_line;

			if(is_splitter(setup_data.type))
			{
				MPX_UART_Open(i_p_splitter);
			}

			DOWN_STATE = RECEIVING;

			//__disable_irq();
			HAL_HalfDuplex_EnableTransmitter(huart_DOWN);
			status = HAL_UART_Transmit(huart_DOWN, "R", 1, 3);

			status = HAL_UART_Transmit(huart_DOWN, send_down_line.text, DOWN_MESSAGE_LENGTH, 5);
			//__enable_irq();

			// DMA Receive for 3
			HAL_HalfDuplex_EnableTransmitterReceiver(huart_DOWN);
			HAL_UART_Receive_DMA(huart_DOWN, poll_down_buffer, UP_MESSAGE_LENGTH*UP_MESSAGES_MAX);

			down_timeout_time = __HAL_TIM_GetCounter(&htim16);
			break;

		case RECEIVING:
			if(receivedDOWN)
			{
				receivedDOWN = 0;
				splitter_kids_counter[i_p_splitter] = 0;
				skc[i_p_splitter] = 1;
				kids_timer[i_p_splitter] = -1;

				// no more transmitting checksum, only calculating
				uint8_t checksum = ComputeCRCN(&poll_down_buffer[poll_down_size-UP_MESSAGE_LENGTH], UP_MESSAGE_LENGTH-1);

				uint8_t i = 0;

				for(i=0; i<UP_MESSAGES_MAX; i++)
				{
					// check checksum
					if(1 /*checksum == poll_down_buffer[i*UP_MESSAGE_LENGTH-1]*/)
					{
						Line sensor_message_line;
						memcpy(sensor_message_line.text, &poll_down_buffer[i*UP_MESSAGE_LENGTH], UP_MESSAGE_LENGTH);
						sensor_message_line.length = UP_MESSAGE_LENGTH;

						if(sensor_message_line.text[0]==empty)
							break;

						// delete messages from T joint but the answer_data, there update angles[3]
						if(getIDfromMessage(sensor_message_line.text)==setup_data.id && setup_data.type == NODE_JOINT_TUT_TU && data_mode!=2)
						{
							if(sensor_message_line.text[0] == answer_data)
								angles[3] = ((sensor_message_line.text[15] << 8) & 0xFF00) + sensor_message_line.text[16];
						}
						else // for the other kinds (splitter, init, data from other) replace them if already in queue, ack messages always add to queue
						{
							// if it's from own child, add own id
							if(sensor_message_line.text[5]==0)
							{
								sensor_message_line.text[5] = (setup_data.id >> 24) & 0xFF;
								sensor_message_line.text[6] =  (setup_data.id >> 16) & 0xFF;
								sensor_message_line.text[7] = (setup_data.id >> 8) & 0xFF;
								sensor_message_line.text[8] = setup_data.id & 0xFF;

								// add splitter branch number
								if(is_splitter(setup_data.type))
									sensor_message_line.text[5] |= ((i_p_splitter << 4) & 0xF0);
							}

							UpdateCRCLine(&sensor_message_line);

							if(sensor_message_line.text[0] == answer_ack || sensor_message_line.text[0] == splitter)
								uart_queue_push_line(&uart_input_queue, &sensor_message_line);
							else
								uart_queue_replace_push_line(&uart_input_queue, &sensor_message_line, getIDfromMessage(sensor_message_line.text));
						}
					}
				}

				DOWN_STATE = END;
				TIMEDOUT = 0;
			}
			else if(__HAL_TIM_GetCounter(&htim16) - down_timeout_time > 13)