char 和 unsigned char 的区别(解决串口通信中文乱码问题)
C语言中的基本数据类型
在C语言中有6种基本数据类型:short、int、long、float、double、char
整型:short、int、long
浮点型:float、double
字符型:char
1. <stdint.h> 数据类型定义
F1 系列标准库<stdint.h>中
typedef unsigned char uint8_t;
typedef unsigned short int uint16_t;
typedef signed short int int16_t;
char (int8_t)取值范围-128 ~ 128
unsigned char (uint8_t)取值范围0 ~ 255 (FF)
unsigned short int(uint16_t) 取值范围0 ~ 65535
signed short int(int16_t)取值范围-3278 ~ 32767
ASCII码取值范围0 ~ 127
2. 注意事项
- STD标准库中USART发送函数原型中:发送数据类型是uint16_t,接收数据类型也是uint16_t
- 字符型数据类型是char
- 写入USART串口的数据类型应当是以uint16_t形式存放在一个设定好的缓冲区用作后续处理,切勿写成uint8_t、char等类型,防止数据编解码出现异常乱码。
- uint8_t转uint16_t不会乱码,反之则未必。
//发送数据原函数
/**
* @brief Transmits single data through the USARTx peripheral.
* @param USARTx: Select the USART or the UART peripheral.
* This parameter can be one of the following values:
* USART1, USART2, USART3, UART4 or UART5.
* @param Data: the data to transmit.
* @retval None
*/
void USART_SendData(USART_TypeDef* USARTx, uint16_t Data)
{
/* Check the parameters */
assert_param(IS_USART_ALL_PERIPH(USARTx));
assert_param(IS_USART_DATA(Data));
/* Transmit Data */
USARTx->DR = (Data & (uint16_t)0x01FF);
}
//接收数据原函数
/**
* @brief Returns the most recent received data by the USARTx peripheral.
* @param USARTx: Select the USART or the UART peripheral.
* This parameter can be one of the following values:
* USART1, USART2, USART3, UART4 or UART5.
* @retval The received data.
*/
uint16_t USART_ReceiveData(USART_TypeDef* USARTx)
{
/* Check the parameters */
assert_param(IS_USART_ALL_PERIPH(USARTx));
/* Receive Data */
return (uint16_t)(USARTx->DR & (uint16_t)0x01FF);
}

浙公网安备 33010602011771号