I am trying to write a pice of code which send to a receiver the frequency to listen.
As per its documentation, it should receive the following sequence:
Example with 123.456 MHz
Command to send (frequency converted in 4 bytes, followed by 2 instruction bytes
0x12 0x23 0x56 0x00 0x01
To be able to memorize six frequencies, I fill an array:
uint32_t mem_freq[6] = {
0x121050,
0x126500,
0x120500,
0x121700,
0x121825,
0x118700,
};
My concern is that when I do :
Serial.write(mem_freq[mem_index]);
//Serial.write(0x00);
//Serial.write(0x01);
Only 1 byte is sent, and it's hard to debug as the serial console displays only ascii characters.
When I use Serial.print instead, mem_freq[2] shows correctly 0x120500
After Majenko's answer, I tried this:
Serial.print(0x123456 >> 16,HEX);
Serial.print(0x123456 >> 8,HEX);
Serial.print(0x123456,HEX);
Serial.print(0x00,HEX);
Serial.print(0x01,HEX);
And it outputs:
12123412345601
Is this normal ?
-
use Serial.print(value, HEX) to print on Serial Monitor in hex form arduino.cc/reference/en/language/functions/communication/serial/…Juraj– Juraj ♦2018年02月26日 18:32:09 +00:00Commented Feb 26, 2018 at 18:32
-
encoding 123.456 as 0x12 0x23 0x56 is very exotic. how do you use the frequency? I would send it as decimal number 123456. It fits into uint32_tJuraj– Juraj ♦2018年02月26日 18:36:45 +00:00Commented Feb 26, 2018 at 18:36
-
@Juraj, i think that the receiver hardware uses BCD and requires the above mentioned byte stream for correct operationjsotola– jsotola2018年02月26日 19:08:09 +00:00Commented Feb 26, 2018 at 19:08
2 Answers 2
You need to manually split your values into bytes. You can either do that by storing them as individual bytes (as shown by Ignacio), or by using bit shifting:
Serial.write(mem_freq[mem_index] >> 16);
Serial.write(mem_freq[mem_index] >> 8);
Serial.write(mem_freq[mem_index]);
That sends the bits 16-23 (0x12) then bits 8-15 (0x10) followed by bits 0-7 (0x50).
-
Thanks Majenko. I have edited my post to show the result in ascii, and it is strange...Jibeji– Jibeji2018年02月26日 20:33:52 +00:00Commented Feb 26, 2018 at 20:33
-
Since you have switched from
write
toprint
it can now print the entire number every time. If you want to print it you should also mask the value with& 0xFF
.Majenko– Majenko2018年02月26日 20:34:57 +00:00Commented Feb 26, 2018 at 20:34 -
Serial.print((0x123456 >> 16) & 0xFF,HEX);
Majenko– Majenko2018年02月26日 20:35:27 +00:00Commented Feb 26, 2018 at 20:35
That's because you need to use an array of arrays, and send three bytes.
uint32_t mem_freq[6][3] = {
{0x12, 0x10, 0x50},
...
};
...
Serial.write(mem_freq[mem_index], 3);
...