? 参考Linux的regmap操作
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define BITS_PER_LONG 64 // 64 bit CPU
//#define BITS_PER_LONG 32 // 32b it CPU
#define GENMASK(h, l) (((~0UL) << (l)) & (~0UL >> (BITS_PER_LONG - 1 - (h))))
unsigned int sys_val[2] = {0}; // array[] support mult;
//unsigned int sys_val = 0x33;
struct reg_field {
unsigned int reg;
unsigned int lsb;
unsigned int msb;
};
#define REG_FIELD(_reg, _lsb, _msb) { \
.reg = _reg, \
.lsb = _lsb, \
.msb = _msb, \
}
enum test_fields {
F_MCU_IS_BUSY,
F_TEST1,
F_TEST2,
F_MCU_IS_PRINT,
F_A1,
F_MAX_FIELDS
};
static const struct reg_field test_reg_fields[] = {
[F_MCU_IS_BUSY] = REG_FIELD(0, 0, 1), // bit[1:0] array[0]
[F_TEST1] = REG_FIELD(0, 2, 2), // bit[2]
[F_TEST2] = REG_FIELD(0, 3, 3), // bit[3]
[F_MCU_IS_PRINT] = REG_FIELD(0, 4, 5), // bit[5:4]
[F_A1] = REG_FIELD(1, 16, 31), // bit[31:16] ; array[1]
};
int set_bit(enum test_fields field_id, unsigned int val)
{
printf("%s ", __FUNCTION__);
unsigned int field_shift, field_mask;
unsigned int mask = ~0;
int tmp_val = val;
field_shift = test_reg_fields[field_id].lsb;
field_mask = GENMASK(test_reg_fields[field_id].msb, test_reg_fields[field_id].lsb);
mask = (mask << field_shift) & field_mask;
tmp_val <<= field_shift;
printf("field_shift=0x%x, field_mask=0x%x, mask=0x%x, ", field_shift, field_mask, mask);
sys_val[test_reg_fields[field_id].reg] &= ~mask;
sys_val[test_reg_fields[field_id].reg] |= tmp_val & mask;
val = sys_val[test_reg_fields[field_id].reg];
printf("sys = 0x%x\n", val);
return 0;
}
int get_bit(enum test_fields field_id, unsigned int *val)
{
printf("%s ", __FUNCTION__);
unsigned int reg_val;
unsigned int field_shift, field_mask;
field_shift = test_reg_fields[field_id].lsb;
field_mask = GENMASK(test_reg_fields[field_id].msb, test_reg_fields[field_id].lsb);
reg_val = sys_val[test_reg_fields[field_id].reg];
printf("field_shift=0x%x, field_mask=0x%x, ", field_shift, field_mask);
reg_val &= field_mask; printf("reg=0x%x ", reg_val);
reg_val >>= field_shift; printf("reg=0x%x ", reg_val);
*val = reg_val;
printf("val=0x%x\n", *val);
}
int clear_bit(enum test_fields field_id)
{
set_bit(field_id, 0x00);
}
int main()
{
unsigned int val;
val = 0x3;
set_bit(F_MCU_IS_BUSY, val);
val = 1;
set_bit(F_TEST1, val);
set_bit(F_TEST2, val);
clear_bit(F_TEST2);
val = 0x2;
set_bit(F_MCU_IS_PRINT, val);
printf("0x%x\n", sys_val[test_reg_fields[F_MCU_IS_PRINT].reg]);
get_bit(F_MCU_IS_BUSY, &val);
get_bit(F_TEST1, &val);
get_bit(F_TEST2, &val);
get_bit(F_MCU_IS_PRINT, &val);
printf("\nArray 2 \n");
val = 0xFFFF;
set_bit(F_A1, val);
get_bit(F_A1, &val);
printf("0x%x\n", sys_val[test_reg_fields[F_A1].reg]);
}
.
|