accessing AVR registers with C? [closed]

假如想象 提交于 2021-01-29 11:19:38

问题


I've been trying to learn everything I can about micro-controllers lately. Since this is self-study, it's taken me a while to learn how the things work at the bare metal. Long story short, I don't want to use the AVR libraries in my C code; I want to access the registers specifically through their addresses using pointers in C. I've searched everywhere online, looked inside the AVR header files, and read a book. If someone could help me out that would be wonderful.


回答1:


You can cast from an integer to a pointer. It's just a normal cast expression.

volatile char * const port_a = (volatile char *) 0x1B;

Many compilers provide extensions to instruct the linker to place an object at a specific address:

volatile char port_a @ 0x1B; // Or something like this

The advantage is that you don't introduce a global variable to represent the pointer, but it might not do the right thing for a hardware register. You need to read carefully your compiler's manual for your specific platform.

The official AVR headers probably contain something more like this:

#define PORTA (* (volatile char *) 0x1B)

This avoids the global variable and the linker hack, but many also consider using the preprocessor also to be hacking.

The only viable solution for production code is to use the official headers. Anything else is only instructional.




回答2:


It pretty much depends on the compiler, some use a stricter interpretation of the register keyword.

For example,

unsigned char a @0x0001; will put the variable into the specific register.

Otherwise, you could just assign numeric values to your pointers, it's a big no-no if your program runs in an OS, but if you have a guaranteed physical memory which you know the boundaries of, it might be acceptable. However, care must be taken that the compiler does not use that register automatically, which is a hard thing to make sure unless you write most of your code in Assembly.

So, the variable declaration method (if your compiler supports it) is the better choice, as it guarantees that no other variable will take up its place.



来源:https://stackoverflow.com/questions/24988522/accessing-avr-registers-with-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!