void printWelcomeMessage(void) { char *strings[] = {"\033[0;0H", "\033[2J", WELCOME_MSG, MAIN_MENU, PROMPT}; for (uint8_t i = 0; i < 5; i++) { HAL_UART_Transmit_IT(&huart2, (uint8_t*)strings[i], strlen(strings[i])); while (HAL_UART_GetState(&huart2) == HAL_UART_STATE_BUSY_TX || HAL_UART_GetState(&huart2) == HAL_UART_STATE_BUSY_TX_RX); } }
uint16_t FillTxBuffer(const uint8_t *buffer, uint16_t count) { uint8_t irqEnabled = __get_PRIMASK() == 0; HAL_StatusTypeDef st; uint16_t free, freestart, tocopy, copied = 0; UNUSED(st); __disable_irq(); freestart = g_txStart + g_txCount; free = g_size - g_txCount; EnableIrq(irqEnabled); freestart -= (freestart >= g_size) ? g_size : 0; if(count > free) count = free; tocopy = freestart + count > g_size ? g_size - freestart : count; memcpy(g_buffer + freestart, buffer, tocopy); __disable_irq(); if(!g_txCount) { EnableIrq(irqEnabled); g_chunkSize = tocopy; st = HAL_UART_Transmit_IT(g_huart, g_buffer + freestart, tocopy); } copied = tocopy; count -= tocopy; __disable_irq(); g_txCount += tocopy; EnableIrq(irqEnabled); if(!count) return copied; buffer += tocopy; memcpy(g_buffer, buffer, count); uint8_t schedule; __disable_irq(); schedule = !g_txCount; g_txCount += count; EnableIrq(irqEnabled); if(schedule) // unlikely corner case st = HAL_UART_Transmit_IT(g_huart, g_buffer, count); return copied + count; }
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart) { if(Rx_Data[0] != 59) // 받은 문자가 ';'이 아니면 { if(Buffer_idx >= MAX_BUFFER_SIZE) // 수신버퍼의 사이즈가 5가 넘으면 { Buffer_idx = 0; // 버퍼인덱스도 0부터 시작 for(int i = 0; i<MAX_BUFFER_SIZE; i++) Rx_Buffer[i] = '\0'; } Rx_Buffer[Buffer_idx] = Rx_Data[0]; // 수신데이터를 버퍼에 처넣음 Buffer_idx++; HAL_UART_Receive_IT(&huart1, (uint8_t *)Rx_Data, 1); // 다시 받을 준비 } else // ';'을 받으면 { char temp[50]; sprintf(temp, "Rx_Data : %c\tBuffer : %s\tBuffer_Idx : %d\n", Rx_Data[0], Rx_Buffer, Buffer_idx); Buffer_idx = 0; // 버퍼 초기화 for(int i = 0; i<MAX_BUFFER_SIZE; i++) Rx_Buffer[i] = '\0'; // 버퍼 초기화 HAL_UART_Transmit_IT(&huart1, (uint8_t *)temp, 50); } }
uint8_t UART_Transmit(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t len) { if(HAL_UART_Transmit_IT(huart, pData, len) != HAL_OK) { if(RingBuffer_Write(&txBuf, pData, len) != RING_BUFFER_OK) return 0; } return 1; }
/** * @brief Transmite informaçao pela UART com IT * @param huart: apontador para estrutura UART_HandleTypeDef que tem informaçºao sobre as * configuraçoes do modulo de UART * @param data: apontador para buffer de informaçao a enviar * @param Size: tamanho de informaçºao a enviar * @retval HAL status (HAL_OK , HAL_ERROR , HAL_BUSY) */ HAL_StatusTypeDef Lib_UART_Transmit_IT(UART_HandleTypeDef *huart, uint8_t * data, uint16_t Size) { HAL_StatusTypeDef result; result = HAL_UART_Transmit_IT(huart, data , Size ); return result; }
/** * @brief Transmit data * @param Data: Pointer to the buffer to send * @param Size: Size of the buffer * @retval None */ void rs232Transmit(uint8_t* Data, uint32_t Size) { /* Make sure the UART is available */ if (Size != 0 && xSemaphoreTake(xSemaphore, 100) == pdTRUE) { HAL_UART_Transmit_IT(&UART_Handle, Data, Size); } }
/** * @brief CDC_Receive_FS * Data received over USB OUT endpoint are sent over CDC interface * through this function. * * @note * This function will block any OUT packet reception on USB endpoint * untill exiting this function. If you exit this function before transfer * is complete on CDC interface (ie. using DMA controller) it will result * in receiving more data while previous ones are still not sent. * * @param Buf: Buffer of data to be received * @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_Receive_FS (uint8_t* Buf, uint32_t *Len) { /* USER CODE BEGIN 6 */ USBD_CDC_SetRxBuffer(hUsbDevice_0, &Buf[0]); USBD_CDC_ReceivePacket(hUsbDevice_0); HAL_UART_Transmit_IT(&huart2, Buf, *Len); return (USBD_OK); /* USER CODE END 6 */ }
int serial_tx_asynch(serial_t *obj, const void *tx, size_t tx_length, uint8_t tx_width, uint32_t handler, uint32_t event, DMAUsage hint) #endif { // DMA usage is currently ignored (void) hint; // Check buffer is ok MBED_ASSERT(tx != (void*)0); MBED_ASSERT(tx_width == 8); // support only 8b width if (tx_length == 0) return 0; // Set up buffer h_serial_tx_buffer_set(obj, (void *)tx, tx_length, tx_width); // Set up events h_serial_tx_enable_event(obj, SERIAL_EVENT_TX_ALL, 0); // Clear all events h_serial_tx_enable_event(obj, event, 1); // Set only the wanted events UART_HandleTypeDef *handle = &UartHandle[SERIAL_OBJ(index)]; // Enable interrupt IRQn_Type irqn = h_serial_get_irq_index(obj); NVIC_ClearPendingIRQ(irqn); NVIC_DisableIRQ(irqn); NVIC_SetPriority(irqn, 1); NVIC_SetVector(irqn, (uint32_t)handler); NVIC_EnableIRQ(irqn); #if DEVICE_SERIAL_ASYNCH_DMA // Enable DMA interrupt irqn = h_serial_tx_get_irqdma_index(obj); NVIC_ClearPendingIRQ(irqn); NVIC_DisableIRQ(irqn); NVIC_SetPriority(irqn, 1); NVIC_SetVector(irqn, (uint32_t)handler); NVIC_EnableIRQ(irqn); // the following function will enable program and enable the DMA transfer if (HAL_UART_Transmit_DMA(handle, (uint8_t*)tx, tx_length) != HAL_OK) { /* Transfer error in transmission process */ return 0; } #else // the following function will enable UART_IT_TXE and error interrupts if (HAL_UART_Transmit_IT(handle, (uint8_t*)tx, tx_length) != HAL_OK) { /* Transfer error in transmission process */ return 0; } #endif DEBUG_PRINTF("UART%u: Tx: 0=(%u, %u) %x\n", obj->serial.module+1, tx_length, tx_width, HAL_UART_GetState(handle)); return tx_length; }
/** * @brief * @param None * @retval None */ void UART1_SendByte(uint8_t Byte) { /* * We need to save the Byte to send in a variable here as the HAL_UART saves * a pointer to the variable. If we had used Byte directly it would save a * pointer to the register where Byte is stored temporarily. */ static uint8_t temp = 0; temp = Byte; HAL_UART_Transmit_IT(&UART_Handle, &temp, 1); }
/** Begin asynchronous TX transfer. The used buffer is specified in the serial object, * tx_buff * * @param obj The serial object * @param tx The buffer for sending * @param tx_length The number of words to transmit * @param tx_width The bit width of buffer word * @param handler The serial handler * @param event The logical OR of events to be registered * @param hint A suggestion for how to use DMA with this transfer * @return Returns number of data transfered, or 0 otherwise */ int serial_tx_asynch(serial_t *obj, const void *tx, size_t tx_length, uint8_t tx_width, uint32_t handler, uint32_t event, DMAUsage hint) { // Check buffer is ok MBED_ASSERT(tx != (void*)0); MBED_ASSERT(tx_width == 8); // support only 8b width if (tx_length == 0) return 0; // Set up buffer h_serial_tx_buffer_set(obj, (void *)tx, tx_length, tx_width); // Set up events h_serial_tx_enable_event(obj, SERIAL_EVENT_TX_ALL, 0); // Clear all events h_serial_tx_enable_event(obj, event, 1); // Set only the wanted events // Enable interrupt IRQn_Type irqn = h_serial_get_irq_index(obj); NVIC_ClearPendingIRQ(irqn); NVIC_DisableIRQ(irqn); NVIC_SetPriority(irqn, 1); NVIC_SetVector(irqn, (uint32_t)handler); UartHandle.Instance = (USART_TypeDef *)SERIAL_OBJ(uart); NVIC_EnableIRQ(irqn); #if DEVICE_SERIAL_ASYNCH_DMA // Enable DMA interrupt irqn = h_serial_tx_get_irqdma_index(obj); NVIC_ClearPendingIRQ(irqn); NVIC_DisableIRQ(irqn); NVIC_SetPriority(irqn, 1); // NVIC_SetVector(irqn, (uint32_t)&h_serial_txdma_irq_handler_asynch); NVIC_SetVector(irqn, (uint32_t)handler); NVIC_EnableIRQ(irqn); // the following function will enable program and enable the DMA transfer if (HAL_UART_Transmit_DMA(&UartHandle, (uint8_t*)tx, tx_length) != HAL_OK) { /* Transfer error in transmission process */ return 0; } #else // the following function will enable UART_IT_TXE and error interrupts if (HAL_UART_Transmit_IT(&UartHandle, (uint8_t*)tx, tx_length) != HAL_OK) { /* Transfer error in transmission process */ return 0; } #endif return tx_length; }
/*************************** *brif:串口2发送命令函数 *para:*command 命令地址 * num 命令长度 *return : 0 成功 * 1 失败 ****************************/ uint8_t Commands_Send(uint8_t *command, uint8_t num) { HAL_UART_Transmit_IT(&huart2,command,num); FingerDelay(30); if(UART_SEND_FLAG == 1) { UART_SEND_FLAG = 0; return 0; } else { return 1; } }
void Sendstring_Dia(void) { uint8_t value[]="Dia"; if(HAL_UART_Transmit_IT(&UartHandle, (uint8_t*)value, 3)!= HAL_OK) { Error_Handler(); } while (UartReady != SET) { } UartReady = RESET; }
void HardwareSerial::write(unsigned char ch) { tx_in_progress = true; if ( HAL_UART_Transmit_IT(&huart6, &ch, 1) != HAL_OK ) { tx_in_progress = false; } else { serial_write_start_timestamp = HAL_GetTick(); while ( tx_in_progress ) { if ( (HAL_GetTick() - serial_write_start_timestamp) > (unsigned long)SERIAL_WRITE_TIMEOUT_MS) { tx_in_progress = false; HAL_UART_ErrorCallback(&huart6); } } } }
void Sendnewline(void) { uint8_t value[]="\n\r"; if(HAL_UART_Transmit_IT(&UartHandle, (uint8_t*)value, 2)!= HAL_OK) { Error_Handler(); } while (UartReady != SET) { } UartReady = RESET; }
void HAL_UART_TxCpltCallback(UART_HandleTypeDef *huart) { HAL_StatusTypeDef st; UNUSED(st); if(huart == g_huart) { if(g_txCount) { g_txCount -= g_chunkSize; g_txStart += g_chunkSize; if(g_txStart >= g_size) g_txStart -= g_size; g_chunkSize = g_txStart + g_txCount > g_size ? g_size - g_txStart : g_txCount; if(g_chunkSize) st = HAL_UART_Transmit_IT(huart, g_buffer + g_txStart, g_chunkSize); } } }
int main(void) { /* USER CODE BEGIN 1 */ uint8_t Data[10]; /* 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(); /* USER CODE BEGIN 2 */ BSP_UART_Init(115200); /* Receive data on UART 6 */ trace_printf("Hello\n"); /* USER CODE END 2 */ /* Infinite loop */ /* USER CODE BEGIN WHILE */ while (1) { /* USER CODE END WHILE */ /* USER CODE BEGIN 3 */ if(HAL_UART_Receive_IT(&huart6,Data,10) == HAL_OK) { HAL_UART_Transmit_IT(&huart6,Data,10); } } /* USER CODE END 3 */ }
void SendDecimal(uint16_t value) { static char digit[4]; digit[0] = (unsigned int)(value/1000); // Calculate digit1 of ADC_value digit[1] = (unsigned int)((value - digit[0]*1000)/100); // Calculate digit2 of ADC_value digit[2] = (unsigned int)((value - (digit[0]*1000+digit[1]*100))/10); // Calculate digit3 of ADC_value digit[3] = (unsigned int)((value - (digit[0]*1000+digit[1]*100+digit[2]*10))/1); // Calculate digit4 of ADC_value digit[0]=digit[0]+0x30; digit[1]=digit[1]+0x30; digit[2]=digit[2]+0x30; digit[3]=digit[3]+0x30; //LCD_Printf(digit2); //LCD_Printf(digit3); //LCD_Printf(digit4); if(HAL_UART_Transmit_IT(&UartHandle, (uint8_t*)digit, 4)!= HAL_OK) { Error_Handler(); } while (UartReady != SET) { } UartReady = RESET; // if(HAL_UART_Transmit_IT(&UartHandle, (uint8_t*)digit+1, 1)!= HAL_OK) // { // Error_Handler(); // } // if(HAL_UART_Transmit_IT(&UartHandle, (uint8_t*)digit+2, 1)!= HAL_OK) // { // Error_Handler(); // } // if(HAL_UART_Transmit_IT(&UartHandle, (uint8_t*)digit+3, 1)!= HAL_OK) // { // Error_Handler(); // } }
/** * @brief CDC_Receive_FS * Callback. Data received over USB OUT endpoint are sent over CDC interface * through this function. * * @note * This function will block any OUT packet reception on USB endpoint * untill exiting this function. If you exit this function before transfer * is complete on CDC interface (ie. using DMA controller) it will result * in receiving more data while previous ones are still not sent. * * @param Buf: Buffer of data to be received * @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_Receive_FS (uint8_t* buf, uint32_t *len) { if(len == 0) return USBD_OK; /* not sure if this ever happens but it might */ /* Push the buffer we just received into the HAL UART TX quee */ HAL_StatusTypeDef r; while((r = HAL_UART_Transmit_IT(&huart2, buf, *len)) == HAL_BUSY) { // We could go into STOP mode here, but USB is connected so who cares about power? // UART, transmit timer are both higher priority interrupts so will interrupt us here } /* Swap the buffer that we'll receive next CDC packet into */ if(buf == cdc2usart_buf_a) USBD_CDC_SetRxBuffer(husb, cdc2usart_buf_b); else USBD_CDC_SetRxBuffer(husb, cdc2usart_buf_a); USBD_CDC_ReceivePacket(husb); return r == HAL_OK ? USBD_OK : USBD_FAIL; }
void mavlink_rc(double x, double y, bool give_up){ if( give_up ){ // 0 means give up roll = 0; pitch = 0; }else{ roll = pid.rollC + x*57.3f*10.0f; pitch = pid.pitchC + y*57.3f*10.0f; } // Pack the message mavlink_msg_rc_channels_override_pack(0xff, 0xbe, &tx_msg, 0x01, 0x01, roll, pitch, 0, 0, 0, 0, 0, 0); // Copy the message to the send buffer len = mavlink_msg_to_send_buffer(buf, &tx_msg); if( Uart1Ready ){ // Uart1Ready = false; HAL_UART_Transmit_IT(&Uart1Handle, buf, len); }/*else{ HAL_UART_DeInit(&Uart1Handle); uart1Init(); Uart1Ready = true; }*/ }
/** * Begin asynchronous TX transfer. The used buffer is specified in the serial * object, tx_buff * * @param obj The serial object * @param tx The buffer for sending * @param tx_length The number of words to transmit * @param tx_width The bit width of buffer word * @param handler The serial handler * @param event The logical OR of events to be registered * @param hint A suggestion for how to use DMA with this transfer * @return Returns number of data transfered, or 0 otherwise */ int serial_tx_asynch(serial_t *obj, const void *tx, size_t tx_length, uint8_t tx_width, uint32_t handler, uint32_t event, DMAUsage hint) { // TODO: DMA usage is currently ignored (void) hint; // Check buffer is ok MBED_ASSERT(tx != (void*)0); MBED_ASSERT(tx_width == 8); // support only 8b width struct serial_s *obj_s = SERIAL_S(obj); UART_HandleTypeDef * huart = &uart_handlers[obj_s->index]; if (tx_length == 0) { return 0; } // Set up buffer serial_tx_buffer_set(obj, (void *)tx, tx_length, tx_width); // Set up events serial_enable_event(obj, SERIAL_EVENT_TX_ALL, 0); // Clear all events serial_enable_event(obj, event, 1); // Set only the wanted events // Enable interrupt IRQn_Type irq_n = serial_get_irq_n(obj); NVIC_ClearPendingIRQ(irq_n); NVIC_DisableIRQ(irq_n); NVIC_SetPriority(irq_n, 1); NVIC_SetVector(irq_n, (uint32_t)handler); NVIC_EnableIRQ(irq_n); // the following function will enable UART_IT_TXE and error interrupts if (HAL_UART_Transmit_IT(huart, (uint8_t*)tx, tx_length) != HAL_OK) { return 0; } return tx_length; }
int main(void) { /* USER CODE BEGIN 1 */ /* 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_USART2_UART_Init(); /* USER CODE BEGIN 2 */ /* USER CODE END 2 */ /* Infinite loop */ /* USER CODE BEGIN WHILE */ while (1) { /* USER CODE END WHILE */ /* USER CODE BEGIN 3 */ HAL_UART_Transmit_IT(&huart2,pString,sizeof(pString)/sizeof(char)); HAL_Delay(500); } /* USER CODE END 3 */ }
void HAL_UART_TxCpltCallback(UART_HandleTypeDef *huart) { if(RingBuffer_GetDataLength(&txBuf) > 0) { RingBuffer_Read(&txBuf, &txData, 1); HAL_UART_Transmit_IT(huart, &txData, 1); } }
// Private Methods static void startTX(Client* c, bool timeout, bool kickstart, bool ack) { static volatile uint8_t txState = TX_IDLE; static int packetLength; // If we are waiting for an Ack and a timeout occured // we resend the last publish packet. if (timeout) { if (txState == TX_WAIT) { // Ack did not arrive in time, resend last pub txState = TX_IDLE; } else { return; } } // If we write to the tx buffer and the uart is idling // we should initiate the transmit process. if (kickstart && (txState != TX_IDLE)) { return; } // If we received an Ack, move on. if (ack && (txState == TX_WAIT)) { c->txBuf.pH += (uint8_t)packetLength; c->txBuf.isFull = false; txState = TX_IDLE; } switch (txState) { // Start sending the next packet case TX_IDLE: if (c->txBuf.available(&c->txBuf) > 0) { packetLength = (int)(c->txBuf.Buf[c->txBuf.pH]) + 1; if ((int)c->txBuf.pH + packetLength > 256) // check if packet surpasses buffer end { if (HAL_UART_Transmit_IT(c->peripheral_UART, &c->txBuf.Buf[c->txBuf.pH], 256 - c->txBuf.pH) != HAL_OK) return; // TODO: react on this c->lastOutAct = HAL_GetTick(); txState = TX_BUSY; } else { if (HAL_UART_Transmit_IT(c->peripheral_UART, &c->txBuf.Buf[c->txBuf.pH], (uint16_t)packetLength) != HAL_OK) return; c->lastOutAct = HAL_GetTick(); if ((c->txBuf.Buf[c->txBuf.pH + 1] & 0x7F) == PROTOCOL_PUBLISH) { c->expectedAckSeq = (c->txBuf.Buf[c->txBuf.pH + 1] & 0x80) > 0; c->ackOutstanding = true; txState = TX_WAIT; } else { c->txBuf.pH += (uint8_t)packetLength; c->txBuf.isFull = false; } } } break; // Complete sending of current packet case TX_BUSY: if (HAL_UART_Transmit_IT(c->peripheral_UART, c->txBuf.Buf, packetLength + c->txBuf.pH - 256) != HAL_OK) return; c->lastOutAct = HAL_GetTick(); if ((c->txBuf.Buf[c->txBuf.pH + 1] & 0x7F) == PROTOCOL_PUBLISH) { c->expectedAckSeq = (c->txBuf.Buf[c->txBuf.pH + 1] & 0x80) > 0; c->ackOutstanding = true; txState = TX_WAIT; } else { c->txBuf.pH += (uint8_t)packetLength; txState = TX_IDLE; c->txBuf.isFull = false; } break; case TX_WAIT: break; } }
/** * @brief Main program * @param None * @retval None */ int main(void) { /* STM32F4xx HAL library initialization: - Configure the Flash prefetch, instruction and Data caches - 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: global MSP (MCU Support Package) initialization */ HAL_Init(); /* Configure the system clock to 180 MHz */ SystemClock_Config(); /* Configure leds */ BSP_LED_Init(LED1); BSP_LED_Init(LED3); /*##-1- Configure the UART peripheral ######################################*/ /* Put the USART peripheral in the Asynchronous mode (UART Mode) */ /* UART configured as follows: - Word Length = 8 Bits (7 data bit + 1 parity bit) : BE CAREFUL : Program 7 data bits + 1 parity bit in PC HyperTerminal - 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 #####################################*/ /* While the UART in reception process, user can transmit data through "aTxBuffer" buffer */ if(HAL_UART_Transmit_IT(&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 "aRxBuffer" buffer : the number max of data received is 10 */ if(HAL_UART_Receive_IT(&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) { if (tx_complete == 1) { BSP_LED_Toggle(LED1); HAL_Delay(250); } } if (rx_complete == 1) { BSP_LED_On(LED1); } /*##-5- Send the received Buffer ###########################################*/ if(HAL_UART_Transmit_IT(&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) { } /*##-7- Send the End Message ###############################################*/ if(HAL_UART_Transmit_IT(&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) { } }
void SERVO_PROTOCOL_SendCommand (SERVO_PROTOCOL_Command cmd, uint8_t channelNum, uint16_t *data, uint32_t dataLength) { //data contains values in Little-endian format. //ServoController protocol uses this format too. servoTxBuffer[0] = cmd; uint32_t origLength;; switch (cmd) { case SERVO_SET_CHANNEL: servoTxBuffer[1] = channelNum; servoTxBuffer[2] = (uint8_t)data[0]; // LO byte of uint16_t servoTxBuffer[3] = (uint8_t)(data[0] >> 8); // HI byte of uint16_t origLength = 4; break; case SERVO_SET_CHANNELS: for (int i = 0; i < dataLength; i++) { uint16_t value = data[i]; servoTxBuffer[1 + i * 2] = (uint8_t)value; // LO byte of uint16_t servoTxBuffer[2 + i * 2] = (uint8_t)(value >> 8); // HI byte of uint16_t } origLength = 1 + dataLength * 2; break; default: return; break; } // Check buffer for special symbols. // Every special symbol increases // transmit length by 1. uint32_t fullLength = origLength; for (int i = 0; i < origLength; i++) { uint8_t byte = servoTxBuffer[i]; if (byte == END_PACKET_SYMBOL || byte == ESC_SYMBOL) { fullLength++; } } // Replace special symbols. // servoTxBuffer transmit length // is equal to fullLength. if (fullLength > origLength) { int32_t origIdx = origLength - 1; int32_t fullIdx = fullLength - 1; while (origIdx >= 0) { uint8_t byte = servoTxBuffer[origIdx--]; switch (byte) { case END_PACKET_SYMBOL: servoTxBuffer[fullIdx--] = ESC_END_REPLACE_SYMBOL; servoTxBuffer[fullIdx--] = ESC_SYMBOL; break; case ESC_SYMBOL: servoTxBuffer[fullIdx--] = ESC_ESC_REPLACE_SYMBOL; servoTxBuffer[fullIdx--] = ESC_SYMBOL; break; default: servoTxBuffer[fullIdx--] = byte; break; } } } // Add END_PACKET_SYMBOL to the end of buffer servoTxBuffer[fullLength++] = END_PACKET_SYMBOL; HAL_UART_Transmit_IT(&huart2, servoTxBuffer, fullLength); }
void uart::puts( const char * data) { HAL_UART_Transmit_IT( &huart, (uint8_t *)data, strlen(data)); }
/** * @brief Main program. * @param None * @retval None */ int main(void) { /* STM32L0xx HAL library initialization: - Configure the Flash prefetch, Flash preread and Buffer caches - 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 LED3 */ BSP_LED_Init(LED3); /* Configure the system clock to 32 Mhz */ SystemClock_Config(); /*##-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; if(HAL_UART_Init(&UartHandle) != HAL_OK) { Error_Handler(); } #ifdef TRANSMITTER_BOARD /* Configure Button Key */ BSP_PB_Init(BUTTON_KEY, BUTTON_MODE_GPIO); /* Toggle led3 waiting for user to press button */ BSP_LED_On(LED3); /* Wait for Button Key press before starting the Communication */ while (BSP_PB_GetState(BUTTON_KEY) == RESET) { } /* Wait for Button Key to be release before starting the Communication */ while (BSP_PB_GetState(BUTTON_KEY) == SET) { } /* Turn led3 off */ BSP_LED_Off(LED3); /* 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_IT(&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_Receive_IT(&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_IT(&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_Transmit_IT(&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 LED3 on: Transfer process is correct */ BSP_LED_On(LED3); /* Infinite loop */ while (1) { } }
/** * @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) { /* Turn LED3 on: in case of Initialization Error */ BSP_LED_On(LED3); while(1) { } } /*##-2- Start the transmission process #####################################*/ /* While the UART in reception process, user can transmit data through "aTxBuffer" buffer */ if(HAL_UART_Transmit_IT(&UartHandle, (uint8_t*)aTxStartMessage, TXSTARTMESSAGESIZE)!= HAL_OK) { /* Turn LED3 on: Transfer error in transmission process */ BSP_LED_On(LED3); while(1) { } } /*##-3- Put UART peripheral in reception process ###########################*/ /* Any data received will be stored "aRxBuffer" buffer : the number max of data received is 10 */ if(HAL_UART_Receive_IT(&UartHandle, (uint8_t *)aRxBuffer, RXBUFFERSIZE) != HAL_OK) { /* Turn LED3 on: Transfer error in reception process */ BSP_LED_On(LED3); while(1) { } } /*##-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_IT(&UartHandle, (uint8_t*)aRxBuffer, RXBUFFERSIZE)!= HAL_OK) { /* Turn LED3 on: Transfer error in transmission process */ BSP_LED_On(LED3); while(1) { } } /*##-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_IT(&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 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 LED2 */ BSP_LED_Init(LED2); /* 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 = 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 /* 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, LED2 is blinking */ while(UserButtonStatus == 0) { /* Toggle LED2*/ BSP_LED_Toggle(LED2); HAL_Delay(100); } BSP_LED_Off(LED2); /* 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_IT(&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_Receive_IT(&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_IT(&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(LED2); HAL_Delay(100); BSP_LED_Off(LED2); HAL_Delay(100); BSP_LED_On(LED2); HAL_Delay(100); BSP_LED_Off(LED2); HAL_Delay(500); } /* Reset transmission flag */ UartReady = RESET; BSP_LED_Off(LED2); /*##-4- Start the transmission process #####################################*/ /* While the UART in reception process, user can transmit data through "aTxBuffer" buffer */ if(HAL_UART_Transmit_IT(&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 LED2 if test passes then enter infinite loop */ BSP_LED_On(LED2); /* Infinite loop */ while (1) { } }
int main(void) { /* USER CODE BEGIN 1 */ char ADC_Tx_Data[70]; /* 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_ADC1_Init(); MX_USART1_UART_Init(); /* USER CODE BEGIN 2 */ HAL_UART_Receive_IT(&huart1, (uint8_t *)Rx_Data, 1); HAL_ADC_Start_DMA(&hadc1, (uint32_t*)&ADC_Value, 6); /* USER CODE END 2 */ /* Infinite loop */ /* USER CODE BEGIN WHILE */ while (1) { HAL_Delay(15); HAL_GPIO_TogglePin(GPIOC, GPIO_PIN_4); HAL_Delay(15); HAL_GPIO_TogglePin(GPIOC, GPIO_PIN_0); HAL_Delay(15); HAL_GPIO_TogglePin(GPIOC, GPIO_PIN_1); HAL_Delay(15); HAL_GPIO_TogglePin(GPIOC, GPIO_PIN_2); HAL_Delay(15); sprintf(ADC_Tx_Data,"ADC1:%4d\tADC2:%4d\tADC3:%4d\tADC4:%4d\tADC5:%4d\tADC6:%4d\n\r", ADC_Value[0], ADC_Value[1], ADC_Value[2], ADC_Value[3], ADC_Value[4], ADC_Value[5]); HAL_UART_Transmit_IT(&huart1, (uint8_t *)ADC_Tx_Data, 70); /* USER CODE END WHILE */ /* USER CODE BEGIN 3 */ } /* USER CODE END 3 */ }