Printing a unsigned long variable

After measuring the frequency I get a 3 Byte variable (unsigned long freq) an I want to printed via serial monitor. But only the lower 16 bits are printed. I guess the binary to decimal routine uses only 16 bit even when the variable is declared long. How can I manage to get all 24 bits converted and printed?

You don't tell us which board, so I assume an Uno (or other 8-bit ATmega).

There a long is 4 bytes, not three. And the print routine is just fine in printing that, no problem :) So the error most be in your, not posted, code. And/or your understanding of 3 byte being a long. :)

Sounds like you try to store your 32-bit long in a 16-bit int.

The associated libraries take some space but sprintf() makes formatting trivial:

char
    szStr[20];
unsigned long
    ulTest;

void setup()
{
    Serial.begin( 9600 );
    ulTest = 0x5A0F;
    sprintf( szStr, "%04X\t%ld", ulTest, ulTest );
    Serial.println( szStr );

}//setup

void loop()
{
    
}//loop

I know it's been a while, but people finding this code will be disappointed. The code supplied (specifically the sprintf( szStr, "%04X\t%ld", ulTest, ulTest ); line) fails on three counts:

  • It only prints 4 hex digits rather than eight
  • The hex formatting assumes an int rather than any sort of long
  • The number itself assumes a signed long rather than unsigned long

This can be fixed by replacing the sprintf line with

sprintf( szStr, "%08lX\t%lu", ulTest, ulTest );