内存映射接口,进一步的问题
我仍然有我的C code,它与内存映射设备涉及的一些问题。
此刻,我申报寄存器我写挥发地址空间
指针,如下图所示将数据写入其中:
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 write data to them as shown below:
volatile unsigned int *wr_register = (int *) 0x40000000;
volatile unsigned int *c_register = (int *) 0x40000100;
...
main{
*wr_register = 0x01234567;
*c_register = 0x01234567;
*(c_register+1) = 0x89abcdef;
}
本作品或多或少的罚款。不过,我想有特定的读取和
写与内存映射寄存器进行交互的功能。因此理想情况下,
它看起来是这样的:
This works more or less fine. However, I would like to have specific read and write functions that interact with the memory mapped registers. So ideally, it would look something like this:
const unsigned int wr_register = 0x40000000;
const unsigned int c_register = 0x40000100;
function write_REG(unsigned int address, int offset, int data)
{
(unsigned int*) (address + offset) = data;
}
main{
*write_REG(0x40000000, 0, 0x01234567);
*write_REG(0x40000100, 0, 0x01234567);
*write_REG(0x40000100, 1, 0x89abcdef);
}
我还没有尝试过了还没有说实话,但如果有人能我想知道
告诉我,如果这是做一个适当的方式?
I have not tried it out yet to be honest, but I am wondering if somebody could tell me if this is a proper way to do it?
编辑:也许这是用别人的,在这里我有我的功能,他们似乎工作。非常感谢为有益的意见!
Maybe it is of use for someone else, here I have my function and they seem to work. Many thanks for the helpful comments!
void reg_write(unsigned int address, int offset, int data)
{
*((volatile unsigned int*)address + offset) = data;
}
int reg_read(unsigned int address, int offset)
{
return(*((volatile unsigned int*)address + offset));
}
非常感谢
有您的code不少问题:
There are quite a few problems with your code:
- 我假设你的意思
无效
其中你写函数
。 - 您应该使指针的函数内部是
挥发性
以及 - 您应该取消引用指针写数据之前。在
*
应该是里面的功能,而不是在调用点(* WRITE_REG
),因为它是现在 - 这将是一个编译错误。 - 您应该添加的偏移量指针,而不是地址。这是因为偏移1,就是要在未来
INT
这可能是,比方说,4个字节了,但它添加到地址只会增加1个字节。
- I assume you meant
void
where you wrotefunction
. - You should make the pointer inside the function to be
volatile
as well. - 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. - 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;
}
和你这样调用它:
write_REG(0x40000000, 0, 0x01234567);