Skip to main content
1 of 4
0x29a
  • 481
  • 1
  • 7
  • 21

Strange proble when running atmega328 independently

I have two ATMEGA328's and I'm experiencing a very strange problem. I have a very simple code to blink a LED:

    #define F_CPU 8000000UL

    #include <avr/io.h>
    #include <util/delay.h>
    #include <stdlib.h>

    void delayms( uint16_t millis ) 
    {
            while ( millis ) 
            {
                    _delay_ms( 1 );
                    millis--;
            }
    }

    int main( void ) 
    {
            DDRD = 0b11111111;

            int interval = 1000;

            while ( 1 ) 
            {
                    PORTD = 0b11111111;
                    delayms( interval );
                    PORTD = 0b00000000;
                    delayms( interval );
            }

            return 0;
    }

And here is the Makefile:

    CC=/usr/bin/avr-gcc
    MEGA=328p
    CFLAGS=-g -Os -Wall -mcall-prologues -mmcu=atmega$(MEGA)
    OBJ2HEX=/usr/bin/avr-objcopy 
    PROG=/usr/bin/avrdude
    TARGET=blink

    program : $(TARGET).hex
            $(PROG) -c avrispv2 -p m$(MEGA) -P /dev/ttyACM2 -e
            $(PROG) -c avrispv2 -p m$(MEGA) -P /dev/ttyACM2 -U flash:w:$(TARGET).hex

    %.obj : %.o
            $(CC) $(CFLAGS) $< -o $@

    %.hex : %.obj
            $(OBJ2HEX) -R .eeprom -O ihex $< $@

    clean :
            rm -f *.hex *.obj *.o

The code works perfectly, but here's the strange part:

ATMEGA #1:

  • Works as expected when connected straight to the 5V source
  • Can't be programmed. avrdude: stk500v2_command(): command failed. Can't connect.

ATMEGA #2:

  • Works only through Arduino case. When connected straight to the 5V source, PORTD outputs nothing.
  • Can be programmed.

This mystery has happened so many times before. All I can think of is that it has something to do with the fuse bits or possibly the frequency is 'hardcoded' for one chip at 8Mhz for the other one 16Mhz. I was expecting that F_CPU defines it.

I don't want to use an external oscillator. Any hints on what's going on?

0x29a
  • 481
  • 1
  • 7
  • 21