收不了消息(一)
发送消息,代码所写应该为接受后发送,但是并没有出现
int main(void)
{
HAL_Init();
SystemClock_Config();
MX_GPIO_Init();
MX_USART1_UART_Init();
uint8_t byte;
uint8_t len;
uint8_t buf[32]="";
while (1)
{
if(HAL_UART_Receive(&huart1,&byte,1,100)==HAL_OK)
{
if(byte=='\n')
{
HAL_UART_Transmit(&huart1,buf,len,100);
// printf("%s\n",buf);
memset(buf,0,sizeof(buf));
len=0;
}
else
buf[len++]=byte;
}
}
}
解决方法
uint8_t len;
int main(void)
{
uint8_t byte;
uint8_t buf[32]="";
HAL_Init();
SystemClock_Config();
MX_GPIO_Init();
MX_USART1_UART_Init();
while (1)
{
if(HAL_UART_Receive(&huart1,&byte,1,100)==HAL_OK)
{
if(byte=='\n')
{
HAL_UART_Transmit(&huart1,buf,len,100);
// printf("%s\n",buf);
memset(buf,0,sizeof(buf));
len=0;
}
else
buf[len++]=byte;
}
}
}
解决了,将变量定义为全局,细节上,可以只把len变量放在全局就行了
收不了消息(二)
uint8_t len;
int main(void)
{
uint8_t byte;
uint8_t buf[32]="";
HAL_Delay(500);
HAL_Init();
SystemClock_Config();
MX_GPIO_Init();
MX_USART1_UART_Init();
while (1)
{
if(HAL_UART_Receive(&huart1,&byte,1,100)==HAL_OK)
{
if(byte=='\n')
{
HAL_UART_Transmit(&huart1,buf,len,100);
// printf("%s\n",buf);
memset(buf,0,sizeof(buf));
len=0;
}
else
buf[len++]=byte;
}
}
}
解决方案
去掉第8行的HAL_Delay(500);
就解决了
乱码问题
用重定向实现,发现是乱码
//重定向
int fputc(int ch,FILE *F)
{
while(!(USART1->ISR & 1<<7)){}
USART1->TDR=ch;
return 0;
}
printf("hello\n");
解决方案
勾选Use Micro LIB