- #include
-
- #define ENUM_VAR_U8(v) v
- #define ENUM_VAR_U16(v) v,v##__end=v+1
- #define ENUM_VAR_U24(v) v,v##__end=v+2
- #define ENUM_VAR_U32(v) v,v##__end=v+3
-
- #define ENUM_VAR_U8e(v,e) v=e
- #define ENUM_VAR_U16e(v,e) v=e,v##__end=v+1
- #define ENUM_VAR_U24e(v,e) v=e,v##__end=v+2
- #define ENUM_VAR_U32e(v,e) v=e,v##__end=v+3
-
-
- //用户自定义变量名字,用于存储
- typedef enum
- {
- ENUM_VAR_U8e(first_member,0),//first_member = 0,//首元素
- ENUM_VAR_U16(my_varA),
- ENUM_VAR_U24(my_varB),
- ENUM_VAR_U32(my_varC),
- MAX_VAR_LEN,//===Keep this enum last===
- }TagEnumVar;
-
- uint8_t g_var[MAX_VAR_LEN];//此数组作为全局变量,用于file/flash读写。
-
- void get_var(TagEnumVar id,void* value_out,uint8_t var_bytes )
- {
- if(var_bytes==1)
- {
- uint8_t *value_ex =(uint8_t*)value_out;
- *value_ex = g_var[id];
- }
- else if(var_bytes==2)
- {
- uint16_t *value_ex =(uint16_t*)value_out;
- *value_ex = g_var[id] | (g_var[id+1]<<8);
- }
- else if(var_bytes==3)
- {
- uint32_t *value_ex =(uint32_t*)value_out;
- *value_ex = g_var[id] | (g_var[id+1]<<8) | (g_var[id+2]<<16);
- }
- else if(var_bytes==4)
- {
- uint32_t *value_ex =(uint32_t*)value_out;
- *value_ex = g_var[id] | (g_var[id+1]<<8) | (g_var[id+2]<<16)| (g_var[id+3]<<24);
- }
-
- }
-
- void set_var(TagEnumVar id,uint32_t value_in,uint8_t var_bytes )
- {
- if(var_bytes==0)
- return;
-
- if(var_bytes>=1)
- g_var[id]=(value_in)&0xFF;
- if(var_bytes>=2)
- g_var[id+1]=(value_in>>8)&0xFF;
- if(var_bytes>=3)
- g_var[id+2]=(value_in>>16)&0xFF;
- if(var_bytes>=4)
- g_var[id+3]=(value_in>>24)&0xFF;
-
- }
-
-
- int main()
- {
- printf("=======C_BuildTime=[%s_%s]==============\r\n\r\n",__DATE__ ,__TIME__ );
-
- //note:可以追加上电后,从file/flash加载数据到g_var里作为初始值
-
- uint8_t u8_in = 0x11;
- uint8_t u8_ot = 0x00;
-
- uint16_t u16_in = 0x1234;
- uint16_t u16_ot = 0x00;
-
- uint32_t u24_in = 0x123456;
- uint32_t u24_ot = 0x00;
-
- uint32_t u32_in = 0x12345678;
- uint32_t u32_ot = 0x00;
-
- //先将数据写入,然后读出来看看是否一致
-
- set_var(first_member,(uint32_t)u8_in,1);
- get_var(first_member,&u8_ot,1);
- printf("get u8,first_member=0x%x.\n",u8_ot);//测试1字节变量的读和写
-
- set_var(my_varA,(uint32_t)u16_in,2);
- get_var(my_varA,&u16_ot,2);
- printf("get u16,my_varA=0x%x.\n",u16_ot);//测试2字节变量的读和写
-
- set_var(my_varB,(uint32_t)u24_in,3);
- get_var(my_varB,&u24_ot,3);
- printf("get u24,my_varB=0x%x.\n",u24_ot);//测试3字节变量的读和写
-
-
- set_var(my_varC,(uint32_t)u32_in,4);
- get_var(my_varC,&u32_ot,4);
- printf("get u32,my_varC=0x%x.\n",u32_ot);//测试4字节变量的读和写
-
- //note:可以追加,关闭程序前,保存g_var数据到对应的file/flash里
- return 0;
- }
运行效果:[注意变量的位数]
注:C语言的文件读写可以参考: