Electronic – Will the same C code for an AVR microcontroller work with any other type

avrcmicrocontrollerprogramming

I'm learning about microcontrollers and have very limited knowledge on the subject.

I just know that one needs to set bits in the registers and manipulate them basically to make a uC work. The registers setup and control the electronics in the micro-controller.

Lets say I wrote a C code in Atmel Studio for a particular 8-bit uC. This uC has register names in its data-sheet like TCNT0 for instance. What if I want to use the same code with another 8-bit AVR? Should I write everything from scratch or just need to make little modifications? Are most of the register names in common?

For example, if I program an ATmega328P with C, would the same code work in any other 8-bit type for example with ATmega168? And if no, would you normally write it from scratch or just modify the previous one?

I'm confused about the code compatibility. How about same question for using 8-bit uC's code for a 32-bit uC like AVR32?

Best Answer

For example, if I program an ATmega328P with C, would the same code work in any other 8-bit type for example with ATmega168?

In that case, the answer happens to be yes. The only difference between the ATmega168P and 328P is the amount of flash memory -- so long as your program fits on the 168P (i.e, as long as it isn't larger than 16 KB), it'll run identically on that part.

In other cases… it depends. There are some subtle differences in peripherals and features across the AVR line, even in situations where peripherals have the same name. Compare the datasheets carefully for details.

How about same question for using 8-bit uC's code for a 32-bit uC like AVR32?

AVR32 is a completely different architecture from 8-bit AVR; they have almost nothing in common besides the name. So you'd probably have to rewrite your program.