Last active
September 24, 2023 12:17
-
-
Save x225am/433968c6a7f6372aa7a21e0a36d11ee1 to your computer and use it in GitHub Desktop.
stm32 read variable string via serial port
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "main.h" | |
#include <string.h> | |
UART_HandleTypeDef huart2; // Change this to your UART handler | |
#define MAX_STRING_LENGTH 50 // Maximum length of the received string | |
char receivedString[MAX_STRING_LENGTH]; // String buffer to store received data | |
uint8_t rxData; // Variable to store received byte | |
uint8_t rxBuffer[MAX_STRING_LENGTH]; // Buffer to store received bytes | |
uint16_t rxIndex = 0; // Index to keep track of received characters | |
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart) | |
{ | |
if (huart->Instance == USART2) // Check if the UART instance is correct | |
{ | |
if (rxData != '\n') // Check if the received byte is not a newline character | |
{ | |
rxBuffer[rxIndex++] = rxData; // Store the received byte in the buffer | |
if (rxIndex >= MAX_STRING_LENGTH) | |
{ | |
// Handle buffer overflow error here | |
// You can set an error flag, clear the buffer, or take appropriate action | |
rxIndex = 0; // Reset the index | |
} | |
} | |
else | |
{ | |
// End of line character received, terminate the string | |
rxBuffer[rxIndex] = '\0'; | |
// Copy the received string to the final storage | |
strcpy(receivedString, (const char *)rxBuffer); | |
// Print the received string over UART | |
HAL_UART_Transmit(&huart2, (uint8_t *)receivedString, strlen(receivedString), HAL_MAX_DELAY); | |
// Reset buffer and index for the next reception | |
rxIndex = 0; | |
memset(rxBuffer, 0, sizeof(rxBuffer)); | |
// Resume UART reception | |
HAL_UART_Receive_IT(&huart2, &rxData, 1); | |
} | |
} | |
} | |
int main(void) | |
{ | |
// HAL initialization code here | |
// Initialize UART with interrupt mode | |
HAL_UART_Init(&huart2); | |
// Start UART reception | |
HAL_UART_Receive_IT(&huart2, &rxData, 1); | |
while (1) | |
{ | |
// Your application code here | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment