本例使用DMA模式
一、USART 发送字串:
#include "main.h"
//
#include "string.h"
#include "stdio.h"
#include "stdlib.h"
#include "gpio.h"
//
char str[256] = {"bi1rfk"}; //自定义字串
uint8_t Tx_buff[256] = {0}; //UART Tx缓冲
void main(void)
{
//格式化字串,利用sprintf()函数, 需包换头文件 string.h
sprintf(Tx_buff, "my callsign is: %s\n", str);
//HAL串口输出
HAL_UART_Transmit_DMA(&huart1, Tx_buff , sizeof(Tx_buff));
}
-----------------------------------------
运行结果:my callsign is: bi1rfk
二、USART 发送浮点数
#include "main.h"
//
#include "string.h"
#include "stdio.h"
#include "stdlib.h"
#include "gpio.h"
//
uint8_t Tx_buff[256] = {0}; //UART Tx缓冲
float pi = 3.141592 //圆周率PI
void main(void)
{
//将浮点数PI转换为字符串,然后按字串方法发送
sprintf((char*)Tx_buff, "%f", pi);
//HAL串口发送
HAL_UART_Transmit_DMA(&huart1, (uint8_t*)Tx_buff , sizeof(Tx_buff));
}
-----------------------------------------
运行结果:3.141592
三、USART接收浮点数
#include "my_main.h"//
//
#include "string.h"
#include "stdio.h"
#include "stdlib.h"
#include "gpio.h"
//
char Rx_buff[256] = {0};
float x = 0.0;
int i = 0;
void main(void)
{
//接收浮点数形式的字串
HAL_UART_Receive_DMA(&huart1, (uint8_t*)Rx_buff, sizeof(Rx_buff));
//atof()将字串转换为浮点数, c语言标准函数库, 需包含头文件 stdlib.h
x = atof(Rx_buff);
//atoi()函数,字串转换为整数
i = atoi(Rx_buff);
}
---------------------------------