访问内存映射寄存器
Accessing memory mapped register
假设在地址0x1ffff670处有一个内存映射设备。设备寄存器只有 8 位。我需要获取该寄存器中的值并递增 1 并写回。
以下是我的方法,
记忆中的场景大概是这样的。
void increment_reg(){
int c;//to save the address read from memory
char *control_register_ptr= (char*) 0x1ffff670;//memory mapped address. using char because it is 8 bits
c=(int) *control_register_ptr;// reading the register and save that to c as an integer
c++;//increment by one
*control_register_ptr=c;//write the new bit pattern to the control register
}
这种做法正确吗?非常感谢。
您的方法几乎是正确的。唯一缺少的部分 - 正如问题评论中指出的那样 - 是向指针类型添加 volatile
,如下所示:
volatile unsigned char * control_register_ptr = ...
我也会unsigned char
,因为这通常更合适,但这基本上没有太大区别(唯一有意义的区别是在向下移动值时。)
volatile
关键字向编译器发出信号,表明该地址处的值可能会从程序外部更改(即通过编译器看不到和不知道的代码)。这将使例如,编译器在优化加载和存储方面更加保守。
假设在地址0x1ffff670处有一个内存映射设备。设备寄存器只有 8 位。我需要获取该寄存器中的值并递增 1 并写回。
以下是我的方法,
记忆中的场景大概是这样的。
void increment_reg(){
int c;//to save the address read from memory
char *control_register_ptr= (char*) 0x1ffff670;//memory mapped address. using char because it is 8 bits
c=(int) *control_register_ptr;// reading the register and save that to c as an integer
c++;//increment by one
*control_register_ptr=c;//write the new bit pattern to the control register
}
这种做法正确吗?非常感谢。
您的方法几乎是正确的。唯一缺少的部分 - 正如问题评论中指出的那样 - 是向指针类型添加 volatile
,如下所示:
volatile unsigned char * control_register_ptr = ...
我也会unsigned char
,因为这通常更合适,但这基本上没有太大区别(唯一有意义的区别是在向下移动值时。)
volatile
关键字向编译器发出信号,表明该地址处的值可能会从程序外部更改(即通过编译器看不到和不知道的代码)。这将使例如,编译器在优化加载和存储方面更加保守。