0

i need your help

i am trying atmega128a using AVR studio 7

but one problem is there

when i control DDRB and PORTB into main()

it works fine

but if i control DDRB and PORTB out of main()

if becomes error

'expected identifier or '(' before volatile'

i just want to know that why always handing DDRB and PORTB is only in main()

here is my code

#define F_CPU 14745600UL

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

DDRB = 0xFF;
PORTB = 0x00;

int main(void)
{
    /* Replace with your application code */

    PORTB = 0x01;
    _delay_ms(300);
    while (1) 
    {
        PORTB <<= 1;

        _delay_ms(300);

        if(PORTB == 0x80){
            PORTB = 0x01;
            _delay_ms(300);
        }
    }
}
David Grayson
  • 84,103
  • 24
  • 152
  • 189

2 Answers2

2

C is not a scripting language. Any line of code that actually runs must be inside a function. You can make a new function and call it from main.

David Grayson
  • 84,103
  • 24
  • 152
  • 189
  • but this code works in visual studio 2017 if you are right it might be not works in any other compiler and IDE plz help me – jongyoub lee Apr 20 '17 at 00:04
  • I don't believe that code works in Visual Studio. First of all, what would DDRD be defined as in VS? I already did help you in my answer by telling you how you can structure your C program. Are you having trouble following my suggestion? – David Grayson Apr 20 '17 at 00:27
  • Do you know how to write a new function and call it from `main`? Can you give it a try? – David Grayson Apr 20 '17 at 00:34
1

They need to be assigned inside of a function because they are macros that end up getting replaced with something that looks like this:

(*(volatile uint8_t *)<address>)

where <address> is a memory address that corresponds to the register that you are trying to access. You are trying to cast and dereference a pointer, which is not a valid operation outside of a function.