简体   繁体   中英

How to send an int over uint8_t data?

I'm using the RadioHead Packet Radio library from airspayce.com. In the example (nrf24_reliable_datagram_client & server) they let two nodes communicate with each other by sending strings back and forth. Now I want to send an int instead of a string there, and do something with this data. This is what they do in the example:

Define the buf byte.

uint8_t buf[RH_NRF24_MAX_MESSAGE_LEN];

This function receives the data:

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

Print the buf variable.

Serial.print((char*)buf);

So far so good.Now I want to do something like:

int value = (char*)buf;

Or:

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

But then I get:

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

Next to that, on the other side where I'm sending the data, I have:

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

When I'm printing this data on the receiver side, using the code from the first question, I get weird characters. So I thought, let's try:

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

But then I get:

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

What am I doing wrong? Thanks in advance!

You can't just assign an array to an integer and hope that it merges the elements together for you - for example, how does it know how to merge them?

For converting a uint16_t to a uint8_t[2] array you would want to do something like this:

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.

You could do it in other ways like using a union of a uint16_t with an array of two uint8_t's, but the above way is more portable. You could also do it by type casting the pointer to an int, however if one end uses big endian and the other uses little endian, that won't work unless you flip the data around in the array as you are receiving it.

For the receiver end, you would have:

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

Hopefully that helps.

Also, the 'overloaded prototype' is saying that no function exists which takes that particular set of input variables. From the print class header you will find there is however this prototype:

write(const uint8_t *buffer, size_t size);

which does what you want - print a specified number of uint8_t's from an array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM