如何使用UART从HC-06向stm32f103发送int?
我已使用蓝牙将 HC-06 连接到电脑,因此我能够向 HC-06 发送数据。 我的工作是将我在 PC 中输入的任何 int 发送到 bluepill (然后它将在另一个屏幕上显示该值)。我正在使用联合概念来做到这一点。
typedef union int_buffer
{
int i;
struct
{
uint8_t bytes[4];
};
}int_buff;
int_buff int_Tx; // Transmit to bluepill
uint8_t receive;
uint8_t send[50], buffer[5];
int counter = 0;
上面是我声明的变量。下面是我的代码:
/* USER CODE BEGIN WHILE */
while (1)
{
if(HAL_UART_Receive(&huart1, &receive, 1, HAL_MAX_DELAY) == HAL_OK) // Sending one by one
{
buffer[counter++] = receive;
}
if(buffer[counter - 1] == '\r')
{
HAL_GPIO_WritePin(GPIOC, GPIO_PIN_13, 0);
memcpy(int_Tx.bytes, buffer, sizeof(int));
sprintf((char* )send, "The integer received is %#X", int_Tx.i);
HAL_UART_Transmit(&huart2, send, sizeof(send), HAL_MAX_DELAY);
}
我已经知道 UART 正在逐字节发送。首先,我收集用户发送的所有字节并将它们存储到缓冲区中。当按下'\r'时,int将被传输到bluepill,它可以在serial studio上查看该值。我的问题是显示了一些值,但它们都是随机数和未知符号。
我不太确定我的概念正确与否。我认为它只是将每个字节存储到 union 中,然后打印出 union 的 int 。感谢您的帮助!
I have connect my HC-06 to pc using bluetooth, so i am able to send data to HC-06.
My work is to send any int I typed in PC to the bluepill (which will then display the value in another screen). I am doing this using union concept.
typedef union int_buffer
{
int i;
struct
{
uint8_t bytes[4];
};
}int_buff;
int_buff int_Tx; // Transmit to bluepill
uint8_t receive;
uint8_t send[50], buffer[5];
int counter = 0;
Above is variable I declared. Below is my code:
/* USER CODE BEGIN WHILE */
while (1)
{
if(HAL_UART_Receive(&huart1, &receive, 1, HAL_MAX_DELAY) == HAL_OK) // Sending one by one
{
buffer[counter++] = receive;
}
if(buffer[counter - 1] == '\r')
{
HAL_GPIO_WritePin(GPIOC, GPIO_PIN_13, 0);
memcpy(int_Tx.bytes, buffer, sizeof(int));
sprintf((char* )send, "The integer received is %#X", int_Tx.i);
HAL_UART_Transmit(&huart2, send, sizeof(send), HAL_MAX_DELAY);
}
I have already know that UART is sending bytes by bytes. Firstly, I collect all the bytes sent by user and store them into a buffer. When '\r' is pressed, the int is transmitted to bluepill, which can view the value on serial studio. My problem is that there are some value displayed but they are all random number and unknown symbol.
I am not so sure that my concept correct or not. I think it is just storing every bytes into union, then print out the int of union. Thx for the help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
除非您发送
int
的二进制表示形式,否则您不能仅将字节复制到联合并获取有意义的整数。在 ARM 上,数字 123 将表示为
{0x7b, 0x00, 0x00, 0x00}
(以字节为单位)。您可能想要做的是使用类似
atoi()< 的函数/代码>
。
我将重新安排您的代码如下:
更改
Unless you are sending a binary representation of
int
, you cannot just copy the bytes to a union and get a meaningful integer out.On ARM, number 123 would be represented as
{0x7b, 0x00, 0x00, 0x00}
in bytes.What you probably want to do is use a function like
atoi()
.I would re-arrange your code as below:
Changes
atoi()
to convert a string to int.