I transmit 256 bytes from stm32 and receive it by SerialPort in Visual studio. Why i receive bytes 2 times? 32 and then 224.
stm32 USART configuration:
huart2.Instance = USART2;
huart2.Init.BaudRate = 9600;
huart2.Init.WordLength = UART_WORDLENGTH_8B;
huart2.Init.StopBits = UART_STOPBITS_1;
huart2.Init.Parity = UART_PARITY_NONE;
huart2.Init.Mode = UART_MODE_TX_RX;
huart2.Init.HwFlowCtl = UART_HWCONTROL_NONE;
huart2.Init.OverSampling = UART_OVERSAMPLING_16;
huart2.Init.OneBitSampling = UART_ONE_BIT_SAMPLE_DISABLE;
huart2.Init.ClockPrescaler = UART_PRESCALER_DIV1;
huart2.AdvancedInit.AdvFeatureInit = UART_ADVFEATURE_NO_INIT;
uint8_t memory[256];
for (int i = 0; i < 256; i++)
memory[i] = 0xFF;
HAL_UART_Transmit(&huart2, memory, sizeof(memory), HAL_MAX_DELAY);
Visual studio:
private void readerSerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
if (!this.readerSerialPort.IsOpen) return;
int bytes = this.readerSerialPort.BytesToRead;
byte[] buffer = new byte[bytes];
this.readerSerialPort.Read(buffer, 0, bytes);
MessageBox.Show(buffer.Length.ToString());
}
Why is this happening?
The serial protocol as well as USB bulk endpoints, which are likely used between the microcontroller and your PC are stream protocols. They assume a constant flow of bytes and do not use delimiters to transmit the boundaries of the original data chunks.
This is opposed to message-oriented protocol that transmit and retain distinct chunks of data.
As a consequence, the size of the chunks you used to submit the data are not retained. Multiple chunks might be joined into a single one, and a single chunk might be split into multiple ones as you have experienced.
If you require a message-oriented protocol, you need to implemented it yourself on top of the stream protocol. Typical approaches are: