如何通过 uint8_t 发送 int 数据?

问题描述 投票:0回答:1

我正在使用airspayce.com 的RadioHead Packet Radio 库。在示例(nrf24_reliable_datagram_client & server)中,它们让两个节点通过来回发送字符串来相互通信。现在我想在那里发送一个 int 而不是一个字符串,并用这些数据做一些事情。这就是他们在示例中所做的:

定义buf字节。

uint8_t buf[RH_NRF24_MAX_MESSAGE_LEN];

该函数接收数据:

manager.recvfromAckTimeout(buf, &len, 500, &from)

打印 buf 变量。

Serial.print((char*)buf);

到目前为止一切顺利。现在我想做一些类似的事情:

int value = (char*)buf;

或者:

char value[10] = { (char*)buf };

但后来我得到:

invalid conversion from 'char*' to 'int' (or to 'char'...)

接下来,在我发送数据的另一边,我有:

uint8_t data[] = { analogRead(A0) };

当我使用第一个问题的代码在接收器端打印这些数据时,我得到了奇怪的字符。所以我想,让我们尝试一下:

Serial.print((char*)buf, DEC); // or BYTE

但后来我得到:

call of overloaded 'print(char*, int)' is ambiguous

我做错了什么?预先感谢!

string pointers arduino int uint8t
1个回答
0
投票

你不能只是将一个数组分配给一个整数,并希望它为你将元素合并在一起 - 例如,它如何知道如何合并它们?

要将 uint16_t 转换为 uint8_t[2] 数组,您需要执行以下操作:

uint16_t analog = analogRead(A0); //read in as int.
uint8_t data[2] = {analog, (analog >> 8)}; // extract as {lower byte, upper byte)
Serial.write(data,2); //write the two bytes to the serial port, lower byte first.

您可以通过其他方式来完成此操作,例如使用 uint16_t 与两个 uint8_t 数组的并集,但上述方式更便携。您也可以通过将指针类型转换为 int 来实现这一点,但是如果一端使用大端,另一端使用小端,则除非您在接收数据时翻转数组中的数据,否则这将不起作用。

对于接收端,您将拥有:

uint8_t data[2];
...
... //whatever you do to receive the bytes that were sent over serial.
...
//Now assuming that data[] contains the received bytes where:
//data[0] was the first in (lower byte) and data[1] was the second in (upper byte)
uint16_t merged = (data[1] << 8) | data[0]; //merge them back together

希望有帮助。

此外,“重载原型”表示不存在采用该特定输入变量集的函数。从打印类标题中你会发现有这个原型:

write(const uint8_t *buffer, size_t size);

它可以满足您的需求 - 从数组中打印指定数量的 uint8_t。

© www.soinside.com 2019 - 2024. All rights reserved.