I am trying to send a string "hello" continiously through UART1 from Atmega 328P to the BLUEPILL board. I am doing the reception by by interrupt. The problem is after few times it starts to give "ello" "hello" alternatively on my serial monitor, I am not able to figure out whats going wrong. BAUD RATE-9600 parity bit- NONE STop bit- 1
main.c:
The usart_IRQ is called here under "usart code begin here":
#include "main.h"
#include "uart.h"
UART_HandleTypeDef huart1;
char *readBuffer;
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
static void MX_USART1_UART_Init(void);
int main(void)
{
HAL_Init();
SystemClock_Config();
MX_GPIO_Init();
MX_USART1_UART_Init();
/* USER CODE BEGIN 2 */
__HAL_UART_ENABLE_IT(&huart1, UART_IT_RXNE);
HAL_NVIC_SetPriority(USART1_IRQn, 0, 0);
HAL_NVIC_EnableIRQ(USART1_IRQn);
/* USER CODE END 2 */
The string received is stored in the "readBuffer" using the readstring and the printed to the serial monitor using the writestring forwhich i created a separate UART library.
while (1)
{
/* USER CODE END WHILE */
readBuffer=serialReadString1();
writeString1(readBuffer);
HAL_Delay(500);
/* USER CODE BEGIN 3 */
}
USART1_IRQHandler
I have enabled the Global interrupt and called the received function there, and used the return because I dont want to use the HAL_irq:
void USART1_IRQHandler(void)
{
/* USER CODE BEGIN USART1_IRQn 0 */
receivestring1();
return;
/* USER CODE END USART1_IRQn 0 */
HAL_UART_IRQHandler(&huart1);
/* USER CODE BEGIN USART1_IRQn 1 */
/* USER CODE END USART1_IRQn 1 */
}
uart.c
for write string:
#include"main.h"
#include "uart.h"
#define RX_BUFFER_SIZE1 144
char rxBuffer1[RX_BUFFER_SIZE1];
uint16_t rx1ReadPos;
void sendChar1( uint8_t ch)
{
while(!(USART1->SR & USART_SR_TXE));
USART1->DR = ch;
}
void writeString1(const char c[])
{
uint16_t i = 0;
for (i = 0; i<= strlen(c); i++)
{
sendChar1(c[i]);
}
memset(rxBuffer1,0,RX_BUFFER_SIZE1);
rx1ReadPos = 0;
}
for read string:
unsigned char receivedChar1(void)
{
while(!(USART1->SR & USART_SR_RXNE));//check whether any tx is going on
return USART1->DR;
}
void receivestring1()
{
while(!(USART1->SR & USART_SR_RXNE));//check whether any tx is going on
rxBuffer1[rx1ReadPos] = USART1->DR;
if (rxBuffer1[rx1ReadPos] != '\n')
{
rx1ReadPos++;
if (rx1ReadPos >= RX_BUFFER_SIZE1)
{
rx1ReadPos = 0;
}
}
}
char* serialReadString1()
{
return rxBuffer1;
}