Further question with memory mapped interface

前端 未结 2 650
小鲜肉
小鲜肉 2021-01-26 18:55

I still have some issues with my c code that deals with an memory mapped device. At the moment I declare the address space for the registers I write as volatile pointer and I wr

相关标签:
2条回答
  • 2021-01-26 19:35

    There are quite a few problems with your code:

    1. I assume you meant void where you wrote function.
    2. You should make the pointer inside the function to be volatile as well.
    3. You should dereference the pointer before writing the data. The * should be inside the function, not at the call site (*write_REG) as it is now - that would be a compile error.
    4. You should add the offset to the pointer, not the address. This is because an offset of 1 is meant to be the next int which could be, say, 4 bytes away, but adding it to the address will only add 1 byte.

    Your corrected function should look like this:

    void write_REG(unsigned int address, int offset, int data)
    {
        *((volatile unsigned int*)address + offset) = data;
    }
    

    and you would call it like:

    write_REG(0x40000000, 0, 0x01234567);
    
    0 讨论(0)
  • 2021-01-26 19:38

    That would be just fine IMHO. I sometimes use macros like:

    #define WR_REG     *(volatile unsigned int*)0x40000000
    

    This allows the registers to be used sort of like variables:

    WR_REG = 0x12345678;
    
    0 讨论(0)
提交回复
热议问题