C语言 结构体、联合、位段
例如,有一些寄存器,寄存器有一些位,每个位都控制不同的设置,要是想单独设置某一个位的值,用位域就是一个比较好的方法,
位域可以无位域名,这时它只用来作填充或调整位置。无名的位域是不能使用的
比如
union _PWM_AUTO_Register{
long value;
struct {
uint16_t pwm_ofs_auto:8; // Automatically determined offset value
uint16_t :8;
uint16_t pwm_grad_auto:8; // Automatically determined gradient value
}PWM_AUTO_Register;
};
寄存器例子:
第一种方法:如果内存小的话可能造成堆栈溢出
union _GSTAT_Register { uint32_t value; struct GSTAT_Register *GSTAT_Register_bit; }; struct GSTAT_Register { uint8_t reset:1; // Indicates that the IC has been reset since the last read access to GSTAT uint8_t drv_err:1; // Indicates that the driver has been shut down due to overtemperature or short circuit detection since the last read access uint8_t uv_cp:1; // Indicates an undervoltage on the charge pump. The driver is disabled in this case. };
第二种方法:比第一种占用的更小
union _GSTAT_Register { uint32_t value; struct { uint8_t reset:1; // Indicates that the IC has been reset since the last read access to GSTAT uint8_t drv_err:1; // Indicates that the driver has been shut down due to overtemperature or short circuit detection since the last read access uint8_t uv_cp:1; // Indicates an undervoltage on the charge pump. The driver is disabled in this case. }GSTAT_Register; };
union _GSTAT_Register gstat = {0};//调用先出事化
gstat.GSTAT_Register.reset = 1;
gstat.GSTAT_Register.uv_cp =1;
sendData(GSTAT, gstat.value);
位段在使用中可能是从第零位开始0,1,2,3,4等,也可能是从最高位开始
union _DCCTRL_Register{ uint32_t value:24; struct { uint16_t dc_time:10, // Upper PWM on time limit for commutation :6, dc_sg:8; // Max. PWM on time for step loss detection using dcStep stallGuard2 in dcStep mode. }DCCTRL_Register; };
一串数字有6位是空的,可以忽略不写加上“:6”即为跳过6个字段,value总共占24位,可一位位操作
我这台是从零开始。
由于是一位一位操作所得到的数就是二进制数,不需要进制转换,与想传入的十进制数或者十六进制数一致。