0

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 ?

3
  • use Serial.print(value, HEX) to print on Serial Monitor in hex form arduino.cc/reference/en/language/functions/communication/serial/…
    – Juraj
    Commented 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_t
    – Juraj
    Commented Feb 26, 2018 at 18:36
  • @Juraj, i think that the receiver hardware uses BCD and requires the above mentioned byte stream for correct operation
    – jsotola
    Commented Feb 26, 2018 at 19:08

2 Answers 2

1

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).

3
  • Thanks Majenko. I have edited my post to show the result in ascii, and it is strange...
    – Jibeji
    Commented Feb 26, 2018 at 20:33
  • Since you have switched from write to print it can now print the entire number every time. If you want to print it you should also mask the value with & 0xFF.
    – Majenko
    Commented Feb 26, 2018 at 20:34
  • Serial.print((0x123456 >> 16) & 0xFF,HEX);
    – Majenko
    Commented Feb 26, 2018 at 20:35
0

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);
 ...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.