0

How can I read the hex code of the main programme stored inside flash memory inside my running Arduino programme?

So far I am able to read the Flash at any given address by using PROGMEM

unsigned int displayInt;
int k;    // counter variable

void setup() {
  Serial.begin(9600);
  while (!Serial);  // wait for serial port to connect. Needed for native USB

  for(k = 0; k < 5; k++) {
    displayInt = pgm_read_word_near(k);
    Serial.println(displayInt); 
  }
}

void loop() {
}

The output is

37900
13716
53
3072
37900

But this not hex code.

I am implementing the OTA (over the air) feature. I will get the new version of a code from GPRS. It will be huge code so I will write it to flash by using the custom bootloader mentioned in this thread. I am able to write to the flash memory. Now I would like to read the data from flash. To begin with I would like to read the main programme inside my main programme.

1 Answer 1

5

Interesting. If you want hex you have to tell it to print in hex. If I change your display line to:

Serial.println(displayInt, HEX); 

Then I get:

940C
3594
35
C00
940C

Compare this to what the decompiled file looks like:

   0:   0c 94 35 00     jmp 0x6a    ; 0x6a <__ctors_end>
   4:   0c 94 5d 00     jmp 0xba    ; 0xba <__bad_interrupt>
   8:   0c 94 5d 00     jmp 0xba    ; 0xba <__bad_interrupt>

If you take the endianness into account (you are reading words, not bytes) then it is the same.


If you change it to read bytes it looks better:

void setup() {
  Serial.begin(115200);
  while (!Serial);  // wait for serial port to connect. Needed for native USB

  for(int k = 0; k < 12; k++) {
    byte c = pgm_read_byte(k);
    char buf [3];
    sprintf (buf, "%02X", c);
    Serial.println(buf); 
  }
}

void loop() {
}

I increased the baud rate to 115200. I'm always puzzled when people use 9600 baud. Do you hanker for the olden days, when 9600 baud modems were the fastest you could get?

That gives this result:

0C
94
35
00
0C
94
5D
00
0C
94
5D
00

As you can see, it is exactly correct.

1
  • Thanks. I am a frontend web developer trying to learn all of it(firmware development) at once. I don't know C very well. Thanks Commented May 11, 2018 at 9:38

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.