July 20, 2013

Arduino: problems compiling sketches for ATMEGA168 vs ATMEGA328

I was struggling to find a solution to a compile problem, trying to recompile code originally written for an ATMEGA168 to an ATMEGA328, when I came to this post that saved me the day...

I had problems with #define PB2 and #define PC2 (and other similar one) that have been renamed for some reason...

ATMEGA8 and ATMEGA168 uses:
/hardware/tools/avr/avr/include/avr/iomx8.h include file,
while ATMEGA328 uses:
/hardware/tools/avr/avr/include/avr/iom328p.h instead.

For example:

for ATMEGA8 and ATMEGA168:
#define PORTB   _SFR_IO8 (0x05)
/* PORTB */
#define PB7     7
#define PB6     6
#define PB5     5
#define PB4     4
#define PB3     3
#define PB2     2
#define PB1     1
#define PB0     0


while for ATMEGA328:
#define PORTB _SFR_IO8(0x05)
#define PORTB0 0
#define PORTB1 1
#define PORTB2 2
#define PORTB3 3
#define PORTB4 4
#define PORTB5 5
#define PORTB6 6
#define PORTB7 7


or, for ATMEGA8 and ATMEGA168:
#define PORTC   _SFR_IO8 (0x08)
/* PORTC */
#define PC6     6
#define PC5     5
#define PC4     4
#define PC3     3
#define PC2     2
#define PC1     1
#define PC0     0


while for ATMEGA328:
#define PORTC _SFR_IO8(0x08)
#define PORTC0 0
#define PORTC1 1
#define PORTC2 2
#define PORTC3 3
#define PORTC4 4
#define PORTC5 5
#define PORTC6 6


Other differences are in the interrupt vectors: ATMEGA 8 and ATMEGA168 uses iomx8.h include file, while ATMEGA328 uses iom328p.h instead.