Programming microcontrollers in ASM or C & how it’s done

assemblyccomputer-architecturemicrocontroller

Just to clarify on these topics:

If I were to program a microcontroller in ASM I would use an assembler, of course. The assembler would compile the code into opcodes (machine code?)(generally 1:1 ratio) which would then be converted into HEX file. It is this file that is actually read into memory and used to program the controller? I read that the HEX file contains the actual location the data (part of that data frame) is to be stored in memory as well as the data to be written there.

If I were program a microcontroller in C (or some other language) what are the restrictions? It would be necessary that you use a C compiler, of course. But, is it that we must use a C compiler that is specifically designed to work with microcontrollers or a specific architecture?

I know that different architectures have varying instruction sets that are incompatible with others, but how is this dealt with and how does all this relate to a CPU that exists in a computer?

I have surely confused topics here and possibly embarrased muself, but I have been reading on these topics for a while today and wanted to clarify everything at one to mitigate further confusion.

Thank you,

Best Answer

A compiler can (for the purpose of your question) be divided in two parts:

  • The first part reads your code, analyzes it and checks it for errors, and does all kinds of clever things with it that have no relation with the target computer

  • The second part takes the output of the first part and translates it into a sequence of machine instructions (either in textual form, or in binary form, or both).

The second part is specific for the CPU on which your program must run. If you want to run on a PIC 16F, you must have a compiler that generates machine instructions for that specific chip, and often the compiler will need to know the exact chip for which you are compiling.

For an AVR, ARM, Cortex, MIPs, etc CPU you will need a different compiler. There are compilers that contain the second part (the back-end) for more than one target. In that case you must somehow specify which of the back-ends must be used.